From 5b87db0ed23231db1ccf8c037eaa7eda317afe4f Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Wed, 27 Mar 2024 17:40:32 +0100 Subject: [PATCH 01/15] Update action-download-artifact to v3 Signed-off-by: Irene Bandera --- .github/workflows/build_eprosima_dependencies.yml | 4 ++-- .github/workflows/test.yml | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build_eprosima_dependencies.yml b/.github/workflows/build_eprosima_dependencies.yml index 21ab38fa..635455bb 100644 --- a/.github/workflows/build_eprosima_dependencies.yml +++ b/.github/workflows/build_eprosima_dependencies.yml @@ -76,7 +76,7 @@ jobs: ddsrouter_branch: ${{ github.event.inputs.ddsrouter_branch || env.DEFAULT_DDSROUTER_BRANCH }} - name: Upload binaries - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: windows_${{ matrix.cmake-config }}_eprosima_dependencies_install path: ${{ github.workspace }}\eprosima\install @@ -137,7 +137,7 @@ jobs: colcon build --event-handlers=console_direct+ - name: Upload binaries - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: ubuntu_eprosima_dependencies_install path: install diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b1f56090..fff47f44 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -59,7 +59,7 @@ jobs: select -first 1 id | % { "fastdds_job_id=" + $_.id } | Out-File $env:GITHUB_ENV -Append - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@v3 with: workflow: build_eprosima_dependencies.yml path: ${{ github.workspace }}\..\eprosima\install @@ -132,7 +132,7 @@ jobs: echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@v3 with: workflow: build_eprosima_dependencies.yml path: /home/runner/work/eprosima/install @@ -260,7 +260,7 @@ jobs: echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@v3 with: workflow: build_eprosima_dependencies.yml path: /home/runner/work/eprosima/install @@ -356,7 +356,7 @@ jobs: echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@v3 with: workflow: build_eprosima_dependencies.yml path: /home/runner/work/eprosima/install @@ -437,7 +437,7 @@ jobs: echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@v3 with: workflow: build_eprosima_dependencies.yml path: /home/runner/work/eprosima/install @@ -523,7 +523,7 @@ jobs: echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@v3 with: workflow: build_eprosima_dependencies.yml path: /home/runner/work/eprosima/install From 916da70aa3484629ccedd112882e55aa073b7930 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Mon, 1 Apr 2024 08:32:26 +0200 Subject: [PATCH 02/15] Use eProsima-CI Signed-off-by: Irene Bandera --- .../actions/install-apt-packages/action.yml | 25 - .../action.yml | 103 --- .../action.yml | 35 - .../action.yml | 30 - .../actions/install-gtest-linux/action.yml | 21 - .../actions/install-gtest-windows/action.yml | 20 - .../install-openssl-windows/action.yml | 10 - .../action.yml | 9 - .../action.yml | 12 - .../install-subpackage-windows/action.yml | 25 - .../install-yamlcpp-windows/action.yml | 19 - .../actions/project_dependencies/action.yml | 95 +++ .github/actions/run-test-ubuntu/action.yml | 21 - .../run-test-windows-python/action.yml | 14 - .github/actions/run-test-windows/action.yml | 16 - .github/workflows/asan_colcon.meta | 15 - .../workflows/build_eprosima_dependencies.yml | 143 ---- .github/workflows/ci.repos | 25 - .github/workflows/clang_colcon.meta | 23 - .../configurations/Linux/colcon.meta | 5 + .../configurations/Windows/colcon.meta | 23 + .github/workflows/docs_colcon.meta | 12 - .github/workflows/setup.cfg | 6 - .github/workflows/test.yml | 786 ++++-------------- .github/workflows/test_colcon.meta | 24 - 25 files changed, 288 insertions(+), 1229 deletions(-) delete mode 100644 .github/actions/install-apt-packages/action.yml delete mode 100644 .github/actions/install-eprosima-dependencies-windows/action.yml delete mode 100644 .github/actions/install-eprosima-multipackage-windows/action.yml delete mode 100644 .github/actions/install-eprosima-package-windows/action.yml delete mode 100644 .github/actions/install-gtest-linux/action.yml delete mode 100644 .github/actions/install-gtest-windows/action.yml delete mode 100644 .github/actions/install-openssl-windows/action.yml delete mode 100644 .github/actions/install-python-packages-windows/action.yml delete mode 100644 .github/actions/install-subpackage-windows-python/action.yml delete mode 100644 .github/actions/install-subpackage-windows/action.yml delete mode 100644 .github/actions/install-yamlcpp-windows/action.yml create mode 100644 .github/actions/project_dependencies/action.yml delete mode 100644 .github/actions/run-test-ubuntu/action.yml delete mode 100644 .github/actions/run-test-windows-python/action.yml delete mode 100644 .github/actions/run-test-windows/action.yml delete mode 100644 .github/workflows/asan_colcon.meta delete mode 100644 .github/workflows/build_eprosima_dependencies.yml delete mode 100644 .github/workflows/ci.repos delete mode 100644 .github/workflows/clang_colcon.meta create mode 100644 .github/workflows/configurations/Linux/colcon.meta create mode 100644 .github/workflows/configurations/Windows/colcon.meta delete mode 100644 .github/workflows/docs_colcon.meta delete mode 100644 .github/workflows/setup.cfg delete mode 100644 .github/workflows/test_colcon.meta diff --git a/.github/actions/install-apt-packages/action.yml b/.github/actions/install-apt-packages/action.yml deleted file mode 100644 index 9c5c3fe5..00000000 --- a/.github/actions/install-apt-packages/action.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: 'install-apt-packages' -description: 'Install necessary apt packages' -runs: - using: "composite" - steps: - - id: install-apt-packages - run: | - sudo apt update && sudo apt -y install \ - clang-tidy \ - curl \ - doxygen \ - graphviz \ - grep \ - imagemagick \ - libasio-dev \ - libtinyxml2-dev \ - libyaml-cpp-dev \ - lcov \ - python3 \ - python3-pip \ - python3-sphinxcontrib.spelling \ - python3-venv \ - software-properties-common \ - wget - shell: bash diff --git a/.github/actions/install-eprosima-dependencies-windows/action.yml b/.github/actions/install-eprosima-dependencies-windows/action.yml deleted file mode 100644 index 02148a5e..00000000 --- a/.github/actions/install-eprosima-dependencies-windows/action.yml +++ /dev/null @@ -1,103 +0,0 @@ -name: Install eProsima dependencies -description: Install and setup foonatham-memory, Fast CDR and Fast DDS for linking and building applications in Windows -inputs: - cmake_build_type: - description: 'Specifies the build type on single-configuration generators' - required: true - default: 'Release' - foonathan_memory_vendor_branch: - description: 'Branch or tag of eProsima/foonathan_memory_vendor repository (https://github.com/eProsima/foonathan_memory_vendor)' - required: true - default: 'master' - fastcdr_branch: - description: 'Branch or tag of eProsima/Fast-CDR repository (https://github.com/eProsima/Fast-CDR)' - required: true - default: 'master' - fastdds_branch: - description: 'Branch or tag of Fast DDS repository (https://github.com/eProsima/Fast-DDS)' - required: true - default: 'master' - utils_branch: - description: 'Branch or tag of Dev Utils repository (https://github.com/eProsima/dev-utils)' - required: true - default: 'main' - ddspipe_branch: - description: 'Branch or tag of DDS Pipe repository (https://github.com/eProsima/DDS-Pipe)' - required: true - default: 'main' - ddsrouter_branch: - description: 'Branch or tag of DDS Router repository (https://github.com/eProsima/DDS-Router)' - required: true - default: 'main' -runs: - using: composite - steps: - - name: Install foonatham memory - shell: pwsh - run: > - git clone --recurse-submodules --branch v0.6-2 https://github.com/foonathan/memory.git; - cmake -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}\eprosima\install ` - -DBUILD_SHARED_LIBS=OFF -DFOONATHAN_MEMORY_BUILD_TOOLS=ON -DCMAKE_POSITION_INDEPENDENT_CODE=ON ` - -DFOONATHAN_MEMORY_BUILD_TESTS=OFF -Ax64 -T host=x64 -B build\memory memory; - cmake --build build\memory --config ${{ inputs.cmake_build_type }} --target install - - - name: Install Fast CDR - shell: pwsh - run: > - git clone https://github.com/eProsima/Fast-CDR.git --branch ${{ inputs.fastcdr_branch }}; - cmake -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}\eprosima\install ` - -DCMAKE_PREFIX_PATH=${{ github.workspace }}\eprosima\install ` - -Ax64 -T host=x64 -B build\fastcdr Fast-CDR; - cmake --build build\fastcdr --config ${{ inputs.cmake_build_type }} --target install - - - name: Install Fast DDS - shell: pwsh - run: > - git clone https://github.com/eProsima/Fast-DDS.git --branch ${{ inputs.fastdds_branch }}; - cmake -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}\eprosima\install ` - -DCMAKE_PREFIX_PATH=${{ github.workspace }}\eprosima\install ` - -DTHIRDPARTY=ON -DSECURITY=ON -DCOMPILE_EXAMPLES=OFF -DEPROSIMA_BUILD_TESTS=OFF ` - -DINTERNAL_DEBUG=ON -Ax64 -T host=x64 -B build\fastdds Fast-DDS; - cmake --build build\fastdds --config ${{ inputs.cmake_build_type }} --target install - - - name: Install Dev Utils - shell: pwsh - run: > - git clone https://github.com/eProsima/dev-utils.git --branch ${{ inputs.utils_branch }}; - "cmake_utils cpp_utils".Split(" ") | ForEach { - echo "building package: $_"; - cmake -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}\eprosima\install ` - -DCMAKE_PREFIX_PATH=${{ github.workspace }}\eprosima\install ` - -Ax64 -T host=x64 -B build\$_ dev-utils/$_; - cmake --build build\$_ --config ${{ inputs.cmake_build_type }} --target install; - } - - - name: Install DDS Pipe - shell: pwsh - run: > - git clone https://github.com/eProsima/DDS-Pipe.git --branch ${{ inputs.ddspipe_branch }}; - "ddspipe_core;ddspipe_core ddspipe_participants;ddspipe_participants".Split(" ") | ForEach { - $subpackage_arr =$_.Split(";") - $subpackage= $subpackage_arr[0] - $subpackage_dir= $subpackage_arr[1] - echo "building package: $subpackage"; - cmake -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}\eprosima\install ` - -DCMAKE_PREFIX_PATH='C:\Program Files\yamlcpp;${{ github.workspace }}\eprosima\install' ` - -Ax64 -T host=x64 -B build\$subpackage DDS-Pipe/$subpackage_dir; - cmake --build build\$subpackage --config ${{ inputs.cmake_build_type }} --target install; - } - - - name: Install DDS Router - shell: pwsh - run: > - git clone https://github.com/eProsima/DDS-Router.git --branch ${{ inputs.ddsrouter_branch }}; - "ddsrouter_core;ddsrouter_core".Split(" ") | ForEach { - $subpackage_arr =$_.Split(";") - $subpackage= $subpackage_arr[0] - $subpackage_dir= $subpackage_arr[1] - echo "building package: $subpackage"; - cmake -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}\eprosima\install ` - -DCMAKE_PREFIX_PATH='C:\Program Files\yamlcpp;${{ github.workspace }}\eprosima\install' ` - -Ax64 -T host=x64 -B build\$subpackage DDS-Router/$subpackage_dir; - cmake --build build\$subpackage --config ${{ inputs.cmake_build_type }} --target install; - } diff --git a/.github/actions/install-eprosima-multipackage-windows/action.yml b/.github/actions/install-eprosima-multipackage-windows/action.yml deleted file mode 100644 index 75708a9f..00000000 --- a/.github/actions/install-eprosima-multipackage-windows/action.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Install eProsima Multiple Packages -description: Install and setup a specific eProsima project with several packages for linking and building application in Windows -inputs: - git_location: - description: 'Git Location of the package to clone project' - required: true - superpackage_name: - description: 'Name of the main package to download project' - required: true - package_names: - description: 'Name of the package to be built in dir build/' - required: true - cmake_build_type: - description: 'Specifies the build type on single-configuration generators' - required: true - default: 'Release' - cmake_options: - description: 'Specifies CMake options for package' - required: true - default: '-DCMAKE_PREFIX_PATH="C:\Program Files" -DCMAKE_CXX_FLAGS="/WX /EHsc" -Ax64 -T host=x64' - cmake_extra_options: - description: 'Specifies CMake extra options for package' - required: false - default: '' -runs: - using: composite - steps: - - run: > - if ( "${{ inputs.git_location }}" ) { git clone ${{ inputs.git_location }} ${{ inputs.superpackage_name }}; } - "${{ inputs.package_names }}".Split(" ") | ForEach { - echo "building package: $_"; - cmake ${{ inputs.cmake_options }} ${{ inputs.cmake_extra_options }} -B build\$_ ${{ inputs.superpackage_name }}\$_; - cmake --build build\$_ --config ${{ inputs.cmake_build_type }} --target install; - } - shell: pwsh diff --git a/.github/actions/install-eprosima-package-windows/action.yml b/.github/actions/install-eprosima-package-windows/action.yml deleted file mode 100644 index 711de6aa..00000000 --- a/.github/actions/install-eprosima-package-windows/action.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Install eProsima Package -description: Install and setup a specific eProsima package for linking and building application in Windows -inputs: - git_location: - description: 'Git Location of the package to clone project' - required: false - default: '' - package_name: - description: 'Name of the package to be built in dir build/' - required: true - cmake_build_type: - description: 'Specifies the build type on single-configuration generators' - required: true - default: 'Release' - cmake_options: - description: 'Specifies CMake general options for package' - required: true - default: '-DCMAKE_PREFIX_PATH="C:\Program Files" -DCMAKE_CXX_FLAGS="/WX /EHsc" -Ax64 -T host=x64' - cmake_extra_options: - description: 'Specifies CMake extra options for package' - required: false - default: '' -runs: - using: composite - steps: - - run: > - git clone ${{ inputs.git_location }} ${{ inputs.package_name }}; - cmake ${{ inputs.cmake_options }} ${{ inputs.cmake_extra_options }} -B build\${{ inputs.package_name }} ${{ inputs.package_name }}; - cmake --build build\${{ inputs.package_name }} --config ${{ inputs.cmake_build_type }} --target install; - shell: pwsh diff --git a/.github/actions/install-gtest-linux/action.yml b/.github/actions/install-gtest-linux/action.yml deleted file mode 100644 index 3c3257df..00000000 --- a/.github/actions/install-gtest-linux/action.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: Install GTest -description: Install and setup GTest for linking and building test application in Linux -runs: - using: composite - steps: - - run: sudo apt install libgtest-dev libgmock-dev - shell: bash - - run: (cd /usr/src/gtest && sudo `which cmake` .) - shell: bash - - run: sudo make -j $(nproc) -C /usr/src/gtest - shell: bash - - run: sudo ln -s /usr/src/gtest/libgtest.a /usr/lib/libgtest.a - shell: bash - - run: sudo ln -s /usr/src/gtest/libgtest_main.a /usr/lib/libgtest_main.a - shell: bash - - run: (cd /usr/src/googletest/googlemock && sudo `which cmake` .) - shell: bash - - run: sudo make -j $(nproc) -C /usr/src/googletest/googlemock - shell: bash - - run: sudo ln -s /usr/src/googletest/googlemock/libgmock.a /usr/lib/libgmock.a - shell: bash diff --git a/.github/actions/install-gtest-windows/action.yml b/.github/actions/install-gtest-windows/action.yml deleted file mode 100644 index a3400a3f..00000000 --- a/.github/actions/install-gtest-windows/action.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Install GTest -description: Install and setup GTest for linking and building test application in Windows -inputs: - cmake_build_type: - description: 'Specifies the build type on single-configuration generators' - required: true - default: 'Release' -runs: - using: composite - steps: - - run: > - cmake --find-package -DNAME=GTest -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=EXIST | Tee-Object -Variable res; - if ( $res -notlike '*GTest found.*') - { - git clone https://github.com/google/googletest.git; - cmake -DCMAKE_INSTALL_PREFIX='C:\Program Files\gtest' -Dgtest_force_shared_crt=ON -DBUILD_GMOCK=ON ` - -B build\gtest -A x64 -T host=x64 googletest; - cmake --build build\gtest --config ${{ inputs.cmake_build_type }} --target install - } - shell: pwsh diff --git a/.github/actions/install-openssl-windows/action.yml b/.github/actions/install-openssl-windows/action.yml deleted file mode 100644 index 964caecd..00000000 --- a/.github/actions/install-openssl-windows/action.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: Install OpenSSL -description: Install and setup OpenSSL for linking and building in Windows -runs: - using: composite - steps: - - run: > - choco install openssl -yr --no-progress; - @(ls -Path C:\Windows\System32\* -Include libssl-*.dll; ls -Path C:\Windows\SysWOW64\* -Include libssl-*.dll) - | rm -ErrorAction SilentlyContinue - shell: pwsh diff --git a/.github/actions/install-python-packages-windows/action.yml b/.github/actions/install-python-packages-windows/action.yml deleted file mode 100644 index 669d045d..00000000 --- a/.github/actions/install-python-packages-windows/action.yml +++ /dev/null @@ -1,9 +0,0 @@ -name: 'install-python-packages-windows' -description: 'Install necessary python packages for windows' -runs: - using: "composite" - steps: - - id: install-python-packages - run: | - python -m pip install -U pytest - shell: pwsh diff --git a/.github/actions/install-subpackage-windows-python/action.yml b/.github/actions/install-subpackage-windows-python/action.yml deleted file mode 100644 index 6ffe10b1..00000000 --- a/.github/actions/install-subpackage-windows-python/action.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: Install subpackage -description: Install and setup subpackage for linking and building application in Windows -inputs: - package_path: - description: 'Specifies the build type on single-configuration generators' - required: true -runs: - using: composite - steps: - - run: > - python -m pip install -e ${{ inputs.package_path }} - shell: pwsh diff --git a/.github/actions/install-subpackage-windows/action.yml b/.github/actions/install-subpackage-windows/action.yml deleted file mode 100644 index 4ade120d..00000000 --- a/.github/actions/install-subpackage-windows/action.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Install subpackage -description: Install and setup subpackage for linking and building application in Windows -inputs: - package_path: - description: 'Specifies the build type on single-configuration generators' - required: true - cmake_build_type: - description: 'Specifies the build type on single-configuration generators' - required: true - default: 'Release' - subpackage: - description: 'Specifies the name of the subpackage to install' - required: true - subpackage_dir: - description: 'Specifies the path of the subpackage to install' - required: true -runs: - using: composite - steps: - - run: > - cmake -DCMAKE_PREFIX_PATH='C:\Program Files\gtest;C:\Program Files;${{ github.workspace }}\..\eprosima\install' ` - -DCMAKE_CXX_FLAGS="/WX /EHsc" -DBUILD_TESTS=ON -B build\${{ inputs.subpackage }} -A x64 -T host=x64 ${{ inputs.package_path }}/${{ inputs.subpackage_dir }}; - cmake --build build\${{ inputs.subpackage }} --config ${{ inputs.cmake_build_type }} --target install; - - shell: pwsh diff --git a/.github/actions/install-yamlcpp-windows/action.yml b/.github/actions/install-yamlcpp-windows/action.yml deleted file mode 100644 index 0a1613de..00000000 --- a/.github/actions/install-yamlcpp-windows/action.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Install yaml-cpp -description: Install and setup yaml-cpp for linking and building in Windows -inputs: - cmake_build_type: - description: 'Specifies the build type on single-configuration generators' - required: true - default: 'Release' -runs: - using: composite - steps: - - run: > - cmake --find-package -DNAME=yamlcpp -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=EXIST | Tee-Object -Variable res; - if ( $res -notlike '*yamlcpp found.*') - { - git clone --branch yaml-cpp-0.7.0 https://github.com/jbeder/yaml-cpp; - cmake -DCMAKE_INSTALL_PREFIX='C:\Program Files\yamlcpp' -B build\yamlcpp yaml-cpp - cmake --build build\yamlcpp --config ${{ inputs.cmake_build_type }} --target install - } - shell: pwsh diff --git a/.github/actions/project_dependencies/action.yml b/.github/actions/project_dependencies/action.yml new file mode 100644 index 00000000..c314d111 --- /dev/null +++ b/.github/actions/project_dependencies/action.yml @@ -0,0 +1,95 @@ +name: build_amlip_dependencies +description: Common first step for all jobs. Checkout repository, download dependencies and install required packages. + +inputs: + + ddsrouter_branch: + description: > + Branch, tag or commit of eProsima/DDS-Router repository. + Check available branches in https://github.com/eProsima/DDS-Router. + required: false + default: main + + os: + description: Specify runs-on machine to download specific artifact + required: true + + cmake_build_type: + description: Specify cmake_build_type option to download specific artifact + required: true + + dependencies_artifact_postfix: + description: Specify artifact postfix in case it wants to use a manual one + required: false + default: _nightly + + target_workspace: + description: Specify directory to download dependencies + required: false + default: ${{ github.workspace }}/install + + # This must be passed as an argument because actions do not access to workflow secrets: + # Unrecognized named-value: 'secrets'. https://github.com/orgs/community/discussions/27054 + # Pass argument {{ secrets.GITHUB_TOKEN }} from workflow + secret_token: + description: 'Secret token to authenticate the WebRequest so it not get a rate limit error.' + required: false + default: '' + +runs: + using: composite + steps: + + - name: Install Fast DDS dependencies + uses: eProsima/eProsima-CI/multiplatform/install_fastdds_dependencies@v0 + with: + cmake_build_type: ${{ inputs.cmake_build_type }} + + - name: Install yaml cpp dependency + uses: eProsima/eProsima-CI/multiplatform/install_yamlcpp@v0 + with: + cmake_build_type: ${{ inputs.cmake_build_type }} + + # In DDS Pipe artifact there are included Fast DDS and dev-utils + - name: Download dependencies artifact + uses: eProsima/eProsima-CI/multiplatform/download_dependency@v0 + with: + artifact_name: built_ddspipe_${{ inputs.os }}_${{ inputs.cmake_build_type }}${{ inputs.dependencies_artifact_postfix }} + workflow_source: build_ddspipe.yml + workflow_source_repository: eProsima/eProsima-CI + target_workspace: ${{ inputs.target_workspace }} + secret_token: ${{ inputs.secret_token }} + workflow_conclusion: completed + + - name: Fetch DDS Router repositories in ubuntu + if: runner.os == 'Linux' + shell: bash + run: | + + echo "::group::Manually clone DDS Router repository" + + echo "Downloading following dependencies:" + echo " - DDS Router: ${{ inputs.ddsrouter_branch }}" + + mkdir -p ${{ github.workspace }} + cd ${{ github.workspace }} + git clone --branch ${{ inputs.ddsrouter_branch }} https://github.com/eProsima/DDS-Router.git + + echo "::endgroup::" + + - name: Fetch DDS Router repositories in windows + if: runner.os == 'Windows' + shell: pwsh + run: | + + "::group::Manually clone DDS Router repository" + + Write-Host 'Downloading following dependencies:' + Write-Host ' - DDS Router: ${{ inputs.ddsrouter_branch }}' + + New-Item -ItemType Directory -Force -Path ${{ github.workspace }} + Set-Location -Path ${{ github.workspace }} + + git clone --branch ${{ inputs.ddsrouter_branch }} https://github.com/eProsima/DDS-Router.git + + "::endgroup::" diff --git a/.github/actions/run-test-ubuntu/action.yml b/.github/actions/run-test-ubuntu/action.yml deleted file mode 100644 index 0075a130..00000000 --- a/.github/actions/run-test-ubuntu/action.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: Run colcon test in ubuntu -description: Run colcon test in ubuntu for a specific package -inputs: - package_name: - description: 'Specifies the package to run the tests' - required: true -runs: - using: composite - steps: - - run: | - source install/setup.bash - colcon test \ - --packages-select ${{ inputs.package_name }} \ - --event-handlers=console_direct+ \ - --return-code-on-test-failure \ - --ctest-args \ - --label-exclude xfail \ - --timeout 60 \ - --pytest-args \ - --timeout 60 - shell: bash diff --git a/.github/actions/run-test-windows-python/action.yml b/.github/actions/run-test-windows-python/action.yml deleted file mode 100644 index 4725ddae..00000000 --- a/.github/actions/run-test-windows-python/action.yml +++ /dev/null @@ -1,14 +0,0 @@ -name: Run subpackage tests in windows -description: Run tests in windows for a specific package -inputs: - package_name: - description: 'Specifies the package build name to run the tests' - required: true -runs: - using: composite - steps: - - run: > - python -m pip install pytest; - python -m pytest ${{ inputs.package_name }} - shell: pwsh - # TODO check if pytest install neeeded diff --git a/.github/actions/run-test-windows/action.yml b/.github/actions/run-test-windows/action.yml deleted file mode 100644 index da262744..00000000 --- a/.github/actions/run-test-windows/action.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Run subpackage tests in windows -description: Run tests in windows for a specific package -inputs: - package_name: - description: 'Specifies the package build name to run the tests' - required: true - cmake_build_type: - description: 'Specifies the build type on single-configuration generators' - required: true - default: 'Release' -runs: - using: composite - steps: - - run: > - ctest -C ${{ inputs.cmake_build_type }} --test-dir build\${{ inputs.package_name }} -V --timeout 60 --label-exclude xfail - shell: pwsh diff --git a/.github/workflows/asan_colcon.meta b/.github/workflows/asan_colcon.meta deleted file mode 100644 index 23c95584..00000000 --- a/.github/workflows/asan_colcon.meta +++ /dev/null @@ -1,15 +0,0 @@ -{ - "names": - { - "amlip_cpp": - { - "cmake-args": - [ - "-DCMAKE_BUILD_TYPE=Debug", - "-DBUILD_TESTS=ON", - "-DASAN_BUILD=ON", - "-DCMAKE_CXX_FLAGS='-Werror'" - ] - } - } -} diff --git a/.github/workflows/build_eprosima_dependencies.yml b/.github/workflows/build_eprosima_dependencies.yml deleted file mode 100644 index 635455bb..00000000 --- a/.github/workflows/build_eprosima_dependencies.yml +++ /dev/null @@ -1,143 +0,0 @@ -name: build_eprosima_dependencies - -on: - workflow_dispatch: - inputs: - foonathan_memory_vendor_branch: - description: 'Branch or tag of eProsima/foonathan_memory_vendor repository (https://github.com/eProsima/foonathan_memory_vendor)' - required: true - default: 'master' - fastcdr_branch: - description: 'Branch or tag of eProsima/Fast-CDR repository (https://github.com/eProsima/Fast-CDR)' - required: true - default: '1.1.x' - fastdds_branch: - description: 'Branch or tag of eProsima/Fast-DDS repository (https://github.com/eProsima/Fast-DDS)' - required: true - default: '2.11.x' - utils_branch: - description: 'Branch or tag of eProsima/dev-utils repository (https://github.com/eProsima/dev-utils)' - required: true - default: 'main' - ddspipe_branch: - description: 'Branch or tag of eProsima/DDS-Pipe repository (https://github.com/eProsima/DDS-Pipe)' - required: true - default: 'main' - ddsrouter_branch: - description: 'Branch or tag of eProsima/DDS-Router repository (https://github.com/eProsima/DDS-Router)' - required: true - default: 'main' - schedule: - - cron: '0 0 * * *' - -jobs: - windows-build: - runs-on: windows-latest - strategy: - fail-fast: false - matrix: - cmake-config: - - 'Release' - - 'Debug' - env: - CXXFLAGS: /MP - OPENSSL64_ROOT: "C:/Program Files/OpenSSL-Win64" - - steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 - with: - path: AML-IP - - - name: Install OpenSSL - uses: ./AML-IP/.github/actions/install-openssl-windows - - - name: Install yaml-cpp - uses: ./AML-IP/.github/actions/install-yamlcpp-windows - with: - cmake_build_type: ${{ matrix.cmake-config }} - - - name: Install eProsima dependencies - uses: ./AML-IP/.github/actions/install-eprosima-dependencies-windows - env: - DEFAULT_FOONATHAN_BRANCH: 'master' - DEFAULT_FASTCDR_BRANCH: '1.1.x' - DEFAULT_FASTDDS_BRANCH: '2.11.x' - DEFAULT_UTILS_BRANCH: 'main' - DEFAULT_DDDSPIPE_BRANCH: 'main' - DEFAULT_DDSROUTER_BRANCH: 'main' - with: - cmake_build_type: ${{ matrix.cmake-config }} - foonathan_memory_vendor_branch: ${{ github.event.inputs.foonathan_memory_vendor_branch || env.DEFAULT_FOONATHAN_BRANCH }} - fastcdr_branch: ${{ github.event.inputs.fastcdr_branch || env.DEFAULT_FASTCDR_BRANCH }} - fastdds_branch: ${{ github.event.inputs.fastdds_branch || env.DEFAULT_FASTDDS_BRANCH }} - utils_branch: ${{ github.event.inputs.utils_branch || env.DEFAULT_UTILS_BRANCH }} - ddspipe_branch: ${{ github.event.inputs.ddspipe_branch || env.DEFAULT_DDDSPIPE_BRANCH }} - ddsrouter_branch: ${{ github.event.inputs.ddsrouter_branch || env.DEFAULT_DDSROUTER_BRANCH }} - - - name: Upload binaries - uses: actions/upload-artifact@v4 - with: - name: windows_${{ matrix.cmake-config }}_eprosima_dependencies_install - path: ${{ github.workspace }}\eprosima\install - - ubuntu-build: - runs-on: ubuntu-latest - environment: - name: codecov - - steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 - with: - path: src/AML-IP - - - name: Avoid AML-IP build - run: | - touch ./src/AML-IP/COLCON_IGNORE - - - name: Install apt packages - uses: ./src/AML-IP/.github/actions/install-apt-packages - - - name: Install colcon - uses: eProsima/eProsima-CI/ubuntu/install_colcon@v0 - - - name: Install Python packages - uses: eProsima/eProsima-CI/ubuntu/install_python_packages@v0 - with: - packages: \ - black==22.3.0 \ - doc8==0.8.0 \ - GitPython \ - setuptools \ - gcovr==5.0 \ - sphinx_rtd_theme==0.4.3 \ - sphinx==3.0.3 \ - sphinx-tabs==3.2.0 \ - sphinxcontrib-imagehelper==1.1.1 \ - sphinxcontrib.spelling==5.0.0 \ - vcstool \ - flake8==5.0.4 \ - flake8-quotes \ - pytest \ - pytest-timeout - - - name: Fetch dependencies repositories - run: | - vcs import src < src/AML-IP/.github/workflows/ci.repos - cd src/foonathan_memory_vendor && git checkout ${{ inputs.foonathan_memory_vendor_branch }} && cd ../.. - cd src/fastcdr && git checkout ${{ inputs.fastcdr_branch }} && cd ../.. - cd src/fastdds && git checkout ${{ inputs.fastdds_branch }} && cd ../.. - cd src/dev-utils && git checkout ${{ inputs.utils_branch }} && cd ../.. - cd src/ddspipe && git checkout ${{ inputs.ddspipe_branch }} && cd ../.. - cd src/ddsrouter && git checkout ${{ inputs.ddsrouter_branch }} && cd ../.. - - - name: Build workspace - run: | - colcon build --event-handlers=console_direct+ - - - name: Upload binaries - uses: actions/upload-artifact@v4 - with: - name: ubuntu_eprosima_dependencies_install - path: install diff --git a/.github/workflows/ci.repos b/.github/workflows/ci.repos deleted file mode 100644 index 98e890a8..00000000 --- a/.github/workflows/ci.repos +++ /dev/null @@ -1,25 +0,0 @@ -repositories: - foonathan_memory_vendor: - type: git - url: https://github.com/eProsima/foonathan_memory_vendor.git - version: master - fastcdr: - type: git - url: https://github.com/eProsima/Fast-CDR.git - version: 1.1.x - fastdds: - type: git - url: https://github.com/eProsima/Fast-DDS.git - version: 2.11.x - dev-utils: - type: git - url: https://github.com/eProsima/dev-utils.git - version: main - ddspipe: - type: git - url: https://github.com/eProsima/DDS-Pipe.git - version: main - ddsrouter: - type: git - url: https://github.com/eProsima/DDS-Router.git - version: main diff --git a/.github/workflows/clang_colcon.meta b/.github/workflows/clang_colcon.meta deleted file mode 100644 index 90eab036..00000000 --- a/.github/workflows/clang_colcon.meta +++ /dev/null @@ -1,23 +0,0 @@ -{ - "names": - { - "amlip_cpp": - { - "cmake-args": - [ - "-DCMAKE_BUILD_TYPE=Release", - "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON", - "-DCMAKE_CXX_FLAGS='-Werror -Wall'" - ] - }, - "amlip_docs": - { - "cmake-args": - [ - "-DCMAKE_BUILD_TYPE=Release", - "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON", - "-DCMAKE_CXX_FLAGS='-Werror -Wall'", - ] - } - } -} diff --git a/.github/workflows/configurations/Linux/colcon.meta b/.github/workflows/configurations/Linux/colcon.meta new file mode 100644 index 00000000..c3e503a7 --- /dev/null +++ b/.github/workflows/configurations/Linux/colcon.meta @@ -0,0 +1,5 @@ +{ + "names": + { + } +} diff --git a/.github/workflows/configurations/Windows/colcon.meta b/.github/workflows/configurations/Windows/colcon.meta new file mode 100644 index 00000000..6fe69c23 --- /dev/null +++ b/.github/workflows/configurations/Windows/colcon.meta @@ -0,0 +1,23 @@ +{ + "names": + { + "amlip_cpp": + { + "cmake-args": + [ + "-DCMAKE_CXX_FLAGS='/WX /EHsc'", + "-Ax64", + "-T host=x64" + ] + }, + "amlip_swig": + { + "cmake-args": + [ + "-DCMAKE_CXX_FLAGS='/WX /EHsc'", + "-Ax64", + "-T host=x64" + ] + } + } +} diff --git a/.github/workflows/docs_colcon.meta b/.github/workflows/docs_colcon.meta deleted file mode 100644 index e9403ef5..00000000 --- a/.github/workflows/docs_colcon.meta +++ /dev/null @@ -1,12 +0,0 @@ -{ - "names": - { - "amlip_docs": - { - "cmake-args": - [ - "-DBUILD_DOCS_TESTS=ON" - ] - } - } -} diff --git a/.github/workflows/setup.cfg b/.github/workflows/setup.cfg deleted file mode 100644 index 38a8772f..00000000 --- a/.github/workflows/setup.cfg +++ /dev/null @@ -1,6 +0,0 @@ -[flake8] -max-line-length = 99 -max-doc-length = 300 -statistics = True -max-complexity = 10 -count = True diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fff47f44..aa64758f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,7 +1,15 @@ name: test on: + workflow_dispatch: + inputs: + + dependencies_artifact_postfix: + description: 'Postfix name to add to artifact name to download dependencies. This is use to download a specific artifact version from eProsima-CI.' + required: true + default: '_nightly' + pull_request: push: branches: @@ -9,699 +17,235 @@ on: schedule: - cron: '0 1 * * *' +env: + code_packages_names: 'amlip_cpp amlip_py amlip_swig amlip_agent' + docs_packages_names: 'amlip_docs' + default_dependencies_artifact_postfix: '_nightly' + jobs: - windows-build-test: - runs-on: windows-latest + +##################################################################### +# TEST + + multiplatform-tests: + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: - cmake-config: - - 'Release' - - 'Debug' - env: - CXXFLAGS: /MP - OPENSSL64_ROOT: "C:/Program Files/OpenSSL-Win64" - + cmake_build_type: + - Release + - Debug + os: + - ubuntu-20.04 + - ubuntu-22.04 + - windows-2019 + - windows-2022 steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 - with: - path: AML-IP - - - name: Install OpenSSL - uses: ./AML-IP/.github/actions/install-openssl-windows - - name: Install yaml-cpp - uses: ./AML-IP/.github/actions/install-yamlcpp-windows + - name: Sync repository + uses: eProsima/eProsima-CI/external/checkout@v0 with: - cmake_build_type: ${{ matrix.cmake-config }} + path: ${{ github.workspace }}/src - - name: Install GTest - uses: ./AML-IP/.github/actions/install-gtest-windows + - name: Download dependencies and install requirements + uses: ./src/.github/actions/project_dependencies with: - cmake_build_type: ${{ matrix.cmake-config }} - - - name: Get build eProsima dependencies Job Id - shell: pwsh - run: | - $secret = ConvertTo-SecureString -String "${{ secrets.GITHUB_TOKEN }}" -AsPlainText - $RUNS_URI = '${{ github.api_url }}/repos/${{ github.repository }}/actions/workflows/build_eprosima_dependencies.yml/runs' - - # Check available queries according with github policy - "::group::Rate Limits with github action token" - ((Invoke-WebRequest -Authentication OAuth -Token $secret ` - -Uri https://api.github.com/users/octocat).Headers.GetEnumerator() | - ? Key -like "X-RateLimit*") | Out-Host - "::endgroup::" - - ((Invoke-WebRequest -Authentication OAuth -Token $secret -Uri $RUNS_URI).Content | ConvertFrom-Json).workflow_runs | ? status -eq 'completed' | - select -first 1 id | % { "fastdds_job_id=" + $_.id } | Out-File $env:GITHUB_ENV -Append - - - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v3 - with: - workflow: build_eprosima_dependencies.yml - path: ${{ github.workspace }}\..\eprosima\install - name: windows_${{ matrix.cmake-config }}_eprosima_dependencies_install - run_id: ${{ env.eprosima_dependencies_job_id }} + os: ${{ matrix.os }} + cmake_build_type: ${{ matrix.cmake_build_type }} + dependencies_artifact_postfix: ${{ github.event.inputs.dependencies_artifact_postfix || env.default_dependencies_artifact_postfix }} + secret_token: ${{ secrets.GITHUB_TOKEN }} - - name: Install amlip_cpp - uses: ./AML-IP/.github/actions/install-subpackage-windows + - name: Compile and run tests + id: compile_and_test + uses: eProsima/eProsima-CI/multiplatform/colcon_build_test@main with: - package_path: AML-IP - subpackage: amlip_cpp - subpackage_dir: amlip_cpp - cmake_build_type: ${{ matrix.cmake-config }} + packages_names: ${{ env.code_packages_names }} + cmake_args: -DBUILD_TESTS=ON -DCMAKE_BUILD_TYPE=${{ matrix.cmake_build_type }} + workspace_dependencies: ${{ github.workspace }}/install + ctest_args: --label-exclude "xfail" + colcon_meta_file: ${{ github.workspace }}/src/.github/workflows/configurations/${{ runner.os }}/colcon.meta - - name: Run tests amlip_cpp - uses: ./AML-IP/.github/actions/run-test-windows + - name: Test Report + uses: eProsima/eProsima-CI/external/test-reporter@main + if: success() || failure() with: - package_name: amlip_cpp - cmake_build_type: ${{ matrix.cmake-config }} - if: always() + name: "Report: ${{ matrix.os }} | ${{ matrix.cmake_build_type }} " + path: "${{ steps.compile_and_test.outputs.ctest_results_path }}*.xml" + working-directory: 'src' + path-replace-backslashes: 'true' + list-tests: 'failed' # NOTE: Windows does not support Python API - ubuntu-build-test: - runs-on: ubuntu-latest - environment: - name: codecov +##################################################################### +# DOCUMENTATION TEST + + ubuntu-test-documentation: + runs-on: ubuntu-latest steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 + + - name: Build and test documentation + uses: eProsima/eProsima-CI/ubuntu/sphinx_docs@main with: - path: src/AML-IP + checkout_path: "${{ github.workspace }}/src/amlip" + path_to_requirements: "${{ github.workspace }}/src/amlip/amlip_docs/requirements.txt" + docs_subpackage_name: ${{ env.docs_packages_names }} + secret_token: ${{ secrets.GITHUB_TOKEN }} - - name: Install apt packages - uses: ./src/AML-IP/.github/actions/install-apt-packages - - name: Install GTest - uses: ./src/AML-IP/.github/actions/install-gtest-linux +##################################################################### +# FLAKY - - name: Install colcon - uses: eProsima/eProsima-CI/ubuntu/install_colcon@v0 + ubuntu-build-test-flaky: + runs-on: ubuntu-latest + steps: - - name: Install Python packages - uses: eProsima/eProsima-CI/ubuntu/install_python_packages@v0 - with: - packages: \ - black==22.3.0 \ - doc8==0.8.0 \ - GitPython \ - setuptools \ - gcovr==5.0 \ - sphinx_rtd_theme==0.4.3 \ - sphinx==3.0.3 \ - sphinx-tabs==3.2.0 \ - sphinxcontrib-imagehelper==1.1.1 \ - sphinxcontrib.spelling==5.0.0 \ - vcstool \ - flake8==5.0.4 \ - flake8-quotes \ - pytest \ - pytest-timeout - - - - name: Get build eProsima dependencies Job Id - run: | - export JOB_ID=$(curl -sL $GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/workflows/build_eprosima_dependencies.yml/runs | \ - jq '.workflow_runs[] | select(.status == "completed") | .id' | \ - head -n 1) - echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - - - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v3 - with: - workflow: build_eprosima_dependencies.yml - path: /home/runner/work/eprosima/install - name: ubuntu_eprosima_dependencies_install - run_id: ${{ env.eprosima_dependencies_job_id }} - - - name: Update colcon mixin - run: | - colcon mixin add default \ - https://raw.githubusercontent.com/colcon/colcon-mixin-repository/master/index.yaml - colcon mixin update default - continue-on-error: true - - - name: Build workspace - run: | - cat src/AML-IP/.github/workflows/test_colcon.meta - source /home/runner/work/eprosima/install/setup.bash - colcon build \ - --packages-up-to-regex amlip \ - --event-handlers=console_direct+ \ - --metas src/AML-IP/.github/workflows/test_colcon.meta \ - --mixin coverage-gcc \ - --packages-skip amlip_docs - - - name: Run tests amlip_cpp - uses: ./src/AML-IP/.github/actions/run-test-ubuntu + - name: Sync repository + uses: eProsima/eProsima-CI/external/checkout@v0 with: - package_name: amlip_cpp - if: always() + path: ${{ github.workspace }}/src - - name: Run tests amlip_swig - uses: ./src/AML-IP/.github/actions/run-test-ubuntu + - name: Download dependencies and install requirements + uses: ./src/.github/actions/project_dependencies with: - package_name: amlip_swig - if: always() + os: ubuntu-22.04 + cmake_build_type: Release + dependencies_artifact_postfix: ${{ github.event.inputs.dependencies_artifact_postfix || env.default_dependencies_artifact_postfix }} + secret_token: ${{ secrets.GITHUB_TOKEN }} - - name: Run tests amlip_py - uses: ./src/AML-IP/.github/actions/run-test-ubuntu + - name: Compile and run tests + id: compile_and_test + uses: eProsima/eProsima-CI/multiplatform/colcon_build_test@main with: - package_name: amlip_py - if: always() - - - name: Generate coverage report - run: | - cp src/AML-IP/codecov.yml . - mkdir coverage-report - mkdir build/amlip - cp --recursive build/amlip_* build/amlip - gcovr \ - --root src/AML-IP/ \ - --output coverage-report/coverage.xml \ - --xml-pretty \ - --exclude='.*docs/.*' \ - --exclude='.*test/.*' \ - --exclude='.*github/.*' \ - --exclude='.*common/.*' \ - --exclude='.*dev/.*' \ - --exclude='.*thirdparty/.*' \ - --exclude='.*resources/.*' \ - --exclude-unreachable-branches \ - build/amlip_* - - - name: Upload coverage - uses: actions/upload-artifact@v1 - with: - name: coverage-report - path: coverage-report/ + packages_names: ${{ env.code_packages_names }} + workspace_dependencies: ${{ github.workspace }}/install + ctest_args: --label-regex "xfail" - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v1 + - name: Test Report + uses: eProsima/eProsima-CI/external/test-reporter@main + if: success() || failure() with: - token: ${{ secrets.CODECOV_TOKEN }} - file: coverage-report/coverage.xml - root_dir: src/AML-IP - fail_ci_if_error: true + name: "Report: Flaky " + path: "${{ steps.compile_and_test.outputs.ctest_results_path }}*.xml" + working-directory: 'src' + fail-on-empty: 'false' + list-tests: 'failed' - - name: Upload Logs - uses: actions/upload-artifact@v1 - with: - name: colcon-logs-ubuntu - path: log/ - if: always() +##################################################################### +# ASAN - ubuntu-test-documentation: + asan-test: runs-on: ubuntu-latest - steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 - with: - path: src/AML-IP - - - name: Install apt packages - uses: ./src/AML-IP/.github/actions/install-apt-packages - - - name: Install colcon - uses: eProsima/eProsima-CI/ubuntu/install_colcon@v0 - - name: Install Python packages - uses: eProsima/eProsima-CI/ubuntu/install_python_packages@v0 + - name: Sync repository + uses: eProsima/eProsima-CI/external/checkout@v0 with: - packages: \ - black==22.3.0 \ - doc8==0.8.0 \ - GitPython \ - setuptools \ - gcovr==5.0 \ - sphinx_rtd_theme==0.4.3 \ - sphinx==3.0.3 \ - sphinx-tabs==3.2.0 \ - sphinxcontrib-imagehelper==1.1.1 \ - sphinxcontrib.spelling==5.0.0 \ - vcstool \ - flake8==5.0.4 \ - flake8-quotes \ - pytest \ - pytest-timeout - - - name: Get build eProsima dependencies Job Id - run: | - export JOB_ID=$(curl -sL $GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/workflows/build_eprosima_dependencies.yml/runs | \ - jq '.workflow_runs[] | select(.status == "completed") | .id' | \ - head -n 1) - echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - - - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v3 - with: - workflow: build_eprosima_dependencies.yml - path: /home/runner/work/eprosima/install - name: ubuntu_eprosima_dependencies_install - run_id: ${{ env.eprosima_dependencies_job_id }} - - - name: Update colcon mixin - run: | - colcon mixin add default \ - https://raw.githubusercontent.com/colcon/colcon-mixin-repository/master/index.yaml - colcon mixin update default - continue-on-error: true - - - name: Build workspace - run: | - cat src/AML-IP/.github/workflows/docs_colcon.meta - source /home/runner/work/eprosima/install/setup.bash - colcon build \ - --packages-select amlip_docs \ - --event-handlers=console_direct+ \ - --metas src/AML-IP/.github/workflows/docs_colcon.meta - - - name: Run tests amlip_docs - uses: ./src/AML-IP/.github/actions/run-test-ubuntu - with: - package_name: amlip_docs - if: always() + path: ${{ github.workspace }}/src - - name: Upload documentation - uses: actions/upload-artifact@v1 + - name: Download dependencies and install requirements + uses: ./src/.github/actions/project_dependencies with: - name: Documentation HTML - path: install/amlip_docs/docs/amlip_docs/sphinx/html/ + os: ubuntu-22.04 + cmake_build_type: Release + dependencies_artifact_postfix: ${{ github.event.inputs.dependencies_artifact_postfix || env.default_dependencies_artifact_postfix }} + secret_token: ${{ secrets.GITHUB_TOKEN }} - - name: Upload spelling errors - uses: actions/upload-artifact@v1 + - name: Compile and run tests + id: compile_and_test + uses: eProsima/eProsima-CI/multiplatform/asan_build_test@main with: - name: spelling_errors.txt - path: build/amlip_docs/docs/test/spelling/output.txt - continue-on-error: true + packages_names: ${{ env.code_packages_names }} + workspace_dependencies: ${{ github.workspace }}/install - - name: Upload Logs - uses: actions/upload-artifact@v1 + - name: Test Report + uses: eProsima/eProsima-CI/external/test-reporter@main + if: success() || failure() with: - name: colcon-logs-ubuntu - path: log/ - if: always() + name: "Report: ASAN " + path: "${{ steps.compile_and_test.outputs.ctest_results_path }}*.xml" + working-directory: 'src' + list-tests: 'failed' - ubuntu-build-test-flaky: - runs-on: ubuntu-latest +##################################################################### +# CLANG + clang-tidy: + runs-on: ubuntu-latest steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 - with: - path: src/AML-IP - - - name: Install apt packages - uses: ./src/AML-IP/.github/actions/install-apt-packages - - - name: Install GTest - uses: ./src/AML-IP/.github/actions/install-gtest-linux - - name: Install colcon - uses: eProsima/eProsima-CI/ubuntu/install_colcon@v0 - - - name: Install Python packages - uses: eProsima/eProsima-CI/ubuntu/install_python_packages@v0 - with: - packages: \ - black==22.3.0 \ - doc8==0.8.0 \ - GitPython \ - setuptools \ - gcovr==5.0 \ - sphinx_rtd_theme==0.4.3 \ - sphinx==3.0.3 \ - sphinx-tabs==3.2.0 \ - sphinxcontrib-imagehelper==1.1.1 \ - sphinxcontrib.spelling==5.0.0 \ - vcstool \ - flake8==5.0.4 \ - flake8-quotes \ - pytest \ - pytest-timeout - - - name: Get build eProsima dependencies Job Id - run: | - export JOB_ID=$(curl -sL $GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/workflows/build_eprosima_dependencies.yml/runs | \ - jq '.workflow_runs[] | select(.status == "completed") | .id' | \ - head -n 1) - echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - - - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v3 + - name: Sync repository + uses: eProsima/eProsima-CI/external/checkout@v0 with: - workflow: build_eprosima_dependencies.yml - path: /home/runner/work/eprosima/install - name: ubuntu_eprosima_dependencies_install - run_id: ${{ env.eprosima_dependencies_job_id }} - - - name: Update colcon mixin - run: | - colcon mixin add default \ - https://raw.githubusercontent.com/colcon/colcon-mixin-repository/master/index.yaml - colcon mixin update default - continue-on-error: true - - - name: Build workspace - run: | - cat src/AML-IP/.github/workflows/test_colcon.meta - source /home/runner/work/eprosima/install/setup.bash - colcon build \ - --packages-up-to-regex amlip \ - --event-handlers=console_direct+ \ - --metas src/AML-IP/.github/workflows/test_colcon.meta \ - --packages-skip amlip_docs - - - name: Run tests - run: | - source install/setup.bash && \ - colcon test \ - --packages-select amlip_cpp \ - --event-handlers=console_direct+ \ - --return-code-on-test-failure \ - --ctest-args \ - --label-regex xfail \ - --timeout 60 + path: ${{ github.workspace }}/src - asan-test: - runs-on: ubuntu-latest + - name: Download dependencies and install requirements + uses: ./src/.github/actions/project_dependencies + with: + os: ubuntu-22.04 + cmake_build_type: Release + dependencies_artifact_postfix: ${{ github.event.inputs.dependencies_artifact_postfix || env.default_dependencies_artifact_postfix }} + secret_token: ${{ secrets.GITHUB_TOKEN }} - steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 + - name: Compile and run tests + uses: eProsima/eProsima-CI/multiplatform/clang_build_test@v0 with: - path: src/AML-IP + packages_names: ${{ env.code_packages_names }} + workspace_dependencies: ${{ github.workspace }}/install - - name: Install apt packages - uses: ./src/AML-IP/.github/actions/install-apt-packages - - name: Install GTest - uses: ./src/AML-IP/.github/actions/install-gtest-linux +##################################################################### +# COVERAGE - - name: Install colcon - uses: eProsima/eProsima-CI/ubuntu/install_colcon@v0 + coverage: + runs-on: ubuntu-22.04 + environment: + name: codecov + steps: - - name: Install Python packages - uses: eProsima/eProsima-CI/ubuntu/install_python_packages@v0 - with: - packages: \ - black==22.3.0 \ - doc8==0.8.0 \ - GitPython \ - setuptools \ - gcovr==5.0 \ - sphinx_rtd_theme==0.4.3 \ - sphinx==3.0.3 \ - sphinx-tabs==3.2.0 \ - sphinxcontrib-imagehelper==1.1.1 \ - sphinxcontrib.spelling==5.0.0 \ - vcstool \ - flake8==5.0.4 \ - flake8-quotes \ - pytest \ - pytest-timeout - - - name: Get build eProsima dependencies Job Id - run: | - export JOB_ID=$(curl -sL $GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/workflows/build_eprosima_dependencies.yml/runs | \ - jq '.workflow_runs[] | select(.status == "completed") | .id' | \ - head -n 1) - echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - - - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v3 + - name: Sync repository + uses: eProsima/eProsima-CI/external/checkout@v0 with: - workflow: build_eprosima_dependencies.yml - path: /home/runner/work/eprosima/install - name: ubuntu_eprosima_dependencies_install - run_id: ${{ env.eprosima_dependencies_job_id }} - - - name: Update colcon mixin - run: | - colcon mixin add default \ - https://raw.githubusercontent.com/colcon/colcon-mixin-repository/master/index.yaml - colcon mixin update default - continue-on-error: true - - - name: Build workspace - run: | - cat src/AML-IP/.github/workflows/asan_colcon.meta - source /home/runner/work/eprosima/install/setup.bash - colcon build \ - --packages-up-to-regex amlip_cpp \ - --event-handlers=console_direct+ \ - --metas src/AML-IP/.github/workflows/asan_colcon.meta - - - name: Run tests - run: | - source install/setup.bash && \ - colcon test \ - --packages-select amlip_cpp \ - --event-handlers=console_direct+ \ - --return-code-on-test-failure \ - --ctest-args \ - --label-exclude "xfail|xasan" \ - --timeout 60 - - - name: Upload Logs - uses: actions/upload-artifact@v1 - with: - name: asan-logs - path: log/ - if: always() + path: ${{ github.workspace }}/src - clang-tidy: - runs-on: ubuntu-latest - steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 + - name: Download dependencies and install requirements + uses: ./src/.github/actions/project_dependencies with: - path: src/AML-IP + os: ubuntu-22.04 + cmake_build_type: Release + dependencies_artifact_postfix: ${{ github.event.inputs.dependencies_artifact_postfix || env.default_dependencies_artifact_postfix }} + secret_token: ${{ secrets.GITHUB_TOKEN }} - - name: Install apt packages - uses: ./src/AML-IP/.github/actions/install-apt-packages - - - name: Install GTest - uses: ./src/AML-IP/.github/actions/install-gtest-linux + - name: Compile and run tests + uses: eProsima/eProsima-CI/ubuntu/coverage_build_test_upload@main + with: + packages_names: ${{ env.code_packages_names }} + workspace_dependencies: ${{ github.workspace }}/install + codecov_token: ${{ secrets.CODECOV_TOKEN }} + codecov_fix_file_path: ${{ github.workspace }}/src/codecov.yml - - name: Install colcon - uses: eProsima/eProsima-CI/ubuntu/install_colcon@v0 - - name: Install Python packages - uses: eProsima/eProsima-CI/ubuntu/install_python_packages@v0 - with: - packages: \ - black==22.3.0 \ - doc8==0.8.0 \ - GitPython \ - setuptools \ - gcovr==5.0 \ - sphinx_rtd_theme==0.4.3 \ - sphinx==3.0.3 \ - sphinx-tabs==3.2.0 \ - sphinxcontrib-imagehelper==1.1.1 \ - sphinxcontrib.spelling==5.0.0 \ - vcstool \ - flake8==5.0.4 \ - flake8-quotes \ - pytest \ - pytest-timeout - - - name: Get build eProsima dependencies Job Id - run: | - export JOB_ID=$(curl -sL $GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/workflows/build_eprosima_dependencies.yml/runs | \ - jq '.workflow_runs[] | select(.status == "completed") | .id' | \ - head -n 1) - echo "eprosima_dependencies_job_id=${JOB_ID}" >> $GITHUB_ENV - - - name: Download eProsima dependencies - uses: dawidd6/action-download-artifact@v3 - with: - workflow: build_eprosima_dependencies.yml - path: /home/runner/work/eprosima/install - name: ubuntu_eprosima_dependencies_install - run_id: ${{ env.eprosima_dependencies_job_id }} - - - name: Build workspace - run: | - cat src/AML-IP/.github/workflows/clang_colcon.meta - source /home/runner/work/eprosima/install/setup.bash - colcon build \ - --event-handlers=console_direct+ \ - --metas src/AML-IP/.github/workflows/clang_colcon.meta - - - name: Run clang-tidy - run: | - mkdir build/amlip - cp --recursive build/amlip_* build/amlip - cd build/amlip - run-clang-tidy -header-filter='.*' -checks='clang-analyzer-cplusplus' -quiet 2> ${{ github.workspace }}/clang_results.yml - - - name: Upload clang results - uses: actions/upload-artifact@v1 - with: - name: clang_results - path: ${{ github.workspace }}/clang_results.yml +##################################################################### +# UNCRUSTIFY uncrustify: runs-on: ubuntu-latest steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 - with: - path: src/AML-IP - - name: Fetch all branches and tags - run: | - cd src/AML-IP - git fetch --prune --unshallow + - name: Uncrustify + uses: eProsima/eProsima-CI/ubuntu/uncrustify@v0 - - name: Install apt packages - uses: ./src/AML-IP/.github/actions/install-apt-packages - - name: Install colcon - uses: eProsima/eProsima-CI/ubuntu/install_colcon@v0 - - - name: Install Python packages - uses: eProsima/eProsima-CI/ubuntu/install_python_packages@v0 - with: - packages: \ - black==22.3.0 \ - doc8==0.8.0 \ - GitPython \ - setuptools \ - gcovr==5.0 \ - sphinx_rtd_theme==0.4.3 \ - sphinx==3.0.3 \ - sphinx-tabs==3.2.0 \ - sphinxcontrib-imagehelper==1.1.1 \ - sphinxcontrib.spelling==5.0.0 \ - vcstool \ - flake8==5.0.4 \ - flake8-quotes \ - pytest \ - pytest-timeout - - - name: Install uncrustify - run: | - git clone https://github.com/uncrustify/uncrustify.git \ - --branch uncrustify-0.71.0 \ - --single-branch uncrustify - mkdir -p uncrustify/build - cd uncrustify/build - cmake .. - sudo cmake --build . --target install - cd ../.. - sudo rm -rf uncrustify - - # (TODO) Change to main branch when PR is merged - - name: Clone ament_lint - run: | - git clone --branch feature/fix-language-set https://github.com/jparisu/ament_lint.git src/ament_lint - - - name: Build ament_uncrustify - run: colcon build --packages-up-to ament_uncrustify - - - name: Fetch uncrustify config file - run: | - curl \ - -l https://raw.githubusercontent.com/eProsima/cpp-style/master/uncrustify.cfg \ - -o uncrustify.cfg - - - name: Get difference - run: | - cd src/AML-IP - echo "MODIFIED_FILES=$(git diff --name-only origin/${GITHUB_BASE_REF} origin/${GITHUB_HEAD_REF} | grep -e '\.h' -e '\.hpp' -e '\.cpp' -e '\.ipp' | tr '\n' ' ')" >> $GITHUB_ENV - - - name: Check difference - run: | - cd src/AML-IP - if [[ -z "${MODIFIED_FILES}" ]] - then - touch empty.hpp - echo "MODIFIED_FILES=empty.hpp" >> $GITHUB_ENV - fi - - - name: Check style - run: | - source install/local_setup.bash - cd src/AML-IP - ament_uncrustify \ - -c ../../uncrustify.cfg \ - --language CPP \ - --xunit-file ../../uncrustify_results.xml \ - ${MODIFIED_FILES} - - - name: Upload uncrustify results - uses: actions/upload-artifact@v1 - with: - name: uncrustify_results - path: uncrustify_results.xml +##################################################################### +# PYTHON LINTER python-linter: runs-on: ubuntu-latest steps: - - name: Sync eProsima/AML-IP repository - uses: actions/checkout@v2 - with: - path: src/AML-IP - - name: Fetch all branches and tags - run: | - cd src/AML-IP - git fetch --prune --unshallow - - - name: Install apt packages - uses: ./src/AML-IP/.github/actions/install-apt-packages - - - name: Install colcon - uses: eProsima/eProsima-CI/ubuntu/install_colcon@v0 - - - name: Install Python packages - uses: eProsima/eProsima-CI/ubuntu/install_python_packages@v0 - with: - packages: \ - black==22.3.0 \ - doc8==0.8.0 \ - GitPython \ - setuptools \ - gcovr==5.0 \ - sphinx_rtd_theme==0.4.3 \ - sphinx==3.0.3 \ - sphinx-tabs==3.2.0 \ - sphinxcontrib-imagehelper==1.1.1 \ - sphinxcontrib.spelling==5.0.0 \ - vcstool \ - flake8==5.0.4 \ - flake8-quotes \ - pytest \ - pytest-timeout - - - name: Get difference - run: | - cd src/AML-IP - echo "MODIFIED_FILES=$(git diff --name-only origin/${GITHUB_BASE_REF} origin/${GITHUB_HEAD_REF} | grep -e '\.py' | tr '\n' ' ')" >> $GITHUB_ENV - - - name: Check difference - run: | - cd src/AML-IP - if [[ -z "${MODIFIED_FILES}" ]] - then - touch empty.py - echo "MODIFIED_FILES=empty.py" >> $GITHUB_ENV - fi - echo ${MODIFIED_FILES} - - - name: Check flake8 linter - run: | - cd src/AML-IP - python3 -m flake8 --config ./.github/workflows/setup.cfg ${MODIFIED_FILES} - if: always() + - name: Python Linter + uses: eProsima/eProsima-CI/ubuntu/python_linter@v0 diff --git a/.github/workflows/test_colcon.meta b/.github/workflows/test_colcon.meta deleted file mode 100644 index ff64538e..00000000 --- a/.github/workflows/test_colcon.meta +++ /dev/null @@ -1,24 +0,0 @@ -{ - "names": - { - "amlip_cpp": - { - "cmake-args": - [ - "-DCMAKE_BUILD_TYPE=Debug", - "-DBUILD_TESTS=ON", - "-DCODE_COVERAGE=ON", - "-DCMAKE_CXX_FLAGS='-Werror'", - "-DBUILD_MANUAL_TESTS=ON", - ] - }, - "amlip_swig": - { - "cmake-args": - [ - "-DCMAKE_BUILD_TYPE=Debug", - "-DBUILD_TESTS=ON", - ] - } - } -} From a236eb1064891ee49a5542eadb686c33029f02d6 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Mon, 1 Apr 2024 09:17:55 +0200 Subject: [PATCH 03/15] Update amlip_docs/requirements.txt & change Python version to 3.11 Signed-off-by: Irene Bandera --- amlip_docs/requirements.txt | 9 ++++++++- readthedocs.yaml | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/amlip_docs/requirements.txt b/amlip_docs/requirements.txt index ed0266f3..16380992 100644 --- a/amlip_docs/requirements.txt +++ b/amlip_docs/requirements.txt @@ -1,9 +1,16 @@ doc8==0.10.1 docutils==0.16.0 GitPython==3.1.24 -setuptools==58.2.0 +setuptools==65.5.1 sphinx_rtd_theme==0.5.2 +sphinx-sitemap==2.2.0 sphinx-tabs==3.2.0 sphinx==4.3.1 +sphinxcontrib-applehelp==1.0.4 +sphinxcontrib-devhelp==1.0.2 +sphinxcontrib-htmlhelp==2.0.1 sphinxcontrib-imagehelper==1.1.1 +sphinxcontrib-plantuml==0.22 +sphinxcontrib-qthelp==1.0.3 +sphinxcontrib-serializinghtml==1.1.5 sphinxcontrib.spelling==7.2.1 diff --git a/readthedocs.yaml b/readthedocs.yaml index 32010e06..202f2257 100644 --- a/readthedocs.yaml +++ b/readthedocs.yaml @@ -9,7 +9,7 @@ version: 2 build: os: ubuntu-22.04 tools: - python: "3.7" + python: "3.11" # Build documentation in the docs/ directory with Sphinx sphinx: From 4cbbe8ba1fd2d4e98b3bbf111b3df11b9ebe57ed Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Mon, 1 Apr 2024 16:21:02 +0200 Subject: [PATCH 04/15] Support Fast-CDR v2 Signed-off-by: Irene Bandera --- .../include/amlip_cpp/node/AsyncEdgeNode.hpp | 2 +- .../ModelManagerReceiverNode.hpp | 8 +- .../ModelManagerSenderNode.hpp | 8 +- .../amlip_cpp/types/GenericDataType.hpp | 46 +- .../amlip_cpp/types/InterfaceDataType.hpp | 20 - .../amlip_cpp/types/id/AmlipIdDataType.hpp | 43 +- .../types/impl/GenericDataTypeCdrAux.ipp | 127 +++ .../types/model/ModelStatisticsDataType.hpp | 57 +- .../amlip_cpp/types/status/StatusDataType.hpp | 25 +- amlip_cpp/src/cpp/dds/Participant.hpp | 25 +- .../multiservice/AsyncMultiServiceClient.hpp | 7 +- .../multiservice/AsyncMultiServiceServer.hpp | 7 +- .../dds/multiservice/MultiServiceClient.hpp | 8 +- .../dds/multiservice/MultiServiceServer.hpp | 7 +- amlip_cpp/src/cpp/dds/rpc/RPCClient.hpp | 8 +- amlip_cpp/src/cpp/dds/rpc/RPCServer.hpp | 8 +- amlip_cpp/src/cpp/node/AsyncEdgeNode.cpp | 4 +- .../cpp/types/AmlipGenericTopicDataType.hpp | 22 +- amlip_cpp/src/cpp/types/GenericDataType.cpp | 54 +- amlip_cpp/src/cpp/types/TemplatesDataType.hpp | 699 +++++++++++++++++ .../src/cpp/types/id/AmlipIdDataType.cpp | 59 +- .../types/id/impl/AmlipIdDataTypeCdrAux.ipp | 110 +++ .../types/impl/AmlipGenericTopicDataType.ipp | 57 +- .../src/cpp/types/impl/TemplatesDataType.ipp | 734 ++++++++++++++++++ .../types/impl/TemplatesDataTypeCdrAux.ipp | 355 +++++++++ .../types/model/ModelStatisticsDataType.cpp | 67 +- .../impl/ModelStatisticsDataTypeCdrAux.ipp | 131 ++++ .../src/cpp/types/multiservice/MsDataType.hpp | 193 ----- .../multiservice/MsReferenceDataType.cpp | 29 +- .../multiservice/MsReferenceDataType.hpp | 24 +- .../types/multiservice/MsRequestDataType.cpp | 36 +- .../types/multiservice/MsRequestDataType.hpp | 35 +- .../types/multiservice/impl/MsDataType.ipp | 179 ----- .../impl/MsReferenceDataTypeCdrAux.ipp | 115 +++ .../impl/MsRequestDataTypeCdrAux.ipp | 106 +++ .../src/cpp/types/rpc/RpcReplyDataType.hpp | 314 -------- .../src/cpp/types/rpc/RpcRequestDataType.hpp | 314 -------- .../cpp/types/rpc/impl/RpcReplyDataType.ipp | 308 -------- .../cpp/types/rpc/impl/RpcRequestDataType.ipp | 309 -------- .../src/cpp/types/status/StatusDataType.cpp | 50 +- .../status/impl/StatusDataTypeCdrAux.ipp | 114 +++ .../communication/agent/agentTest.cpp | 17 +- .../modelManagerTest.cpp | 4 +- .../asyncMainComputingNodeTest.cpp | 6 +- .../communication/asyncMultiserviceTest.cpp | 103 ++- .../communication/directMessageTest.cpp | 3 +- .../communication/multiserviceTest.cpp | 106 ++- .../communication/publicationTest.cpp | 1 - amlip_cpp/test/manual/node/agent_client.cpp | 1 + amlip_cpp/test/manual/node/agent_repeater.cpp | 1 + amlip_cpp/test/manual/node/agent_server.cpp | 1 + .../test/unittest/dds/ddsHandlerTest.cpp | 3 +- .../unittest/dds/entitiesCreationTest.cpp | 5 +- .../test/unittest/dds/participantTest.cpp | 2 + .../test/unittest/node/nodeCreationTest.cpp | 24 +- amlip_cpp/test/unittest/types/amlipIdTest.cpp | 11 +- .../unittest/types/genericDataTypeTest.cpp | 6 +- .../unittest/types/modelStatisticsTest.cpp | 4 +- .../swig/amlip_swig/types/GenericDataType.i | 2 + 59 files changed, 3102 insertions(+), 2022 deletions(-) create mode 100644 amlip_cpp/include/amlip_cpp/types/impl/GenericDataTypeCdrAux.ipp create mode 100644 amlip_cpp/src/cpp/types/TemplatesDataType.hpp create mode 100644 amlip_cpp/src/cpp/types/id/impl/AmlipIdDataTypeCdrAux.ipp create mode 100644 amlip_cpp/src/cpp/types/impl/TemplatesDataType.ipp create mode 100644 amlip_cpp/src/cpp/types/impl/TemplatesDataTypeCdrAux.ipp create mode 100644 amlip_cpp/src/cpp/types/model/impl/ModelStatisticsDataTypeCdrAux.ipp delete mode 100644 amlip_cpp/src/cpp/types/multiservice/MsDataType.hpp delete mode 100644 amlip_cpp/src/cpp/types/multiservice/impl/MsDataType.ipp create mode 100644 amlip_cpp/src/cpp/types/multiservice/impl/MsReferenceDataTypeCdrAux.ipp create mode 100644 amlip_cpp/src/cpp/types/multiservice/impl/MsRequestDataTypeCdrAux.ipp delete mode 100644 amlip_cpp/src/cpp/types/rpc/RpcReplyDataType.hpp delete mode 100644 amlip_cpp/src/cpp/types/rpc/RpcRequestDataType.hpp delete mode 100644 amlip_cpp/src/cpp/types/rpc/impl/RpcReplyDataType.ipp delete mode 100644 amlip_cpp/src/cpp/types/rpc/impl/RpcRequestDataType.ipp create mode 100644 amlip_cpp/src/cpp/types/status/impl/StatusDataTypeCdrAux.ipp diff --git a/amlip_cpp/include/amlip_cpp/node/AsyncEdgeNode.hpp b/amlip_cpp/include/amlip_cpp/node/AsyncEdgeNode.hpp index 2dd77c5a..700bfc0e 100644 --- a/amlip_cpp/include/amlip_cpp/node/AsyncEdgeNode.hpp +++ b/amlip_cpp/include/amlip_cpp/node/AsyncEdgeNode.hpp @@ -22,10 +22,10 @@ #include -#include #include #include #include +#include // Forward declaration of dds classes namespace eprosima { diff --git a/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerReceiverNode.hpp b/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerReceiverNode.hpp index 2b4d9d15..f00ec4a1 100644 --- a/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerReceiverNode.hpp +++ b/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerReceiverNode.hpp @@ -21,15 +21,15 @@ #include -#include - -#include - #include #include #include #include +#include + +#include + // Forward declaration of dds classes namespace eprosima { diff --git a/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerSenderNode.hpp b/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerSenderNode.hpp index 958863d0..316c8c54 100644 --- a/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerSenderNode.hpp +++ b/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerSenderNode.hpp @@ -21,15 +21,15 @@ #include -#include - -#include - #include #include #include #include +#include + +#include + // Forward declaration of dds classes namespace eprosima { diff --git a/amlip_cpp/include/amlip_cpp/types/GenericDataType.hpp b/amlip_cpp/include/amlip_cpp/types/GenericDataType.hpp index b763589b..ded260e3 100644 --- a/amlip_cpp/include/amlip_cpp/types/GenericDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/GenericDataType.hpp @@ -24,15 +24,11 @@ #include #include +#include + #include #include -namespace eprosima { -namespace fastcdr { -class Cdr; -} // namespace fastcdr -} // namespace eprosima - namespace eprosima { namespace amlip { @@ -122,43 +118,53 @@ class GenericDataType : public InterfaceDataType const GenericDataType& x) const; /*! - * @brief Return value of attribute \c data_ + * @brief This function copies the value in member \c data_ + * @param data New value to be copied in member id \c data_ + */ + AMLIP_CPP_DllAPI void data( + void* data); + + /*! + * @brief Returns value of attribute \c data_ */ AMLIP_CPP_DllAPI void* data() const; /*! - * @brief Return value of attribute \c data__size_ + * @brief Returns value of attribute \c data_size_ */ AMLIP_CPP_DllAPI uint32_t data_size() const; + /*! + * @brief Returns reference to attribute \c data_size_ + */ + AMLIP_CPP_DllAPI uint32_t& data_size(); + /*! * @brief This function returns the name of this specific data type */ AMLIP_CPP_DllAPI static std::string type_name(); - ///// - // InterfaceDataType methods - /*! - * @brief This function serializes an object using CDR serialization. - * @param cdr CDR serialization object. + * @brief This function returns value of attribute \c has_been_allocated_ */ - AMLIP_CPP_DllAPI void serialize( - eprosima::fastcdr::Cdr& cdr) const; + AMLIP_CPP_DllAPI bool has_been_allocated() const; /*! - * @brief This function deserializes an object using CDR serialization. - * @param cdr CDR serialization object. + * @brief This function copies the value in member \c has_been_allocated_ + * @param take_ownership New value to be copied in member \c has_been_allocated_ */ - AMLIP_CPP_DllAPI void deserialize( - eprosima::fastcdr::Cdr& cdr); + AMLIP_CPP_DllAPI void has_been_allocated( + bool take_ownership); + + ///// + // InterfaceDataType methods /*! * @brief This function serializes the key members of an object using CDR serialization. * @param cdr CDR serialization object. */ AMLIP_CPP_DllAPI void serialize_key( - eprosima::fastcdr::Cdr& cdr) const; + eprosima::fastcdr::Cdr& cdr) const override; /*! * @brief This function returns the maximum serialized size of an object diff --git a/amlip_cpp/include/amlip_cpp/types/InterfaceDataType.hpp b/amlip_cpp/include/amlip_cpp/types/InterfaceDataType.hpp index 86519cb0..f728c6ad 100644 --- a/amlip_cpp/include/amlip_cpp/types/InterfaceDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/InterfaceDataType.hpp @@ -47,26 +47,6 @@ class AMLIP_CPP_DllAPI InterfaceDataType { public: - /*! - * @brief This function serializes an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize( - eprosima::fastcdr::Cdr& cdr) const = 0; - - /*! - * @brief This function deserializes an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void deserialize( - eprosima::fastcdr::Cdr& cdr) = 0; - /*! * @brief This function serializes the key members of an object using CDR serialization. * diff --git a/amlip_cpp/include/amlip_cpp/types/id/AmlipIdDataType.hpp b/amlip_cpp/include/amlip_cpp/types/id/AmlipIdDataType.hpp index 842a109b..b71a07af 100644 --- a/amlip_cpp/include/amlip_cpp/types/id/AmlipIdDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/id/AmlipIdDataType.hpp @@ -28,13 +28,9 @@ #include #include -#include +#include -namespace eprosima { -namespace fastcdr { -class Cdr; -} // namespace fastcdr -} // namespace eprosima +#include namespace eprosima { @@ -155,6 +151,13 @@ class AmlipIdDataType : public InterfaceDataType AMLIP_CPP_DllAPI void name( const std::array& name); + /*! + * @brief This function copies the value in member \c name_ + * @param name New value to be copied in member id \c name_ + */ + AMLIP_CPP_DllAPI void name( + const std::string& name); + /*! * @brief This function gets the value in member \c name as array of octets * @return Value of member \c name_ as array of octets @@ -167,6 +170,12 @@ class AmlipIdDataType : public InterfaceDataType */ AMLIP_CPP_DllAPI std::array id() const; + /*! + * @brief This function returns reference to \c rand_id_ + * @return Reference to \c rand_id_ + */ + AMLIP_CPP_DllAPI std::array& id(); + /*! * @brief This function copies the value in member \c rand_id_ * @param id New value to be copied in member id \c rand_id_ @@ -221,20 +230,6 @@ class AmlipIdDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes an object using CDR serialization. - * @param cdr CDR serialization object. - */ - AMLIP_CPP_DllAPI void serialize( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function deserializes an object using CDR serialization. - * @param cdr CDR serialization object. - */ - AMLIP_CPP_DllAPI void deserialize( - eprosima::fastcdr::Cdr& cdr) override; - /*! * @brief This function serializes the key members of an object using CDR serialization. * @param cdr CDR serialization object. @@ -325,6 +320,14 @@ class AmlipIdDataType : public InterfaceDataType AMLIP_CPP_DllAPI static std::array str_name_to_array_( const std::string& name); + /*! + * @brief This function converts a vector of octets of fixed size to a string. + * @param name Value to be converted given as vector of octets of fixed size + * @return Converted value to a string + */ + AMLIP_CPP_DllAPI static std::string array_name_to_str_( + const std::array& name); + /*! * @brief This function generates a random name as a fixed-length array of octets */ diff --git a/amlip_cpp/include/amlip_cpp/types/impl/GenericDataTypeCdrAux.ipp b/amlip_cpp/include/amlip_cpp/types/impl/GenericDataTypeCdrAux.ipp new file mode 100644 index 00000000..adcd4439 --- /dev/null +++ b/amlip_cpp/include/amlip_cpp/types/impl/GenericDataTypeCdrAux.ipp @@ -0,0 +1,127 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file GenericDataTypeCdrAux.ipp + * This source file contains the definition of a generic type that contains void* data. + */ + +#pragma once + +#include +#include + +#include +using namespace eprosima::fastcdr::exception; + +namespace eprosima { +namespace fastcdr { + + +template<> +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::GenericDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.data_size(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.has_been_allocated(), current_alignment); + + calculated_size += calculator.calculate_array_serialized_size(static_cast(data.data()), + data.data_size(), current_alignment); + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template<> +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::GenericDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.data_size() + << eprosima::fastcdr::MemberId(1) << data.has_been_allocated() + ; + scdr.serialize_array(static_cast(data.data()), data.data_size()); + scdr.end_serialize_type(current_state); +} + +template<> +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::GenericDataType& data) +{ + // If data has been already allocated (it has been already deserialized), we free it + if (data.has_been_allocated()) + { + free(data.data()); + } + + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.data_size(); + break; + + case 1: + bool aux; + dcdr >> aux; + data.has_been_allocated(aux); + break; + + case 2: + + // Store enough space to deserialize the data + data.data(malloc(data.data_size() * sizeof(uint8_t))); + // Deserialize array + dcdr.deserialize_array(static_cast(data.data()), data.data_size()); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/include/amlip_cpp/types/model/ModelStatisticsDataType.hpp b/amlip_cpp/include/amlip_cpp/types/model/ModelStatisticsDataType.hpp index f27b4a75..8fe95e67 100644 --- a/amlip_cpp/include/amlip_cpp/types/model/ModelStatisticsDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/model/ModelStatisticsDataType.hpp @@ -23,14 +23,11 @@ #include #include +#include + #include #include -namespace eprosima { -namespace fastcdr { -class Cdr; -} // namespace fastcdr -} // namespace eprosima namespace eprosima { namespace amlip { @@ -166,6 +163,11 @@ class ModelStatisticsDataType : public InterfaceDataType */ AMLIP_CPP_DllAPI std::string name() const; + /*! + * @return Returns reference to attribute \c name_ + */ + AMLIP_CPP_DllAPI std::string& name(); + /*! * @brief This function copies the value in member \c name_ * @param name New value to be copied in member id \c name_ @@ -174,31 +176,48 @@ class ModelStatisticsDataType : public InterfaceDataType const std::string& name); /*! - * @brief Return value of attribute \c data_ + * @brief This function copies the value in member \c data_ + * @param data New value to be copied in member id \c data_ + */ + AMLIP_CPP_DllAPI void data( + void* data); + + /*! + * @brief Returns value of attribute \c data_ */ AMLIP_CPP_DllAPI void* data() const; /*! - * @brief Return value of attribute \c data_ in std::string + * @brief Returns value of attribute \c data_ in std::string */ AMLIP_CPP_DllAPI std::string to_string() const noexcept; /*! - * @brief Return value of attribute \c data_ in std::vector + * @brief Returns value of attribute \c data_ in std::vector */ AMLIP_CPP_DllAPI std::vector to_vector() const noexcept; /*! - * @brief Return value of attribute \c data_size_ + * @brief Returns value of attribute \c data_size_ */ AMLIP_CPP_DllAPI uint32_t data_size() const; + /*! + * @brief Returns reference to attribute \c data_size_ + */ + AMLIP_CPP_DllAPI uint32_t& data_size(); + /*! * @brief This function gets the value in member \c rand_id as array of octets * @return Value of member \c rand_id_ as array of octets */ AMLIP_CPP_DllAPI AmlipIdDataType server_id() const; + /*! + * @return Returns reference to attribute \c server_id_ + */ + AMLIP_CPP_DllAPI AmlipIdDataType& server_id(); + /*! * @brief This function copies the value in member \c id_ * @param id New value to be copied in member id \c id_ @@ -211,22 +230,20 @@ class ModelStatisticsDataType : public InterfaceDataType */ AMLIP_CPP_DllAPI static std::string type_name(); - ///// - // InterfaceDataType methods - /*! - * @brief This function serializes an object using CDR serialization. - * @param cdr CDR serialization object. + * @brief This function returns value of attribute \c has_been_allocated_ */ - AMLIP_CPP_DllAPI void serialize( - eprosima::fastcdr::Cdr& cdr) const override; + AMLIP_CPP_DllAPI bool has_been_allocated() const; /*! - * @brief This function deserializes an object using CDR serialization. - * @param cdr CDR serialization object. + * @brief This function copies the value in member \c has_been_allocated_ + * @param take_ownership New value to be copied in member \c has_been_allocated_ */ - AMLIP_CPP_DllAPI void deserialize( - eprosima::fastcdr::Cdr& cdr) override; + AMLIP_CPP_DllAPI void has_been_allocated( + bool take_ownership); + + ///// + // InterfaceDataType methods /*! * @brief This function serializes the key members of an object using CDR serialization. diff --git a/amlip_cpp/include/amlip_cpp/types/status/StatusDataType.hpp b/amlip_cpp/include/amlip_cpp/types/status/StatusDataType.hpp index a5281977..f9095ba7 100644 --- a/amlip_cpp/include/amlip_cpp/types/status/StatusDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/status/StatusDataType.hpp @@ -22,6 +22,8 @@ #ifndef AMLIPCPP__SRC_CPP_TYPES_STATUSDATATYPE_HPP #define AMLIPCPP__SRC_CPP_TYPES_STATUSDATATYPE_HPP +#include + #include #include #include @@ -71,12 +73,21 @@ class StatusDataType : public InterfaceDataType //! Get id value AMLIP_CPP_DllAPI AmlipIdDataType id() const noexcept; + //! Get reference id value + AMLIP_CPP_DllAPI AmlipIdDataType& id() noexcept; + //! Get Node Kind value AMLIP_CPP_DllAPI NodeKind node_kind() const noexcept; + //! Get reference Node Kind value + AMLIP_CPP_DllAPI NodeKind& node_kind() noexcept; + //! Get State Kind value AMLIP_CPP_DllAPI StateKind state() const noexcept; + //! Get reference State Kind value + AMLIP_CPP_DllAPI StateKind& state() noexcept; + //! Whether this object is correctly defined, thus none of its internal variables are undefined. AMLIP_CPP_DllAPI bool is_defined() const noexcept; @@ -86,20 +97,6 @@ class StatusDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes an object using CDR serialization. - * @param cdr CDR serialization object. - */ - AMLIP_CPP_DllAPI void serialize( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function deserializes an object using CDR serialization. - * @param cdr CDR serialization object. - */ - AMLIP_CPP_DllAPI void deserialize( - eprosima::fastcdr::Cdr& cdr) override; - /*! * @brief This function serializes the key members of an object using CDR serialization. * @param cdr CDR serialization object. diff --git a/amlip_cpp/src/cpp/dds/Participant.hpp b/amlip_cpp/src/cpp/dds/Participant.hpp index cc07a614..7c410d61 100644 --- a/amlip_cpp/src/cpp/dds/Participant.hpp +++ b/amlip_cpp/src/cpp/dds/Participant.hpp @@ -19,27 +19,24 @@ #ifndef AMLIPCPP__SRC_CPP_DDS_PARTICIPANT_HPP #define AMLIPCPP__SRC_CPP_DDS_PARTICIPANT_HPP -#include -#include -#include -#include -#include -#include - -#include - #include -#include -#include -#include -#include -#include #include #include #include #include #include #include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include namespace eprosima { namespace amlip { diff --git a/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp b/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp index 2c7b546f..1af59243 100644 --- a/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp +++ b/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp @@ -24,14 +24,15 @@ #include #include +#include +#include +#include + #include #include #include #include #include -#include -#include -#include namespace eprosima { namespace amlip { diff --git a/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp b/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp index f7f34463..2f87854d 100644 --- a/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp +++ b/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp @@ -19,14 +19,15 @@ #ifndef AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_ASYNCMULTISERVICESERVER_HPP #define AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_ASYNCMULTISERVICESERVER_HPP +#include +#include +#include + #include #include #include #include #include -#include -#include -#include namespace eprosima { namespace amlip { diff --git a/amlip_cpp/src/cpp/dds/multiservice/MultiServiceClient.hpp b/amlip_cpp/src/cpp/dds/multiservice/MultiServiceClient.hpp index 2d28c631..948e6d7c 100644 --- a/amlip_cpp/src/cpp/dds/multiservice/MultiServiceClient.hpp +++ b/amlip_cpp/src/cpp/dds/multiservice/MultiServiceClient.hpp @@ -19,14 +19,16 @@ #ifndef AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_MULTISERVICECLIENT_HPP #define AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_MULTISERVICECLIENT_HPP +#include +#include +#include +#include + #include #include #include #include #include -#include -#include -#include namespace eprosima { namespace amlip { diff --git a/amlip_cpp/src/cpp/dds/multiservice/MultiServiceServer.hpp b/amlip_cpp/src/cpp/dds/multiservice/MultiServiceServer.hpp index cd1a16eb..a8a3a499 100644 --- a/amlip_cpp/src/cpp/dds/multiservice/MultiServiceServer.hpp +++ b/amlip_cpp/src/cpp/dds/multiservice/MultiServiceServer.hpp @@ -19,14 +19,15 @@ #ifndef AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_MULTISERVICESERVER_HPP #define AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_MULTISERVICESERVER_HPP +#include +#include +#include + #include #include #include #include #include -#include -#include -#include namespace eprosima { namespace amlip { diff --git a/amlip_cpp/src/cpp/dds/rpc/RPCClient.hpp b/amlip_cpp/src/cpp/dds/rpc/RPCClient.hpp index 93133368..a1822123 100644 --- a/amlip_cpp/src/cpp/dds/rpc/RPCClient.hpp +++ b/amlip_cpp/src/cpp/dds/rpc/RPCClient.hpp @@ -19,15 +19,13 @@ #ifndef AMLIPCPP__SRC_CPP_DDS__RPC_RPCCLIENT_HPP #define AMLIPCPP__SRC_CPP_DDS__RPC_RPCCLIENT_HPP +#include +#include + #include #include #include -#include -#include - -#include - namespace eprosima { namespace amlip { namespace dds { diff --git a/amlip_cpp/src/cpp/dds/rpc/RPCServer.hpp b/amlip_cpp/src/cpp/dds/rpc/RPCServer.hpp index 4191c481..c7c19e07 100644 --- a/amlip_cpp/src/cpp/dds/rpc/RPCServer.hpp +++ b/amlip_cpp/src/cpp/dds/rpc/RPCServer.hpp @@ -19,15 +19,13 @@ #ifndef AMLIPCPP__SRC_CPP_DDS_RPC_RPCSERVER_HPP #define AMLIPCPP__SRC_CPP_DDS_RPC_RPCSERVER_HPP +#include +#include + #include #include #include -#include -#include - -#include - namespace eprosima { namespace amlip { namespace dds { diff --git a/amlip_cpp/src/cpp/node/AsyncEdgeNode.cpp b/amlip_cpp/src/cpp/node/AsyncEdgeNode.cpp index b2174012..65b87b90 100644 --- a/amlip_cpp/src/cpp/node/AsyncEdgeNode.cpp +++ b/amlip_cpp/src/cpp/node/AsyncEdgeNode.cpp @@ -19,10 +19,10 @@ #include #include -#include +#include + #include #include -#include namespace eprosima { namespace amlip { diff --git a/amlip_cpp/src/cpp/types/AmlipGenericTopicDataType.hpp b/amlip_cpp/src/cpp/types/AmlipGenericTopicDataType.hpp index 09fd108d..ff42580b 100644 --- a/amlip_cpp/src/cpp/types/AmlipGenericTopicDataType.hpp +++ b/amlip_cpp/src/cpp/types/AmlipGenericTopicDataType.hpp @@ -19,7 +19,10 @@ #ifndef AMLIPCPP__SRC_CPP_TYPES_AMLIPGENERICTOPICDATATYPE_HPP #define AMLIPCPP__SRC_CPP_TYPES_AMLIPGENERICTOPICDATATYPE_HPP +#include #include +#include +#include #include #include @@ -70,7 +73,15 @@ class AmlipGenericTopicDataType : public eprosima::fastdds::dds::TopicDataType, //! \c serialize method overriden from \c TopicDataType virtual bool serialize( void* data, - eprosima::fastrtps::rtps::SerializedPayload_t* payload) override; + eprosima::fastrtps::rtps::SerializedPayload_t* payload) override + { + return serialize(data, payload, eprosima::fastdds::dds::DEFAULT_DATA_REPRESENTATION); + } + + virtual bool serialize( + void* data, + eprosima::fastrtps::rtps::SerializedPayload_t* payload, + eprosima::fastdds::dds::DataRepresentationId_t data_representation) override; //! \c deserialize method overriden from \c TopicDataType virtual bool deserialize( @@ -79,7 +90,14 @@ class AmlipGenericTopicDataType : public eprosima::fastdds::dds::TopicDataType, //! \c getSerializedSizeProvider method overriden from \c TopicDataType virtual std::function getSerializedSizeProvider( - void* data) override; + void* data) override + { + return getSerializedSizeProvider(data, eprosima::fastdds::dds::DEFAULT_DATA_REPRESENTATION); + } + + virtual std::function getSerializedSizeProvider( + void* data, + eprosima::fastdds::dds::DataRepresentationId_t data_representation) override; //! \c getKey method overriden from \c TopicDataType virtual bool getKey( diff --git a/amlip_cpp/src/cpp/types/GenericDataType.cpp b/amlip_cpp/src/cpp/types/GenericDataType.cpp index ab808c94..909abbf7 100644 --- a/amlip_cpp/src/cpp/types/GenericDataType.cpp +++ b/amlip_cpp/src/cpp/types/GenericDataType.cpp @@ -24,10 +24,7 @@ char dummy; } // namespace #endif // _WINID_SIZE -#include - -#include -using namespace eprosima::fastcdr::exception; +#include #include #include @@ -36,7 +33,7 @@ using namespace eprosima::fastcdr::exception; #include #include -#include +#include namespace eprosima { namespace amlip { @@ -49,10 +46,11 @@ GenericDataType::GenericDataType( void* data, const uint32_t size, bool take_ownership /* = false */) - : data_(data) - , data_size_(size) - , has_been_allocated_(take_ownership) { + data_size_ = size; + data_ = malloc(size * sizeof(uint8_t)); + std::memcpy(data_, data, size); + has_been_allocated_.store(take_ownership); } GenericDataType::GenericDataType() @@ -184,6 +182,12 @@ bool GenericDataType::operator !=( return !(*this == x); } +void GenericDataType::data( + void* data) +{ + data_ = data; +} + void* GenericDataType::data() const { return data_; @@ -194,36 +198,25 @@ uint32_t GenericDataType::data_size() const return data_size_; } +uint32_t& GenericDataType::data_size() +{ + return data_size_; +} + std::string GenericDataType::type_name() { return TYPE_NAME_; } -void GenericDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const +bool GenericDataType::has_been_allocated() const { - scdr << data_size_; - scdr.serializeArray(static_cast(data_), data_size_); + return has_been_allocated_.load(); } -void GenericDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) +void GenericDataType::has_been_allocated( + bool take_ownership) { - // If data has been already allocated (it has been already deserialized), we free it - if (has_been_allocated_) - { - free(data_); - } - - dcdr >> data_size_; - - // Store enough space to deserialize the data - data_ = malloc(data_size_ * sizeof(uint8_t)); - // Deserialize array - dcdr.deserializeArray(static_cast(data_), data_size_); - - // Set as this data has been allocated by this class - has_been_allocated_.store(true); + has_been_allocated_.store(take_ownership); } void GenericDataType::serialize_key( @@ -310,3 +303,6 @@ std::ostream& operator <<( } /* namespace types */ } /* namespace amlip */ } /* namespace eprosima */ + +// Include auxiliary functions like for serializing/deserializing. +#include diff --git a/amlip_cpp/src/cpp/types/TemplatesDataType.hpp b/amlip_cpp/src/cpp/types/TemplatesDataType.hpp new file mode 100644 index 00000000..9357b723 --- /dev/null +++ b/amlip_cpp/src/cpp/types/TemplatesDataType.hpp @@ -0,0 +1,699 @@ +// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file TemplatesDataType.hpp + */ + +#include + +#ifndef AMLIPCPP_TYPES_TEMPLATESDATATYPE_HPP +#define AMLIPCPP_TYPES_TEMPLATESDATATYPE_HPP + +#include + +#include +#include + + +namespace eprosima { +namespace amlip { +namespace types { + +/** + * TODO + */ +template +class MsDataType : public MsReferenceDataType +{ + + FORCE_TEMPLATE_SUBCLASS(types::InterfaceDataType, T); + +public: + + MsDataType(); + + MsDataType( + const AmlipIdDataType& client_id, + const TaskId& task_id, + const AmlipIdDataType& server_id, + const T& data); + + MsDataType( + const MsReferenceDataType& reference, + const T& data); + + MsDataType( + MsReferenceDataType&& reference, + T&& data); + + + /*! + * @brief This function serializes the key members of an object using CDR serialization. + * + * @param cdr CDR serialization object. + * + * @warning this method must be overriden in child class. + */ + virtual void serialize_key( + eprosima::fastcdr::Cdr& cdr) const override; + + /*! + * @brief This function returns the maximum serialized size of an object + * depending on the buffer alignment. + * + * @param current_alignment Buffer alignment. + * + * @return Maximum serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_max_cdr_serialized_size( + size_t current_alignment = 0); + + /*! + * @brief This function returns the serialized size of a data depending on the buffer alignment. + * @param data Data which is calculated its serialized size. + * @param current_alignment Buffer alignment. + * + * @return Serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_cdr_serialized_size( + const MsDataType& data, + size_t current_alignment = 0); + + /*! + * @brief This function returns the maximum serialized size of the Key of an object + * depending on the buffer alignment. + * + * @param current_alignment Buffer alignment. + * + * @return Maximum serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_key_max_cdr_serialized_size( + size_t current_alignment = 0); + + /*! + * @brief This function tells you if the Key has been defined for this type + * + * @warning this method must be overriden in child class. + */ + static bool is_key_defined(); + + /** + * @brief Whether the type is bounded + * + * @warning this method must be overriden in child class. + */ + static bool is_bounded(); + + /** + * @brief Whether the type is plain + * + * @warning this method must be overriden in child class. + */ + static bool is_plain(); + + /** + * @brief Construct an empty sample in the memory allocated + * + * @pre The type must be plain + * + * @param memory already allocated memory for the new data + * + * @return true if the construction was successful, false otherwise + * + * @warning this method must be overriden in child class. + */ + static bool construct_sample( + void* memory); + + /** + * @brief Name of the Data Type. This name will be used as the DDS type name. + * + * @warning this method must be overriden in child class. + */ + static std::string type_name(); + + const T& data() const; + + T& data(); + + void data( + T new_value); + +protected: + + static const char* DATA_TYPE_PREFIX_NAME_; + + T data_; +}; + + +template +class RpcRequestDataType : public InterfaceDataType +{ + + FORCE_TEMPLATE_SUBCLASS(types::InterfaceDataType, T); + +public: + + /** + * @brief Default constructor. + */ + RpcRequestDataType(); + + /** + * @brief Construct a new RpcRequestDataType object. + * + * @param client_id Id of the Participant (associated with the RPC Client) + * @param task_id Id of the task + * @param server_id Id of the Participant (associated with the RPC Server) + * @param + * + */ + RpcRequestDataType( + const AmlipIdDataType& client_id, + const TaskId& task_id, + const AmlipIdDataType& server_id, + const T& data); + + /*! + * @brief Default destructor. + */ + virtual ~RpcRequestDataType(); + + /*! + * @brief Copy constructor. + * @param x Reference to the object RpcRequestDataType that will be copied. + */ + RpcRequestDataType( + const RpcRequestDataType& x); + + /*! + * @brief Move constructor. + * @param x Reference to the object RpcRequestDataType that will be copied. + */ + RpcRequestDataType( + RpcRequestDataType&& x); + + /*! + * @brief Copy assignment. + * @param x Reference to the object RpcRequestDataType that will be copied. + */ + RpcRequestDataType& operator =( + const RpcRequestDataType& x); + + /*! + * @brief Move assignment. + * @param x Reference to the object RpcRequestDataType that will be copied. + */ + RpcRequestDataType& operator =( + RpcRequestDataType&& x); + + /*! + * @brief Comparison operator. + * @param x RpcRequestDataType object to compare. + */ + bool operator ==( + const RpcRequestDataType& x) const; + + /*! + * @brief Comparison operator. + * @param x RpcRequestDataType object to compare. + */ + bool operator !=( + const RpcRequestDataType& x) const; + + /*! + * @brief Comparison operator. + * @param x RpcRequestDataType object to compare. + */ + bool operator <( + const RpcRequestDataType& x) const; + + /*! + * @brief Return value of attribute \c client_id_ + */ + AmlipIdDataType client_id() const; + + /*! + * @brief Returns reference of attribute \c client_id_ + */ + AmlipIdDataType& client_id(); + + /*! + * @brief This function copies the value in member \c client_id_ + * @param new_value New value to be copied in member id \c client_id_ + */ + void client_id( + const AmlipIdDataType& new_value); + + /*! + * @brief Return value of attribute \c task_id_ + */ + TaskId task_id() const; + + /*! + * @brief Returns reference of attribute \c task_id_ + */ + TaskId& task_id(); + + /*! + * @brief This function copies the value in member \c task_id_ + * @param new_value New value to be copied in member id \c task_id_ + */ + void task_id( + const TaskId& new_value); + + /*! + * @brief Returns value of attribute \c server_id_ + */ + AmlipIdDataType server_id() const; + + /*! + * @brief Returns reference of attribute \c server_id_ + */ + AmlipIdDataType& server_id(); + + /*! + * @brief This function copies the value in member \c server_id_ + * @param new_value New value to be copied in member id \c server_id_ + */ + void server_id( + const AmlipIdDataType& new_value); + + ///// + // InterfaceDataType methods + + /*! + * @brief This function serializes the key members of an object using CDR serialization. + * + * @param cdr CDR serialization object. + * + * @warning this method must be overriden in child class. + */ + virtual void serialize_key( + eprosima::fastcdr::Cdr& cdr) const override; + + /*! + * @brief This function returns the maximum serialized size of an object + * depending on the buffer alignment. + * + * @param current_alignment Buffer alignment. + * + * @return Maximum serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_max_cdr_serialized_size( + size_t current_alignment = 0); + + /*! + * @brief This function returns the serialized size of a data depending on the buffer alignment. + * @param data Data which is calculated its serialized size. + * @param current_alignment Buffer alignment. + * + * @return Serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_cdr_serialized_size( + const RpcRequestDataType& data, + size_t current_alignment = 0); + + /*! + * @brief This function returns the maximum serialized size of the Key of an object + * depending on the buffer alignment. + * + * @param current_alignment Buffer alignment. + * + * @return Maximum serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_key_max_cdr_serialized_size( + size_t current_alignment = 0); + + /*! + * @brief This function tells you if the Key has been defined for this type + * + * @warning this method must be overriden in child class. + */ + static bool is_key_defined(); + + /** + * @brief Whether the type is bounded + * + * @warning this method must be overriden in child class. + */ + static bool is_bounded(); + + /** + * @brief Whether the type is plain + * + * @warning this method must be overriden in child class. + */ + static bool is_plain(); + + /** + * @brief Construct an empty sample in the memory allocated + * + * @pre The type must be plain + * + * @param memory already allocated memory for the new data + * + * @return true if the construction was successful, false otherwise + * + * @warning this method must be overriden in child class. + */ + static bool construct_sample( + void* memory); + + /** + * @brief Name of the Data Type. This name will be used as the DDS type name. + * + * @warning this method must be overriden in child class. + */ + static std::string type_name(); + + /*! + * @brief Return value of attribute \c data_ + */ + const T& data() const; + + T& data(); + + /*! + * @brief This function copies the value in member \c data_ + * @param new_value New value to be copied in member id \c data_ + */ + void data( + T new_value); + +protected: + + AmlipIdDataType client_id_; + + TaskId task_id_; + + AmlipIdDataType server_id_; + + static const char* DATA_TYPE_PREFIX_NAME_; // "rpc_request" + + T data_; + +}; + +//! \c RpcRequestDataType to stream serializator +template +std::ostream& operator <<( + std::ostream& os, + const RpcRequestDataType& request); + + +template +class RpcReplyDataType : public InterfaceDataType +{ + + FORCE_TEMPLATE_SUBCLASS(types::InterfaceDataType, T); + +public: + + /** + * @brief Default constructor. + */ + RpcReplyDataType(); + + /** + * @brief Construct a new RpcReplyDataType object. + * + * @param client_id Id of the Participant (associated with the RPC Client) + * @param task_id Id of the task + * @param server_id Id of the Participant (associated with the RPC Server) + * @param data + * + */ + RpcReplyDataType( + const AmlipIdDataType& client_id, + const TaskId& task_id, + const AmlipIdDataType& server_id, + const T& data); + + /*! + * @brief Default destructor. + */ + virtual ~RpcReplyDataType(); + + /*! + * @brief Copy constructor. + * @param x Reference to the object RpcReplyDataType that will be copied. + */ + RpcReplyDataType( + const RpcReplyDataType& x); + + /*! + * @brief Move constructor. + * @param x Reference to the object RpcReplyDataType that will be copied. + */ + RpcReplyDataType( + RpcReplyDataType&& x); + + /*! + * @brief Copy assignment. + * @param x Reference to the object RpcReplyDataType that will be copied. + */ + RpcReplyDataType& operator =( + const RpcReplyDataType& x); + + /*! + * @brief Move assignment. + * @param x Reference to the object RpcReplyDataType that will be copied. + */ + RpcReplyDataType& operator =( + RpcReplyDataType&& x); + + /*! + * @brief Comparison operator. + * @param x RpcReplyDataType object to compare. + */ + bool operator ==( + const RpcReplyDataType& x) const; + + /*! + * @brief Comparison operator. + * @param x RpcReplyDataType object to compare. + */ + bool operator !=( + const RpcReplyDataType& x) const; + + /*! + * @brief Comparison operator. + * @param x RpcReplyDataType object to compare. + */ + bool operator <( + const RpcReplyDataType& x) const; + + /*! + * @brief Returns value of attribute \c client_id_ + */ + AmlipIdDataType client_id() const; + + /*! + * @brief Returns reference of attribute \c client_id_ + */ + AmlipIdDataType& client_id(); + + /*! + * @brief This function copies the value in member \c client_id_ + * @param new_value New value to be copied in member id \c client_id_ + */ + void client_id( + const AmlipIdDataType& new_value); + + /*! + * @brief Returns value of attribute \c task_id_ + */ + TaskId task_id() const; + + /*! + * @brief Returns reference of attribute \c task_id_ + */ + TaskId& task_id(); + + /*! + * @brief This function copies the value in member \c task_id_ + * @param new_value New value to be copied in member id \c task_id_ + */ + void task_id( + const TaskId& new_value); + + /*! + * @brief Returns value of attribute \c server_id_ + */ + AmlipIdDataType server_id() const; + + /*! + * @brief Returns reference of attribute \c server_id_ + */ + AmlipIdDataType& server_id(); + + /*! + * @brief This function copies the value in member \c server_id_ + * @param new_value New value to be copied in member id \c server_id_ + */ + void server_id( + const AmlipIdDataType& new_value); + + ///// + // InterfaceDataType methods + + /*! + * @brief This function serializes the key members of an object using CDR serialization. + * + * @param cdr CDR serialization object. + * + * @warning this method must be overriden in child class. + */ + virtual void serialize_key( + eprosima::fastcdr::Cdr& cdr) const override; + + /*! + * @brief This function returns the maximum serialized size of an object + * depending on the buffer alignment. + * + * @param current_alignment Buffer alignment. + * + * @return Maximum serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_max_cdr_serialized_size( + size_t current_alignment = 0); + + /*! + * @brief This function returns the serialized size of a data depending on the buffer alignment. + * @param data Data which is calculated its serialized size. + * @param current_alignment Buffer alignment. + * + * @return Serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_cdr_serialized_size( + const RpcReplyDataType& data, + size_t current_alignment = 0); + + /*! + * @brief This function returns the maximum serialized size of the Key of an object + * depending on the buffer alignment. + * + * @param current_alignment Buffer alignment. + * + * @return Maximum serialized size. + * + * @warning this method must be overriden in child class. + */ + static size_t get_key_max_cdr_serialized_size( + size_t current_alignment = 0); + + /*! + * @brief This function tells you if the Key has been defined for this type + * + * @warning this method must be overriden in child class. + */ + static bool is_key_defined(); + + /** + * @brief Whether the type is bounded + * + * @warning this method must be overriden in child class. + */ + static bool is_bounded(); + + /** + * @brief Whether the type is plain + * + * @warning this method must be overriden in child class. + */ + static bool is_plain(); + + /** + * @brief Construct an empty sample in the memory allocated + * + * @pre The type must be plain + * + * @param memory already allocated memory for the new data + * + * @return true if the construction was successful, false otherwise + * + * @warning this method must be overriden in child class. + */ + static bool construct_sample( + void* memory); + + /** + * @brief Name of the Data Type. This name will be used as the DDS type name. + * + * @warning this method must be overriden in child class. + */ + static std::string type_name(); + + /*! + * @brief Return value of attribute \c data_ + */ + const T& data() const; + + T& data(); + + /*! + * @brief This function copies the value in member \c data_ + * @param new_value New value to be copied in member id \c data_ + */ + void data( + T new_value); + +protected: + + AmlipIdDataType client_id_; + + TaskId task_id_; + + AmlipIdDataType server_id_; + + static const char* DATA_TYPE_PREFIX_NAME_; + + T data_; +}; + +//! \c RpcReplyDataType to stream serializator +template +std::ostream& operator <<( + std::ostream& os, + const RpcReplyDataType& reply); + +} /* namespace types */ +} /* namespace amlip */ +} /* namespace eprosima */ + +// Include auxiliary functions like for serializing/deserializing. +#include + +#include + +#endif // AMLIPCPP_TYPES_TEMPLATESDATATYPE_HPP diff --git a/amlip_cpp/src/cpp/types/id/AmlipIdDataType.cpp b/amlip_cpp/src/cpp/types/id/AmlipIdDataType.cpp index 80478b78..1855ded7 100644 --- a/amlip_cpp/src/cpp/types/id/AmlipIdDataType.cpp +++ b/amlip_cpp/src/cpp/types/id/AmlipIdDataType.cpp @@ -23,10 +23,7 @@ char dummy; // TODO: Check whether this is actually useful and remove if not } // namespace #endif // _WINID_SIZE -#include - -#include -using namespace eprosima::fastcdr::exception; +#include #include #include @@ -40,7 +37,7 @@ using namespace eprosima::fastcdr::exception; #include #include -#include +#include namespace eprosima { namespace amlip { @@ -151,15 +148,7 @@ bool AmlipIdDataType::operator <( std::string AmlipIdDataType::name() const { - auto it = std::find(name_.begin(), name_.end(), '\0'); - if (it != name_.end()) - { - return std::string(std::begin(name_), it); - } - else - { - return std::string(std::begin(name_), std::end(name_)); - } + return array_name_to_str_(name_); } void AmlipIdDataType::name( @@ -168,6 +157,12 @@ void AmlipIdDataType::name( name_ = name; } +void AmlipIdDataType::name( + const std::string& name) +{ + name_ = str_name_to_array_(name); +} + std::array AmlipIdDataType::base64_name() const { return name_; @@ -178,6 +173,11 @@ std::array AmlipIdDataType::id() const return rand_id_; } +std::array& AmlipIdDataType::id() +{ + return rand_id_; +} + void AmlipIdDataType::id( const std::array& id) { @@ -258,6 +258,20 @@ std::array AmlipIdDataType::str_name_to_array_( return char_name_to_array_(name.c_str()); } +std::string AmlipIdDataType::array_name_to_str_( + const std::array& name) +{ + auto it = std::find(name.begin(), name.end(), '\0'); + if (it != name.end()) + { + return std::string(std::begin(name), it); + } + else + { + return std::string(std::begin(name), std::end(name)); + } +} + std::array AmlipIdDataType::random_name_() { // make sure a random seed is properly set in the main scope @@ -287,20 +301,6 @@ std::array AmlipIdDataType::random_id_() return rand_id; } -void AmlipIdDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const -{ - scdr << name_; - scdr << rand_id_; -} - -void AmlipIdDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) -{ - dcdr >> name_; - dcdr >> rand_id_; -} - void AmlipIdDataType::serialize_key( eprosima::fastcdr::Cdr&) const { @@ -362,3 +362,6 @@ std::ostream& operator <<( } /* namespace types */ } /* namespace amlip */ } /* namespace eprosima */ + +// Include auxiliary functions like for serializing/deserializing. +#include diff --git a/amlip_cpp/src/cpp/types/id/impl/AmlipIdDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/id/impl/AmlipIdDataTypeCdrAux.ipp new file mode 100644 index 00000000..576133e0 --- /dev/null +++ b/amlip_cpp/src/cpp/types/id/impl/AmlipIdDataTypeCdrAux.ipp @@ -0,0 +1,110 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file AmlipIdDataTypeCdrAux.ipp + */ + +#pragma once + +#include +#include + + +#include +using namespace eprosima::fastcdr::exception; + +namespace eprosima { +namespace fastcdr { + +template<> +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::AmlipIdDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.name(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.id(), current_alignment); + + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template<> +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::AmlipIdDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.name() + << eprosima::fastcdr::MemberId(1) << data.id() + ; + scdr.end_serialize_type(current_state); +} + +template<> +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::AmlipIdDataType& data) +{ + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: { + std::string aux; + dcdr >> aux; + data.name(aux); + break; + } + + case 1: + dcdr >> data.id(); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +} // namespace fastcdr +} // namespace eprosima diff --git a/amlip_cpp/src/cpp/types/impl/AmlipGenericTopicDataType.ipp b/amlip_cpp/src/cpp/types/impl/AmlipGenericTopicDataType.ipp index 15d094a4..4fdb77f1 100644 --- a/amlip_cpp/src/cpp/types/impl/AmlipGenericTopicDataType.ipp +++ b/amlip_cpp/src/cpp/types/impl/AmlipGenericTopicDataType.ipp @@ -25,8 +25,7 @@ #ifndef AMLIPCPP__SRC_CPP_TYPES_IMPL_AMLIPGENERICTOPICDATATYPE_IPP #define AMLIPCPP__SRC_CPP_TYPES_IMPL_AMLIPGENERICTOPICDATATYPE_IPP -#include -#include +#include #include @@ -36,6 +35,7 @@ namespace types { using SerializedPayload_t = eprosima::fastrtps::rtps::SerializedPayload_t; using InstanceHandle_t = eprosima::fastrtps::rtps::InstanceHandle_t; +using DataRepresentationId_t = eprosima::fastdds::dds::DataRepresentationId_t; template AmlipGenericTopicDataType::AmlipGenericTopicDataType() @@ -63,30 +63,37 @@ AmlipGenericTopicDataType::~AmlipGenericTopicDataType() template bool AmlipGenericTopicDataType::serialize( void* data, - SerializedPayload_t* payload) + SerializedPayload_t* payload, + DataRepresentationId_t data_representation) { T* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload->data), payload->max_size); // Object that serializes the data. - eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN, eprosima::fastcdr::Cdr::DDS_CDR); + eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN, + data_representation == DataRepresentationId_t::XCDR_DATA_REPRESENTATION ? + eprosima::fastcdr::CdrVersion::XCDRv1 : eprosima::fastcdr::CdrVersion::XCDRv2); payload->encapsulation = ser.endianness() == eprosima::fastcdr::Cdr::BIG_ENDIANNESS ? CDR_BE : CDR_LE; - // Serialize encapsulation - ser.serialize_encapsulation(); + ser.set_encoding_flag( + data_representation == DataRepresentationId_t::XCDR_DATA_REPRESENTATION ? + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR : + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2); try { + // Serialize encapsulation + ser.serialize_encapsulation(); // Serialize the object. - p_type->serialize(ser); + ser << *p_type; } - catch (eprosima::fastcdr::exception::NotEnoughMemoryException& /*exception*/) + catch (eprosima::fastcdr::exception::Exception& /*exception*/) { return false; } // Get the serialized length - payload->length = static_cast(ser.getSerializedDataLength()); + payload->length = static_cast(ser.get_serialized_data_length()); return true; } @@ -102,7 +109,7 @@ bool AmlipGenericTopicDataType::deserialize( eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload->data), payload->length); // Object that deserializes the data. - eprosima::fastcdr::Cdr deser(fastbuffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN, eprosima::fastcdr::Cdr::DDS_CDR); + eprosima::fastcdr::Cdr deser(fastbuffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN); // Deserialize encapsulation. deser.read_encapsulation(); @@ -111,9 +118,9 @@ bool AmlipGenericTopicDataType::deserialize( try { // Deserialize the object. - p_type->deserialize(deser); + deser >> *p_type; } - catch (eprosima::fastcdr::exception::NotEnoughMemoryException& /*exception*/) + catch (eprosima::fastcdr::exception::Exception& /*exception*/) { return false; } @@ -123,12 +130,25 @@ bool AmlipGenericTopicDataType::deserialize( template std::function AmlipGenericTopicDataType::getSerializedSizeProvider( - void* data) + void* data, + DataRepresentationId_t data_representation) { - return [data]() -> uint32_t + return [data, data_representation]() -> uint32_t { - return static_cast(T::get_cdr_serialized_size(*static_cast(data))) + - 4u /*encapsulation*/; + try + { + eprosima::fastcdr::CdrSizeCalculator calculator( + data_representation == DataRepresentationId_t::XCDR_DATA_REPRESENTATION ? + eprosima::fastcdr::CdrVersion::XCDRv1 :eprosima::fastcdr::CdrVersion::XCDRv2); + size_t current_alignment {0}; + return static_cast(calculator.calculate_serialized_size( + *static_cast(data), current_alignment)) + + 4u /*encapsulation*/; + } + catch (eprosima::fastcdr::exception::Exception& /*exception*/) + { + return 0; + } }; } @@ -151,11 +171,12 @@ bool AmlipGenericTopicDataType::getKey( // Object that serializes the data. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); - p_type->serialize_key(ser); + static_cast(ser); + static_cast(*p_type); if (force_md5 || T::get_key_max_cdr_serialized_size() > 16) { md5_.init(); - md5_.update(key_buffer_, static_cast(ser.getSerializedDataLength())); + md5_.update(key_buffer_, static_cast(ser.get_serialized_data_length())); md5_.finalize(); for (uint8_t i = 0; i < 16; ++i) { diff --git a/amlip_cpp/src/cpp/types/impl/TemplatesDataType.ipp b/amlip_cpp/src/cpp/types/impl/TemplatesDataType.ipp new file mode 100644 index 00000000..f67ca1aa --- /dev/null +++ b/amlip_cpp/src/cpp/types/impl/TemplatesDataType.ipp @@ -0,0 +1,734 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file TemplatesDataType.ipp + */ + +#ifndef AMLIPCPP_TYPES_TEMPLATESDATATYPE_IPP +#define AMLIPCPP_TYPES_TEMPLATESDATATYPE_IPP + +namespace eprosima { +namespace amlip { +namespace types { + +template +const char* MsDataType::DATA_TYPE_PREFIX_NAME_ = "ms_data_"; + +template +MsDataType::MsDataType() +{ +} + +template +MsDataType::MsDataType( + const AmlipIdDataType& client_id, + const TaskId& task_id, + const AmlipIdDataType& server_id, + const T& data) + : MsReferenceDataType(client_id, task_id, server_id) + , data_(data) +{ +} + +template +MsDataType::MsDataType( + const MsReferenceDataType& reference, + const T& data) + : MsReferenceDataType(reference) + , data_(data) +{ +} + +template +MsDataType::MsDataType( + MsReferenceDataType&& reference, + T&& data) + : MsReferenceDataType(std::move(reference)) + , data_(std::move(data)) +{ +} + +template +void MsDataType::serialize_key( + eprosima::fastcdr::Cdr& cdr) const +{ +} + +template +size_t MsDataType::get_max_cdr_serialized_size( + size_t current_alignment /* = 0 */) +{ + size_t initial_alignment = current_alignment; + + current_alignment += MsReferenceDataType::get_max_cdr_serialized_size(current_alignment); + + current_alignment += T::get_max_cdr_serialized_size(current_alignment); + + return current_alignment - initial_alignment; +} + +template +size_t MsDataType::get_cdr_serialized_size( + const MsDataType& data, + size_t current_alignment /* = 0 */) +{ + size_t initial_alignment = current_alignment; + + current_alignment += MsReferenceDataType::get_cdr_serialized_size(data, current_alignment); + + current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); + + return current_alignment - initial_alignment; +} + +template +size_t MsDataType::get_key_max_cdr_serialized_size( + size_t current_alignment /* = 0 */) +{ + return current_alignment; +} + +template +bool MsDataType::is_key_defined() +{ + return false; +} + +template +bool MsDataType::is_bounded() +{ + return T::is_bounded(); +} + +template +bool MsDataType::is_plain() +{ + return T::is_plain(); +} + +template +bool MsDataType::construct_sample( + void* memory) +{ + if (!is_plain()) + { + return false; + } + else + { + new (memory) MsDataType(); + return true; + } +} + +template +std::string MsDataType::type_name() +{ + // NOTE: there is no easy way to concatenate 2 const chars + std::string result(DATA_TYPE_PREFIX_NAME_); + result.append(T::type_name()); + + return result; +} + +template +const T& MsDataType::data() const +{ + return data_; +} + +template +T& MsDataType::data() +{ + return data_; +} + +template +void MsDataType::data( + T new_value) +{ + data_ = new_value; +} + +template +const char* RpcRequestDataType::DATA_TYPE_PREFIX_NAME_ = "rpc_request"; + +template +RpcRequestDataType::RpcRequestDataType() + : task_id_(0) +{ +} + +template +RpcRequestDataType::RpcRequestDataType( + const AmlipIdDataType& client_id, + const TaskId& task_id, + const AmlipIdDataType& server_id, + const T& data) + : client_id_(client_id) + , task_id_(task_id) + , server_id_(server_id) + , data_(data) +{ +} + +template +RpcRequestDataType::~RpcRequestDataType() +{ +} + +template +RpcRequestDataType::RpcRequestDataType( + const RpcRequestDataType& x) +{ + client_id_ = x.client_id_; + task_id_ = x.task_id_; + server_id_ = x.server_id_; + data_ = x.data_; +} + +template +RpcRequestDataType::RpcRequestDataType( + RpcRequestDataType&& x) +{ + client_id_ = std::move(x.client_id_); + task_id_ = std::move(x.task_id_); + server_id_ = std::move(x.server_id_); + data_ = std::move(x.data_); +} + +template +RpcRequestDataType& RpcRequestDataType::operator =( + const RpcRequestDataType& x) +{ + client_id_ = x.client_id_; + task_id_ = x.task_id_; + server_id_ = x.server_id_; + data_ = x.data_; + + return *this; +} + +template +RpcRequestDataType& RpcRequestDataType::operator =( + RpcRequestDataType&& x) +{ + client_id_ = std::move(x.client_id_); + task_id_ = std::move(x.task_id_); + server_id_ = std::move(x.server_id_); + data_ = std::move(x.data_); + + return *this; +} + +template +bool RpcRequestDataType::operator ==( + const RpcRequestDataType& x) const +{ + return (server_id_ == x.server_id_ && task_id_ == x.task_id_ && client_id_ == x.client_id_ && data_ == x.data_); +} + +template +bool RpcRequestDataType::operator !=( + const RpcRequestDataType& x) const +{ + return !(*this == x); +} + +template +bool RpcRequestDataType::operator <( + const RpcRequestDataType& x) const +{ + if (server_id_ < x.server_id_) + { + return true; + } + else if (x.server_id_ < server_id_) + { + return false; + } + if (client_id_ < x.client_id_) + { + return true; + } + else if (x.client_id_ < client_id_) + { + return false; + } + else + { + return (task_id_ < x.task_id_); + } +} + +template +AmlipIdDataType RpcRequestDataType::client_id() const +{ + return client_id_; +} + +template +AmlipIdDataType& RpcRequestDataType::client_id() +{ + return client_id_; +} + +template +void RpcRequestDataType::client_id( + const AmlipIdDataType& new_value) +{ + client_id_ = new_value; +} + +template +TaskId RpcRequestDataType::task_id() const +{ + return task_id_; +} + +template +TaskId& RpcRequestDataType::task_id() +{ + return task_id_; +} + +template +void RpcRequestDataType::task_id( + const TaskId& new_value) +{ + task_id_ = new_value; +} + +template +AmlipIdDataType RpcRequestDataType::server_id() const +{ + return server_id_; +} + +template +AmlipIdDataType& RpcRequestDataType::server_id() +{ + return server_id_; +} + +template +void RpcRequestDataType::server_id( + const AmlipIdDataType& new_value) +{ + server_id_ = new_value; +} + +template +void RpcRequestDataType::serialize_key( + eprosima::fastcdr::Cdr&) const +{ +} + +template +size_t RpcRequestDataType::get_max_cdr_serialized_size( + size_t current_alignment) +{ + size_t initial_alignment = current_alignment; + + current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); + current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); + current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); + + current_alignment += T::get_max_cdr_serialized_size(current_alignment); + + return current_alignment - initial_alignment; +} + +template +size_t RpcRequestDataType::get_cdr_serialized_size( + const RpcRequestDataType& data, + size_t current_alignment) +{ + size_t initial_alignment = current_alignment; + + current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); + current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); + current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); + + current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); + + return current_alignment - initial_alignment; +} + +template +size_t RpcRequestDataType::get_key_max_cdr_serialized_size( + size_t current_alignment) +{ + return current_alignment; +} + +template +bool RpcRequestDataType::is_key_defined() +{ + return false; +} + +template +bool RpcRequestDataType::is_bounded() +{ + return T::is_bounded(); +} + +template +bool RpcRequestDataType::is_plain() +{ + return T::is_plain(); +} + +template +bool RpcRequestDataType::construct_sample( + void* memory) +{ + if (!is_plain()) + { + return false; + } + else + { + new (memory) RpcRequestDataType(); + return true; + } +} + +template +std::string RpcRequestDataType::type_name() +{ + // NOTE: there is no easy way to concatenate 2 const chars + std::string result(DATA_TYPE_PREFIX_NAME_); + result.append(T::type_name()); + + return result; +} + +template +const T& RpcRequestDataType::data() const +{ + return data_; +} + +template +T& RpcRequestDataType::data() +{ + return data_; +} + +template +void RpcRequestDataType::data( + T new_value) +{ + data_ = new_value; +} + +template +std::ostream& operator <<( + std::ostream& os, + const RpcRequestDataType& request) +{ + os << "RPC-REQUEST{" << request.client_id() << "|" << request.task_id() << "}"; + return os; +} + +template +const char* RpcReplyDataType::DATA_TYPE_PREFIX_NAME_ = "rpc_reply"; + +template +RpcReplyDataType::RpcReplyDataType() +{ +} + +template +RpcReplyDataType::RpcReplyDataType( + const AmlipIdDataType& client_id, + const TaskId& task_id, + const AmlipIdDataType& server_id, + const T& data) + : client_id_(client_id) + , task_id_(task_id) + , server_id_(server_id) + , data_(data) +{ +} + +template +RpcReplyDataType::~RpcReplyDataType() +{ +} + +template +RpcReplyDataType::RpcReplyDataType( + const RpcReplyDataType& x) +{ + client_id_ = x.client_id_; + task_id_ = x.task_id_; + server_id_ = x.server_id_; + data_ = x.data_; +} + +template +RpcReplyDataType::RpcReplyDataType( + RpcReplyDataType&& x) +{ + client_id_ = std::move(x.client_id_); + task_id_ = std::move(x.task_id_); + server_id_ = std::move(x.server_id_); + data_ = std::move(x.data_); +} + +template +RpcReplyDataType& RpcReplyDataType::operator =( + const RpcReplyDataType& x) +{ + client_id_ = x.client_id_; + task_id_ = x.task_id_; + server_id_ = x.server_id_; + data_ = x.data_; + + return *this; +} + +template +RpcReplyDataType& RpcReplyDataType::operator =( + RpcReplyDataType&& x) +{ + client_id_ = std::move(x.client_id_); + task_id_ = std::move(x.task_id_); + server_id_ = std::move(x.server_id_); + data_ = std::move(x.data_); + + return *this; +} + +template +bool RpcReplyDataType::operator ==( + const RpcReplyDataType& x) const +{ + return (server_id_ == x.server_id_ && task_id_ == x.task_id_ && client_id_ == x.client_id_ && data_ == x.data_); +} + +template +bool RpcReplyDataType::operator !=( + const RpcReplyDataType& x) const +{ + return !(*this == x); +} + +template +bool RpcReplyDataType::operator <( + const RpcReplyDataType& x) const +{ + if (server_id_ < x.server_id_) + { + return true; + } + else if (x.server_id_ < server_id_) + { + return false; + } + if (client_id_ < x.client_id_) + { + return true; + } + else if (x.client_id_ < client_id_) + { + return false; + } + else + { + return (task_id_ < x.task_id_); + } +} + +template +AmlipIdDataType RpcReplyDataType::client_id() const +{ + return client_id_; +} + +template +AmlipIdDataType& RpcReplyDataType::client_id() +{ + return client_id_; +} + +template +void RpcReplyDataType::client_id( + const AmlipIdDataType& new_value) +{ + client_id_ = new_value; +} + +template +TaskId RpcReplyDataType::task_id() const +{ + return task_id_; +} + +template +TaskId& RpcReplyDataType::task_id() +{ + return task_id_; +} + +template +void RpcReplyDataType::task_id( + const TaskId& new_value) +{ + task_id_ = new_value; +} + +template +AmlipIdDataType RpcReplyDataType::server_id() const +{ + return server_id_; +} + +template +AmlipIdDataType& RpcReplyDataType::server_id() +{ + return server_id_; +} + +template +void RpcReplyDataType::server_id( + const AmlipIdDataType& new_value) +{ + server_id_ = new_value; +} + +template +void RpcReplyDataType::serialize_key( + eprosima::fastcdr::Cdr& cdr) const +{ +} + +template +size_t RpcReplyDataType::get_max_cdr_serialized_size( + size_t current_alignment /* = 0 */) +{ + size_t initial_alignment = current_alignment; + + current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); + current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); + current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); + + current_alignment += T::get_max_cdr_serialized_size(current_alignment); + + return current_alignment - initial_alignment; +} + +template +size_t RpcReplyDataType::get_cdr_serialized_size( + const RpcReplyDataType& data, + size_t current_alignment /* = 0 */) +{ + size_t initial_alignment = current_alignment; + + current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); + current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); + current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); + + current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); + + return current_alignment - initial_alignment; +} + +template +size_t RpcReplyDataType::get_key_max_cdr_serialized_size( + size_t current_alignment /* = 0 */) +{ + return current_alignment; +} + +template +bool RpcReplyDataType::is_key_defined() +{ + return false; +} + +template +bool RpcReplyDataType::is_bounded() +{ + return T::is_bounded(); +} + +template +bool RpcReplyDataType::is_plain() +{ + return T::is_plain(); +} + +template +bool RpcReplyDataType::construct_sample( + void* memory) +{ + if (!is_plain()) + { + return false; + } + else + { + new (memory) RpcReplyDataType(); + return true; + } +} + +template +std::string RpcReplyDataType::type_name() +{ + // NOTE: there is no easy way to concatenate 2 const chars + std::string result(DATA_TYPE_PREFIX_NAME_); + result.append(T::type_name()); + + return result; +} + +template +const T& RpcReplyDataType::data() const +{ + return data_; +} + +template +T& RpcReplyDataType::data() +{ + return data_; +} + +template +void RpcReplyDataType::data( + T new_value) +{ + data_ = new_value; +} + +template +std::ostream& operator <<( + std::ostream& os, + const RpcReplyDataType& reply) +{ + os << "RPC-REPLY{" << reply.server_id() << "|" << reply.task_id() << "}"; + return os; +} + +} /* namespace types */ +} /* namespace amlip */ +} /* namespace eprosima */ + +#endif // AMLIPCPP_TYPES_TEMPLATESDATATYPE_IPP diff --git a/amlip_cpp/src/cpp/types/impl/TemplatesDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/impl/TemplatesDataTypeCdrAux.ipp new file mode 100644 index 00000000..a2dd9a91 --- /dev/null +++ b/amlip_cpp/src/cpp/types/impl/TemplatesDataTypeCdrAux.ipp @@ -0,0 +1,355 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file TemplatesDataTypeCdrAux.cpp + */ + +#pragma once + + +namespace eprosima { +namespace fastcdr { + +class Cdr; +class CdrSizeCalculator; + +template +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const eprosima::amlip::types::MsDataType& data, + size_t& current_alignment); + +template +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const eprosima::amlip::types::MsDataType& data); + +template +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + eprosima::amlip::types::MsDataType& data); + +template +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const eprosima::amlip::types::RpcRequestDataType& data, + size_t& current_alignment); + +template +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const eprosima::amlip::types::RpcRequestDataType& data); + +template +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + eprosima::amlip::types::RpcRequestDataType& data); + +template +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const eprosima::amlip::types::RpcReplyDataType& data, + size_t& current_alignment); + +template +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const eprosima::amlip::types::RpcReplyDataType& data); + +template +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + eprosima::amlip::types::RpcReplyDataType& data); + +} // namespace fastcdr +} // namespace eprosima + +#include +#include + + +#include +using namespace eprosima::fastcdr::exception; + +namespace eprosima { +namespace fastcdr { + +template +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::MsDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.client_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.task_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(2), + data.server_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(3), + data.data(), current_alignment); + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.client_id() + << eprosima::fastcdr::MemberId(1) << data.task_id() + << eprosima::fastcdr::MemberId(2) << data.server_id() + << eprosima::fastcdr::MemberId(3) << data.data() + ; + scdr.end_serialize_type(current_state); +} + +template +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::MsDataType& data) +{ + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.client_id(); + break; + + case 1: + dcdr >> data.task_id(); + break; + + case 2: + dcdr >> data.server_id(); + break; + + case 3: + dcdr >> data.data(); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +template +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::RpcRequestDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.client_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.task_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(2), + data.server_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(3), + data.data(), current_alignment); + + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::RpcRequestDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.client_id() + << eprosima::fastcdr::MemberId(1) << data.task_id() + << eprosima::fastcdr::MemberId(2) << data.server_id() + << eprosima::fastcdr::MemberId(3) << data.data() + ; + scdr.end_serialize_type(current_state); +} + +template +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::RpcRequestDataType& data) +{ + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.client_id(); + break; + case 1: + dcdr >> data.task_id(); + break; + case 2: + dcdr >> data.server_id(); + break; + case 3: + dcdr >> data.data(); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +template +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::RpcReplyDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.client_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.task_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(2), + data.server_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(3), + data.data(), current_alignment); + + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::RpcReplyDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.client_id() + << eprosima::fastcdr::MemberId(1) << data.task_id() + << eprosima::fastcdr::MemberId(2) << data.server_id() + << eprosima::fastcdr::MemberId(3) << data.data() + ; + scdr.end_serialize_type(current_state); +} + +template +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::RpcReplyDataType& data) +{ + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.client_id(); + break; + case 1: + dcdr >> data.task_id(); + break; + case 2: + dcdr >> data.server_id(); + break; + case 3: + dcdr >> data.data(); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/model/ModelStatisticsDataType.cpp b/amlip_cpp/src/cpp/types/model/ModelStatisticsDataType.cpp index ab24bd42..e310e540 100644 --- a/amlip_cpp/src/cpp/types/model/ModelStatisticsDataType.cpp +++ b/amlip_cpp/src/cpp/types/model/ModelStatisticsDataType.cpp @@ -17,26 +17,20 @@ */ -#include - -#include -using namespace eprosima::fastcdr::exception; +#include #include #include #include -#include #include -#include #include -#include #include #include #include #include -#include +#include namespace eprosima { namespace amlip { @@ -263,12 +257,23 @@ std::string ModelStatisticsDataType::name() const return name_; } +std::string& ModelStatisticsDataType::name() +{ + return name_; +} + void ModelStatisticsDataType::name( const std::string& name) { name_ = name; } +void ModelStatisticsDataType::data( + void* data) +{ + data_ = data; +} + void* ModelStatisticsDataType::data() const { return data_; @@ -290,11 +295,21 @@ uint32_t ModelStatisticsDataType::data_size() const return data_size_; } +uint32_t& ModelStatisticsDataType::data_size() +{ + return data_size_; +} + AmlipIdDataType ModelStatisticsDataType::server_id() const { return server_id_; } +AmlipIdDataType& ModelStatisticsDataType::server_id() +{ + return server_id_; +} + void ModelStatisticsDataType::server_id( const AmlipIdDataType& id) { @@ -306,38 +321,15 @@ std::string ModelStatisticsDataType::type_name() return TYPE_NAME_; } -void ModelStatisticsDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const +bool ModelStatisticsDataType::has_been_allocated() const { - scdr << name_.c_str(); - - scdr << data_size_; - scdr.serializeArray(static_cast(data_), data_size_); - - scdr << server_id_; + return has_been_allocated_.load(); } -void ModelStatisticsDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) +void ModelStatisticsDataType::has_been_allocated( + bool take_ownership) { - dcdr >> name_; - - // If data has been already allocated (it has been already deserialized), we free it - if (has_been_allocated_) - { - free(data_); - } - - dcdr >> data_size_; - // Store enough space to deserialize the data - data_ = std::malloc(data_size_ * sizeof(uint8_t)); - // Deserialize array - dcdr.deserializeArray(static_cast(data_), data_size_); - - // Set as this data has been allocated by this class - has_been_allocated_.store(true); - - dcdr >> server_id_; + has_been_allocated_.store(take_ownership); } void ModelStatisticsDataType::serialize_key( @@ -424,3 +416,6 @@ std::ostream& operator <<( } /* namespace types */ } /* namespace amlip */ } /* namespace eprosima */ + +// Include auxiliary functions like for serializing/deserializing. +#include diff --git a/amlip_cpp/src/cpp/types/model/impl/ModelStatisticsDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/model/impl/ModelStatisticsDataTypeCdrAux.ipp new file mode 100644 index 00000000..adf5c924 --- /dev/null +++ b/amlip_cpp/src/cpp/types/model/impl/ModelStatisticsDataTypeCdrAux.ipp @@ -0,0 +1,131 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file ModelStatisticsDataTypeCdrAux.ipp + */ + +#pragma once + +#include +#include + + +#include +using namespace eprosima::fastcdr::exception; + +namespace eprosima { +namespace fastcdr { + + +template<> +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::ModelStatisticsDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.name(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.data_size(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(2), + data.server_id(), current_alignment); + + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template<> +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::ModelStatisticsDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.name() + << eprosima::fastcdr::MemberId(1) << data.data_size() + << eprosima::fastcdr::MemberId(2) << data.server_id() + ; + scdr.serialize_array(static_cast(data.data()), data.data_size()); + scdr.end_serialize_type(current_state); +} + +template<> +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::ModelStatisticsDataType& data) +{ + // If data has been already allocated (it has been already deserialized), we free it + if (data.has_been_allocated()) + { + free(data.data()); + } + + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.name(); + break; + + case 1: + dcdr >> data.data_size(); + break; + + case 2: + dcdr >> data.server_id(); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); + + // Store enough space to deserialize the data + data.data(malloc(data.data_size() * sizeof(uint8_t))); + // Deserialize array + cdr.deserialize_array(static_cast(data.data()), data.data_size()); + + // Set as this data has been allocated by this class + data.has_been_allocated(true); +} + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/multiservice/MsDataType.hpp b/amlip_cpp/src/cpp/types/multiservice/MsDataType.hpp deleted file mode 100644 index 08c993ac..00000000 --- a/amlip_cpp/src/cpp/types/multiservice/MsDataType.hpp +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/*! - * @file MsDataType.hpp - */ - -#ifndef AMLIPCPP_TYPES_MSDATATYPE_HPP -#define AMLIPCPP_TYPES_MSDATATYPE_HPP - -#include - -namespace eprosima { -namespace fastcdr { -// Forward declaration of the CDR class -class Cdr; -} // namespace fastcdr -} // namespace eprosima - -namespace eprosima { -namespace amlip { -namespace types { - -/** - * TODO - */ -template -class MsDataType : public MsReferenceDataType -{ - - FORCE_TEMPLATE_SUBCLASS(types::InterfaceDataType, T); - -public: - - MsDataType(); - - MsDataType( - const AmlipIdDataType& client_id, - const TaskId& task_id, - const AmlipIdDataType& server_id, - const T& data); - - MsDataType( - const MsReferenceDataType& reference, - const T& data); - - MsDataType( - MsReferenceDataType&& reference, - T&& data); - - /*! - * @brief This function serializes an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function deserializes an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void deserialize( - eprosima::fastcdr::Cdr& cdr) override; - - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * - * @return Serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_cdr_serialized_size( - const MsDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - * - * @warning this method must be overriden in child class. - */ - static bool is_key_defined(); - - /** - * @brief Whether the type is bounded - * - * @warning this method must be overriden in child class. - */ - static bool is_bounded(); - - /** - * @brief Whether the type is plain - * - * @warning this method must be overriden in child class. - */ - static bool is_plain(); - - /** - * @brief Construct an empty sample in the memory allocated - * - * @pre The type must be plain - * - * @param memory already allocated memory for the new data - * - * @return true if the construction was successful, false otherwise - * - * @warning this method must be overriden in child class. - */ - static bool construct_sample( - void* memory); - - /** - * @brief Name of the Data Type. This name will be used as the DDS type name. - * - * @warning this method must be overriden in child class. - */ - static std::string type_name(); - - const T& data() const; - - void data( - T new_value); - -protected: - - static const char* DATA_TYPE_PREFIX_NAME_; - - T data_; -}; - -} /* namespace types */ -} /* namespace amlip */ -} /* namespace eprosima */ - -// Include implementation template file -#include - -#endif // AMLIPCPP_TYPES_MSDATATYPE_HPP diff --git a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.cpp b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.cpp index 8a1b6019..742b04e5 100644 --- a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.cpp +++ b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.cpp @@ -16,10 +16,7 @@ * @file MsReferenceDataType.cpp */ -#include - -#include -using namespace eprosima::fastcdr::exception; +#include #include #include @@ -27,7 +24,7 @@ using namespace eprosima::fastcdr::exception; #include #include -#include +#include namespace eprosima { namespace amlip { @@ -133,24 +130,15 @@ AmlipIdDataType MsReferenceDataType::server_id() const return server_id_; } -void MsReferenceDataType::server_id( - const AmlipIdDataType& new_value) -{ - server_id_ = new_value; -} - -void MsReferenceDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const +AmlipIdDataType& MsReferenceDataType::server_id() { - MsRequestDataType::serialize(scdr); - scdr << server_id_; + return server_id_; } -void MsReferenceDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) +void MsReferenceDataType::server_id( + const AmlipIdDataType& new_value) { - MsRequestDataType::deserialize(dcdr); - dcdr >> server_id_; + server_id_ = new_value; } void MsReferenceDataType::serialize_key( @@ -229,3 +217,6 @@ std::ostream& operator <<( } /* namespace types */ } /* namespace amlip */ } /* namespace eprosima */ + +// Include auxiliary functions like for serializing/deserializing. +#include diff --git a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.hpp b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.hpp index bc0528fc..ab20c4f7 100644 --- a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.hpp +++ b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.hpp @@ -27,11 +27,6 @@ #include #include -namespace eprosima { -namespace fastcdr { -class Cdr; -} // namespace fastcdr -} // namespace eprosima namespace eprosima { namespace amlip { @@ -116,6 +111,11 @@ class MsReferenceDataType : public MsRequestDataType */ AmlipIdDataType server_id() const; + /*! + * TODO + */ + AmlipIdDataType& server_id(); + /*! * TODO */ @@ -125,20 +125,6 @@ class MsReferenceDataType : public MsRequestDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes an object using CDR serialization. - * @param cdr CDR serialization object. - */ - void serialize( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function deserializes an object using CDR serialization. - * @param cdr CDR serialization object. - */ - void deserialize( - eprosima::fastcdr::Cdr& cdr) override; - /*! * @brief This function serializes the key members of an object using CDR serialization. * @param cdr CDR serialization object. diff --git a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.cpp b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.cpp index 3db4d19b..1f1121c9 100644 --- a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.cpp +++ b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.cpp @@ -16,10 +16,7 @@ * @file MsRequestDataType.cpp */ -#include - -#include -using namespace eprosima::fastcdr::exception; +#include #include #include @@ -27,7 +24,7 @@ using namespace eprosima::fastcdr::exception; #include #include -#include +#include namespace eprosima { namespace amlip { @@ -117,8 +114,13 @@ AmlipIdDataType MsRequestDataType::client_id() const return client_id_; } +AmlipIdDataType& MsRequestDataType::client_id() +{ + return client_id_; +} + void MsRequestDataType::client_id( - const AmlipIdDataType& new_value) + AmlipIdDataType& new_value) { client_id_ = new_value; } @@ -128,24 +130,15 @@ TaskId MsRequestDataType::task_id() const return task_id_; } -void MsRequestDataType::task_id( - const TaskId& new_value) -{ - task_id_ = new_value; -} - -void MsRequestDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const +TaskId& MsRequestDataType::task_id() { - scdr << client_id_; - scdr << task_id_; + return task_id_; } -void MsRequestDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) +void MsRequestDataType::task_id( + TaskId& new_value) { - dcdr >> client_id_; - dcdr >> task_id_; + task_id_ = new_value; } void MsRequestDataType::serialize_key( @@ -216,3 +209,6 @@ std::ostream& operator <<( } /* namespace types */ } /* namespace amlip */ } /* namespace eprosima */ + +// Include auxiliary functions like for serializing/deserializing. +#include diff --git a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.hpp b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.hpp index 2b125bcf..58f27c13 100644 --- a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.hpp +++ b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.hpp @@ -24,15 +24,12 @@ #include #include +#include + #include #include #include -namespace eprosima { -namespace fastcdr { -class Cdr; -} // namespace fastcdr -} // namespace eprosima namespace eprosima { namespace amlip { @@ -119,36 +116,32 @@ class MsRequestDataType : public InterfaceDataType /*! * TODO */ - void client_id( - const AmlipIdDataType& new_value); + AmlipIdDataType& client_id(); /*! * TODO */ - TaskId task_id() const; + void client_id( + AmlipIdDataType& new_value); /*! * TODO */ - void task_id( - const TaskId& new_value); - - ///// - // InterfaceDataType methods + TaskId task_id() const; /*! - * @brief This function serializes an object using CDR serialization. - * @param cdr CDR serialization object. + * TODO */ - void serialize( - eprosima::fastcdr::Cdr& cdr) const override; + TaskId& task_id(); /*! - * @brief This function deserializes an object using CDR serialization. - * @param cdr CDR serialization object. + * TODO */ - void deserialize( - eprosima::fastcdr::Cdr& cdr) override; + void task_id( + TaskId& new_value); + + ///// + // InterfaceDataType methods /*! * @brief This function serializes the key members of an object using CDR serialization. diff --git a/amlip_cpp/src/cpp/types/multiservice/impl/MsDataType.ipp b/amlip_cpp/src/cpp/types/multiservice/impl/MsDataType.ipp deleted file mode 100644 index b5127441..00000000 --- a/amlip_cpp/src/cpp/types/multiservice/impl/MsDataType.ipp +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/*! - * @file MsDataType.ipp - */ - -#ifndef AMLIPCPP__SRC_CPP_TYPES_IMPL_MSDATATYPE_IPP -#define AMLIPCPP__SRC_CPP_TYPES_IMPL_MSDATATYPE_IPP - -namespace eprosima { -namespace amlip { -namespace types { - -template -const char* MsDataType::DATA_TYPE_PREFIX_NAME_ = "ms_data_"; - -template -MsDataType::MsDataType() -{ -} - -template -MsDataType::MsDataType( - const AmlipIdDataType& client_id, - const TaskId& task_id, - const AmlipIdDataType& server_id, - const T& data) - : MsReferenceDataType(client_id, task_id, server_id) - , data_(data) -{ -} - -template -MsDataType::MsDataType( - const MsReferenceDataType& reference, - const T& data) - : MsReferenceDataType(reference) - , data_(data) -{ -} - -template -MsDataType::MsDataType( - MsReferenceDataType&& reference, - T&& data) - : MsReferenceDataType(std::move(reference)) - , data_(std::move(data)) -{ -} - -template -void MsDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const -{ - MsReferenceDataType::serialize(scdr); - scdr << data_; -} - -template -void MsDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) -{ - MsReferenceDataType::deserialize(dcdr); - dcdr >> data_; -} - -template -void MsDataType::serialize_key( - eprosima::fastcdr::Cdr& cdr) const -{ -} - -template -size_t MsDataType::get_max_cdr_serialized_size( - size_t current_alignment /* = 0 */) -{ - size_t initial_alignment = current_alignment; - - current_alignment += MsReferenceDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_max_cdr_serialized_size(current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t MsDataType::get_cdr_serialized_size( - const MsDataType& data, - size_t current_alignment /* = 0 */) -{ - size_t initial_alignment = current_alignment; - - current_alignment += MsReferenceDataType::get_cdr_serialized_size(data, current_alignment); - - current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t MsDataType::get_key_max_cdr_serialized_size( - size_t current_alignment /* = 0 */) -{ - return current_alignment; -} - -template -bool MsDataType::is_key_defined() -{ - return false; -} - -template -bool MsDataType::is_bounded() -{ - return T::is_bounded(); -} - -template -bool MsDataType::is_plain() -{ - return T::is_plain(); -} - -template -bool MsDataType::construct_sample( - void* memory) -{ - if (!is_plain()) - { - return false; - } - else - { - new (memory) MsDataType(); - return true; - } -} - -template -std::string MsDataType::type_name() -{ - // NOTE: there is no easy way to concatenate 2 const chars - std::string result(DATA_TYPE_PREFIX_NAME_); - result.append(T::type_name()); - - return result; -} - -template -const T& MsDataType::data() const -{ - return data_; -} - -template -void MsDataType::data( - T new_value) -{ - data_ = new_value; -} - -} /* namespace types */ -} /* namespace amlip */ -} /* namespace eprosima */ - -#endif // AMLIPCPP__SRC_CPP_TYPES_IMPL_MSDATATYPE_IPP diff --git a/amlip_cpp/src/cpp/types/multiservice/impl/MsReferenceDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/multiservice/impl/MsReferenceDataTypeCdrAux.ipp new file mode 100644 index 00000000..fe39de74 --- /dev/null +++ b/amlip_cpp/src/cpp/types/multiservice/impl/MsReferenceDataTypeCdrAux.ipp @@ -0,0 +1,115 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file MsReferenceDataTypeCdrAux.ipp + */ + +#pragma once + +#include +#include + + +#include +using namespace eprosima::fastcdr::exception; + +namespace eprosima { +namespace fastcdr { + + +template<> +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::MsReferenceDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.client_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.task_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(2), + data.server_id(), current_alignment); + + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template<> +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsReferenceDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.client_id() + << eprosima::fastcdr::MemberId(1) << data.task_id() + << eprosima::fastcdr::MemberId(2) << data.server_id() + ; + scdr.end_serialize_type(current_state); +} + +template<> +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::MsReferenceDataType& data) +{ + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.client_id(); + break; + + case 1: + dcdr >> data.task_id(); + break; + + case 2: + dcdr >> data.server_id(); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/multiservice/impl/MsRequestDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/multiservice/impl/MsRequestDataTypeCdrAux.ipp new file mode 100644 index 00000000..d6179a57 --- /dev/null +++ b/amlip_cpp/src/cpp/types/multiservice/impl/MsRequestDataTypeCdrAux.ipp @@ -0,0 +1,106 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file MsRequestDataTypeCdrAux.ipp + */ + +#pragma once + +#include +#include + + +#include +using namespace eprosima::fastcdr::exception; + +namespace eprosima { +namespace fastcdr { + + +template<> +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::MsRequestDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.client_id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.task_id(), current_alignment); + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template<> +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsRequestDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.client_id() + << eprosima::fastcdr::MemberId(1) << data.task_id() + ; + scdr.end_serialize_type(current_state); +} + +template<> +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::MsRequestDataType& data) +{ + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.client_id(); + break; + + case 1: + dcdr >> data.task_id(); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/rpc/RpcReplyDataType.hpp b/amlip_cpp/src/cpp/types/rpc/RpcReplyDataType.hpp deleted file mode 100644 index 0254a2fc..00000000 --- a/amlip_cpp/src/cpp/types/rpc/RpcReplyDataType.hpp +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2023 Proyectos y Sistemas de Mantenimiento SL (eProsima). -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/*! - * @file RpcReplyDataType.hpp - */ - -#ifndef AMLIPCPP_TYPES_RPCREPLYDATATYPE_HPP -#define AMLIPCPP_TYPES_RPCREPLYDATATYPE_HPP - -#include -#include -#include -#include - -#include -#include -#include - -namespace eprosima { -namespace fastcdr { -// Forward declaration of the CDR class -class Cdr; -} // namespace fastcdr -} // namespace eprosima - -namespace eprosima { -namespace amlip { -namespace types { - - -template -class RpcReplyDataType : public InterfaceDataType -{ - - FORCE_TEMPLATE_SUBCLASS(types::InterfaceDataType, T); - -public: - - /** - * @brief Default constructor. - */ - RpcReplyDataType(); - - /** - * @brief Construct a new RpcReplyDataType object. - * - * @param client_id Id of the Participant (associated with the RPC Client) - * @param task_id Id of the task - * @param server_id Id of the Participant (associated with the RPC Server) - * @param data - * - */ - RpcReplyDataType( - const AmlipIdDataType& client_id, - const TaskId& task_id, - const AmlipIdDataType& server_id, - const T& data); - - /*! - * @brief Default destructor. - */ - virtual ~RpcReplyDataType(); - - /*! - * @brief Copy constructor. - * @param x Reference to the object RpcReplyDataType that will be copied. - */ - RpcReplyDataType( - const RpcReplyDataType& x); - - /*! - * @brief Move constructor. - * @param x Reference to the object RpcReplyDataType that will be copied. - */ - RpcReplyDataType( - RpcReplyDataType&& x); - - /*! - * @brief Copy assignment. - * @param x Reference to the object RpcReplyDataType that will be copied. - */ - RpcReplyDataType& operator =( - const RpcReplyDataType& x); - - /*! - * @brief Move assignment. - * @param x Reference to the object RpcReplyDataType that will be copied. - */ - RpcReplyDataType& operator =( - RpcReplyDataType&& x); - - /*! - * @brief Comparison operator. - * @param x RpcReplyDataType object to compare. - */ - bool operator ==( - const RpcReplyDataType& x) const; - - /*! - * @brief Comparison operator. - * @param x RpcReplyDataType object to compare. - */ - bool operator !=( - const RpcReplyDataType& x) const; - - /*! - * @brief Comparison operator. - * @param x RpcReplyDataType object to compare. - */ - bool operator <( - const RpcReplyDataType& x) const; - - /*! - * @brief Return value of attribute \c client_id_ - */ - AmlipIdDataType client_id() const; - - /*! - * @brief This function copies the value in member \c client_id_ - * @param new_value New value to be copied in member id \c client_id_ - */ - void client_id( - const AmlipIdDataType& new_value); - - /*! - * @brief Return value of attribute \c task_id_ - */ - TaskId task_id() const; - - /*! - * @brief This function copies the value in member \c task_id_ - * @param new_value New value to be copied in member id \c task_id_ - */ - void task_id( - const TaskId& new_value); - - /*! - * @brief Return value of attribute \c server_id_ - */ - AmlipIdDataType server_id() const; - - /*! - * @brief This function copies the value in member \c server_id_ - * @param new_value New value to be copied in member id \c server_id_ - */ - void server_id( - const AmlipIdDataType& new_value); - - ///// - // InterfaceDataType methods - - /*! - * @brief This function serializes an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function deserializes an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void deserialize( - eprosima::fastcdr::Cdr& cdr) override; - - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * - * @return Serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_cdr_serialized_size( - const RpcReplyDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - * - * @warning this method must be overriden in child class. - */ - static bool is_key_defined(); - - /** - * @brief Whether the type is bounded - * - * @warning this method must be overriden in child class. - */ - static bool is_bounded(); - - /** - * @brief Whether the type is plain - * - * @warning this method must be overriden in child class. - */ - static bool is_plain(); - - /** - * @brief Construct an empty sample in the memory allocated - * - * @pre The type must be plain - * - * @param memory already allocated memory for the new data - * - * @return true if the construction was successful, false otherwise - * - * @warning this method must be overriden in child class. - */ - static bool construct_sample( - void* memory); - - /** - * @brief Name of the Data Type. This name will be used as the DDS type name. - * - * @warning this method must be overriden in child class. - */ - static std::string type_name(); - - /*! - * @brief Return value of attribute \c data_ - */ - const T& data() const; - - /*! - * @brief This function copies the value in member \c data_ - * @param new_value New value to be copied in member id \c data_ - */ - void data( - T new_value); - -protected: - - AmlipIdDataType client_id_; - - TaskId task_id_; - - AmlipIdDataType server_id_; - - static const char* DATA_TYPE_PREFIX_NAME_; - - T data_; -}; - -//! \c RpcReplyDataType to stream serializator -template -std::ostream& operator <<( - std::ostream& os, - const RpcReplyDataType& reply); - -} /* namespace types */ -} /* namespace amlip */ -} /* namespace eprosima */ - -// Include implementation template file -#include - -#endif // AMLIPCPP_TYPES_RPCREPLYDATATYPE_HPP diff --git a/amlip_cpp/src/cpp/types/rpc/RpcRequestDataType.hpp b/amlip_cpp/src/cpp/types/rpc/RpcRequestDataType.hpp deleted file mode 100644 index 57b53be6..00000000 --- a/amlip_cpp/src/cpp/types/rpc/RpcRequestDataType.hpp +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2023 Proyectos y Sistemas de Mantenimiento SL (eProsima). -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/*! - * @file RpcRequestDataType.hpp - */ - -#ifndef AMLIP__SRC_CPP_TYPES_RPCREQUESTDATATYPE_HPP -#define AMLIP__SRC_CPP_TYPES_RPCREQUESTDATATYPE_HPP - -#include -#include -#include -#include - -#include -#include -#include - -namespace eprosima { -namespace fastcdr { -class Cdr; -} // namespace fastcdr -} // namespace eprosima - -namespace eprosima { -namespace amlip { -namespace types { - - -template -class RpcRequestDataType : public InterfaceDataType -{ - - FORCE_TEMPLATE_SUBCLASS(types::InterfaceDataType, T); - -public: - - /** - * @brief Default constructor. - */ - RpcRequestDataType(); - - /** - * @brief Construct a new RpcRequestDataType object. - * - * @param client_id Id of the Participant (associated with the RPC Client) - * @param task_id Id of the task - * @param server_id Id of the Participant (associated with the RPC Server) - * @param - * - */ - RpcRequestDataType( - const AmlipIdDataType& client_id, - const TaskId& task_id, - const AmlipIdDataType& server_id, - const T& data); - - /*! - * @brief Default destructor. - */ - virtual ~RpcRequestDataType(); - - /*! - * @brief Copy constructor. - * @param x Reference to the object RpcRequestDataType that will be copied. - */ - RpcRequestDataType( - const RpcRequestDataType& x); - - /*! - * @brief Move constructor. - * @param x Reference to the object RpcRequestDataType that will be copied. - */ - RpcRequestDataType( - RpcRequestDataType&& x); - - /*! - * @brief Copy assignment. - * @param x Reference to the object RpcRequestDataType that will be copied. - */ - RpcRequestDataType& operator =( - const RpcRequestDataType& x); - - /*! - * @brief Move assignment. - * @param x Reference to the object RpcRequestDataType that will be copied. - */ - RpcRequestDataType& operator =( - RpcRequestDataType&& x); - - /*! - * @brief Comparison operator. - * @param x RpcRequestDataType object to compare. - */ - bool operator ==( - const RpcRequestDataType& x) const; - - /*! - * @brief Comparison operator. - * @param x RpcRequestDataType object to compare. - */ - bool operator !=( - const RpcRequestDataType& x) const; - - /*! - * @brief Comparison operator. - * @param x RpcRequestDataType object to compare. - */ - bool operator <( - const RpcRequestDataType& x) const; - - /*! - * @brief Return value of attribute \c client_id_ - */ - AmlipIdDataType client_id() const; - - /*! - * @brief This function copies the value in member \c client_id_ - * @param new_value New value to be copied in member id \c client_id_ - */ - void client_id( - const AmlipIdDataType& new_value); - - /*! - * @brief Return value of attribute \c task_id_ - */ - TaskId task_id() const; - - /*! - * @brief This function copies the value in member \c task_id_ - * @param new_value New value to be copied in member id \c task_id_ - */ - void task_id( - const TaskId& new_value); - - /*! - * @brief Return value of attribute \c server_id_ - */ - AmlipIdDataType server_id() const; - - /*! - * @brief This function copies the value in member \c server_id_ - * @param new_value New value to be copied in member id \c server_id_ - */ - void server_id( - const AmlipIdDataType& new_value); - - ///// - // InterfaceDataType methods - - /*! - * @brief This function serializes an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function deserializes an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void deserialize( - eprosima::fastcdr::Cdr& cdr) override; - - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * - * @return Serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_cdr_serialized_size( - const RpcRequestDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - * - * @warning this method must be overriden in child class. - */ - static bool is_key_defined(); - - /** - * @brief Whether the type is bounded - * - * @warning this method must be overriden in child class. - */ - static bool is_bounded(); - - /** - * @brief Whether the type is plain - * - * @warning this method must be overriden in child class. - */ - static bool is_plain(); - - /** - * @brief Construct an empty sample in the memory allocated - * - * @pre The type must be plain - * - * @param memory already allocated memory for the new data - * - * @return true if the construction was successful, false otherwise - * - * @warning this method must be overriden in child class. - */ - static bool construct_sample( - void* memory); - - /** - * @brief Name of the Data Type. This name will be used as the DDS type name. - * - * @warning this method must be overriden in child class. - */ - static std::string type_name(); - - /*! - * @brief Return value of attribute \c data_ - */ - const T& data() const; - - /*! - * @brief This function copies the value in member \c data_ - * @param new_value New value to be copied in member id \c data_ - */ - void data( - T new_value); - -protected: - - AmlipIdDataType client_id_; - - TaskId task_id_; - - AmlipIdDataType server_id_; - - static const char* DATA_TYPE_PREFIX_NAME_; // "rpc_request" - - T data_; - -}; - -//! \c RpcRequestDataType to stream serializator -template -std::ostream& operator <<( - std::ostream& os, - const RpcRequestDataType& request); - -} /* namespace types */ -} /* namespace amlip */ -} /* namespace eprosima */ - -// Include implementation template file -#include - -#endif // AMLIP__SRC_CPP_TYPES_RPCREQUESTDATATYPE_HPP diff --git a/amlip_cpp/src/cpp/types/rpc/impl/RpcReplyDataType.ipp b/amlip_cpp/src/cpp/types/rpc/impl/RpcReplyDataType.ipp deleted file mode 100644 index 522e137b..00000000 --- a/amlip_cpp/src/cpp/types/rpc/impl/RpcReplyDataType.ipp +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright 2023 Proyectos y Sistemas de Mantenimiento SL (eProsima). -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/*! - * @file RpcReplyDataType.ipp - */ - -#ifndef AMLIPCPP__SRC_CPP_TYPES_IMPL_RPCREPLYDATATYPE_IPP -#define AMLIPCPP__SRC_CPP_TYPES_IMPL_RPCREPLYDATATYPE_IPP - -namespace eprosima { -namespace amlip { -namespace types { - -template -const char* RpcReplyDataType::DATA_TYPE_PREFIX_NAME_ = "rpc_reply"; - -template -RpcReplyDataType::RpcReplyDataType() -{ -} - -template -RpcReplyDataType::RpcReplyDataType( - const AmlipIdDataType& client_id, - const TaskId& task_id, - const AmlipIdDataType& server_id, - const T& data) - : client_id_(client_id) - , task_id_(task_id) - , server_id_(server_id) - , data_(data) -{ -} - -template -RpcReplyDataType::~RpcReplyDataType() -{ -} - -template -RpcReplyDataType::RpcReplyDataType( - const RpcReplyDataType& x) -{ - client_id_ = x.client_id_; - task_id_ = x.task_id_; - server_id_ = x.server_id_; - data_ = x.data_; -} - -template -RpcReplyDataType::RpcReplyDataType( - RpcReplyDataType&& x) -{ - client_id_ = std::move(x.client_id_); - task_id_ = std::move(x.task_id_); - server_id_ = std::move(x.server_id_); - data_ = std::move(x.data_); -} - -template -RpcReplyDataType& RpcReplyDataType::operator =( - const RpcReplyDataType& x) -{ - client_id_ = x.client_id_; - task_id_ = x.task_id_; - server_id_ = x.server_id_; - data_ = x.data_; - - return *this; -} - -template -RpcReplyDataType& RpcReplyDataType::operator =( - RpcReplyDataType&& x) -{ - client_id_ = std::move(x.client_id_); - task_id_ = std::move(x.task_id_); - server_id_ = std::move(x.server_id_); - data_ = std::move(x.data_); - - return *this; -} - -template -bool RpcReplyDataType::operator ==( - const RpcReplyDataType& x) const -{ - return (server_id_ == x.server_id_ && task_id_ == x.task_id_ && client_id_ == x.client_id_ && data_ == x.data_); -} - -template -bool RpcReplyDataType::operator !=( - const RpcReplyDataType& x) const -{ - return !(*this == x); -} - -template -bool RpcReplyDataType::operator <( - const RpcReplyDataType& x) const -{ - if (server_id_ < x.server_id_) - { - return true; - } - else if (x.server_id_ < server_id_) - { - return false; - } - if (client_id_ < x.client_id_) - { - return true; - } - else if (x.client_id_ < client_id_) - { - return false; - } - else - { - return (task_id_ < x.task_id_); - } -} - -template -AmlipIdDataType RpcReplyDataType::client_id() const -{ - return client_id_; -} - -template -void RpcReplyDataType::client_id( - const AmlipIdDataType& new_value) -{ - client_id_ = new_value; -} - -template -TaskId RpcReplyDataType::task_id() const -{ - return task_id_; -} - -template -void RpcReplyDataType::task_id( - const TaskId& new_value) -{ - task_id_ = new_value; -} - -template -AmlipIdDataType RpcReplyDataType::server_id() const -{ - return server_id_; -} - -template -void RpcReplyDataType::server_id( - const AmlipIdDataType& new_value) -{ - server_id_ = new_value; -} - -template -void RpcReplyDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const -{ - scdr << client_id_; - scdr << task_id_; - scdr << server_id_; - scdr << data_; -} - -template -void RpcReplyDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) -{ - dcdr >> client_id_; - dcdr >> task_id_; - dcdr >> server_id_; - dcdr >> data_; -} - -template -void RpcReplyDataType::serialize_key( - eprosima::fastcdr::Cdr& cdr) const -{ -} - -template -size_t RpcReplyDataType::get_max_cdr_serialized_size( - size_t current_alignment /* = 0 */) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_max_cdr_serialized_size(current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t RpcReplyDataType::get_cdr_serialized_size( - const RpcReplyDataType& data, - size_t current_alignment /* = 0 */) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t RpcReplyDataType::get_key_max_cdr_serialized_size( - size_t current_alignment /* = 0 */) -{ - return current_alignment; -} - -template -bool RpcReplyDataType::is_key_defined() -{ - return false; -} - -template -bool RpcReplyDataType::is_bounded() -{ - return T::is_bounded(); -} - -template -bool RpcReplyDataType::is_plain() -{ - return T::is_plain(); -} - -template -bool RpcReplyDataType::construct_sample( - void* memory) -{ - if (!is_plain()) - { - return false; - } - else - { - new (memory) RpcReplyDataType(); - return true; - } -} - -template -std::string RpcReplyDataType::type_name() -{ - // NOTE: there is no easy way to concatenate 2 const chars - std::string result(DATA_TYPE_PREFIX_NAME_); - result.append(T::type_name()); - - return result; -} - -template -const T& RpcReplyDataType::data() const -{ - return data_; -} - -template -void RpcReplyDataType::data( - T new_value) -{ - data_ = new_value; -} - -template -std::ostream& operator <<( - std::ostream& os, - const RpcReplyDataType& reply) -{ - os << "RPC-REPLY{" << reply.server_id() << "|" << reply.task_id() << "}"; - return os; -} - -} /* namespace types */ -} /* namespace amlip */ -} /* namespace eprosima */ - -#endif // AMLIPCPP__SRC_CPP_TYPES_IMPL_RPCREPLYDATATYPE_IPP diff --git a/amlip_cpp/src/cpp/types/rpc/impl/RpcRequestDataType.ipp b/amlip_cpp/src/cpp/types/rpc/impl/RpcRequestDataType.ipp deleted file mode 100644 index a49b6019..00000000 --- a/amlip_cpp/src/cpp/types/rpc/impl/RpcRequestDataType.ipp +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright 2023 Proyectos y Sistemas de Mantenimiento SL (eProsima). -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/*! - * @file RpcRequestDataType.cpp - */ - -#ifndef AMLIPCPP__SRC_CPP_TYPES_IMPL_RPCREQUESTDATATYPE_IPP -#define AMLIPCPP__SRC_CPP_TYPES_IMPL_RPCREQUESTDATATYPE_IPP - -namespace eprosima { -namespace amlip { -namespace types { - -template -const char* RpcRequestDataType::DATA_TYPE_PREFIX_NAME_ = "rpc_request"; - -template -RpcRequestDataType::RpcRequestDataType() - : task_id_(0) -{ -} - -template -RpcRequestDataType::RpcRequestDataType( - const AmlipIdDataType& client_id, - const TaskId& task_id, - const AmlipIdDataType& server_id, - const T& data) - : client_id_(client_id) - , task_id_(task_id) - , server_id_(server_id) - , data_(data) -{ -} - -template -RpcRequestDataType::~RpcRequestDataType() -{ -} - -template -RpcRequestDataType::RpcRequestDataType( - const RpcRequestDataType& x) -{ - client_id_ = x.client_id_; - task_id_ = x.task_id_; - server_id_ = x.server_id_; - data_ = x.data_; -} - -template -RpcRequestDataType::RpcRequestDataType( - RpcRequestDataType&& x) -{ - client_id_ = std::move(x.client_id_); - task_id_ = std::move(x.task_id_); - server_id_ = std::move(x.server_id_); - data_ = std::move(x.data_); -} - -template -RpcRequestDataType& RpcRequestDataType::operator =( - const RpcRequestDataType& x) -{ - client_id_ = x.client_id_; - task_id_ = x.task_id_; - server_id_ = x.server_id_; - data_ = x.data_; - - return *this; -} - -template -RpcRequestDataType& RpcRequestDataType::operator =( - RpcRequestDataType&& x) -{ - client_id_ = std::move(x.client_id_); - task_id_ = std::move(x.task_id_); - server_id_ = std::move(x.server_id_); - data_ = std::move(x.data_); - - return *this; -} - -template -bool RpcRequestDataType::operator ==( - const RpcRequestDataType& x) const -{ - return (server_id_ == x.server_id_ && task_id_ == x.task_id_ && client_id_ == x.client_id_ && data_ == x.data_); -} - -template -bool RpcRequestDataType::operator !=( - const RpcRequestDataType& x) const -{ - return !(*this == x); -} - -template -bool RpcRequestDataType::operator <( - const RpcRequestDataType& x) const -{ - if (server_id_ < x.server_id_) - { - return true; - } - else if (x.server_id_ < server_id_) - { - return false; - } - if (client_id_ < x.client_id_) - { - return true; - } - else if (x.client_id_ < client_id_) - { - return false; - } - else - { - return (task_id_ < x.task_id_); - } -} - -template -AmlipIdDataType RpcRequestDataType::client_id() const -{ - return client_id_; -} - -template -void RpcRequestDataType::client_id( - const AmlipIdDataType& new_value) -{ - client_id_ = new_value; -} - -template -TaskId RpcRequestDataType::task_id() const -{ - return task_id_; -} - -template -void RpcRequestDataType::task_id( - const TaskId& new_value) -{ - task_id_ = new_value; -} - -template -AmlipIdDataType RpcRequestDataType::server_id() const -{ - return server_id_; -} - -template -void RpcRequestDataType::server_id( - const AmlipIdDataType& new_value) -{ - server_id_ = new_value; -} - -template -void RpcRequestDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const -{ - scdr << client_id_; - scdr << task_id_; - scdr << server_id_; - scdr << data_; -} - -template -void RpcRequestDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) -{ - dcdr >> client_id_; - dcdr >> task_id_; - dcdr >> server_id_; - dcdr >> data_; -} - -template -void RpcRequestDataType::serialize_key( - eprosima::fastcdr::Cdr&) const -{ -} - -template -size_t RpcRequestDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_max_cdr_serialized_size(current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t RpcRequestDataType::get_cdr_serialized_size( - const RpcRequestDataType& data, - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t RpcRequestDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - return current_alignment; -} - -template -bool RpcRequestDataType::is_key_defined() -{ - return false; -} - -template -bool RpcRequestDataType::is_bounded() -{ - return T::is_bounded(); -} - -template -bool RpcRequestDataType::is_plain() -{ - return T::is_plain(); -} - -template -bool RpcRequestDataType::construct_sample( - void* memory) -{ - if (!is_plain()) - { - return false; - } - else - { - new (memory) RpcRequestDataType(); - return true; - } -} - -template -std::string RpcRequestDataType::type_name() -{ - // NOTE: there is no easy way to concatenate 2 const chars - std::string result(DATA_TYPE_PREFIX_NAME_); - result.append(T::type_name()); - - return result; -} - -template -const T& RpcRequestDataType::data() const -{ - return data_; -} - -template -void RpcRequestDataType::data( - T new_value) -{ - data_ = new_value; -} - -template -std::ostream& operator <<( - std::ostream& os, - const RpcRequestDataType& request) -{ - os << "RPC-REQUEST{" << request.client_id() << "|" << request.task_id() << "}"; - return os; -} - -} /* namespace types */ -} /* namespace amlip */ -} /* namespace eprosima */ - -#endif // AMLIPCPP__SRC_CPP_TYPES_IMPL_RPCREQUESTDATATYPE_IPP diff --git a/amlip_cpp/src/cpp/types/status/StatusDataType.cpp b/amlip_cpp/src/cpp/types/status/StatusDataType.cpp index 275d9e17..3e078a54 100644 --- a/amlip_cpp/src/cpp/types/status/StatusDataType.cpp +++ b/amlip_cpp/src/cpp/types/status/StatusDataType.cpp @@ -16,11 +16,11 @@ * @file StatusDataType.cpp */ -#include +#include -#include +#include -#include +#include namespace eprosima { namespace amlip { @@ -63,50 +63,39 @@ AmlipIdDataType StatusDataType::id() const noexcept return id_; } +AmlipIdDataType& StatusDataType::id() noexcept +{ + return id_; +} + NodeKind StatusDataType::node_kind() const noexcept { return node_kind_; } -StateKind StatusDataType::state() const noexcept +NodeKind& StatusDataType::node_kind() noexcept { - return state_; + return node_kind_; } -bool StatusDataType::is_defined() const noexcept +StateKind StatusDataType::state() const noexcept { - return (id().is_defined() && node_kind() != NodeKind::undetermined && state() != StateKind::unknown); + return state_; } -std::string StatusDataType::to_string() const noexcept +StateKind& StatusDataType::state() noexcept { - return utils::generic_to_string(*this); + return state_; } -void StatusDataType::serialize( - eprosima::fastcdr::Cdr& scdr) const +bool StatusDataType::is_defined() const noexcept { - scdr << id_; - scdr << (uint32_t)node_kind_; - scdr << (uint32_t)state_; + return (id().is_defined() && node_kind() != NodeKind::undetermined && state() != StateKind::unknown); } -void StatusDataType::deserialize( - eprosima::fastcdr::Cdr& dcdr) +std::string StatusDataType::to_string() const noexcept { - dcdr >> id_; - - { - uint32_t enum_value = 0; - dcdr >> enum_value; - node_kind_ = (NodeKind)enum_value; - } - - { - uint32_t enum_value = 0; - dcdr >> enum_value; - state_ = (StateKind)enum_value; - } + return utils::generic_to_string(*this); } void StatusDataType::serialize_key( @@ -176,3 +165,6 @@ std::ostream& operator <<( } /* namespace types */ } /* namespace amlip */ } /* namespace eprosima */ + +// Include auxiliary functions like for serializing/deserializing. +#include diff --git a/amlip_cpp/src/cpp/types/status/impl/StatusDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/status/impl/StatusDataTypeCdrAux.ipp new file mode 100644 index 00000000..c9ec809d --- /dev/null +++ b/amlip_cpp/src/cpp/types/status/impl/StatusDataTypeCdrAux.ipp @@ -0,0 +1,114 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file StatusDataTypeCdrAux.ipp + */ + +#pragma once + +#include +#include + + +#include +using namespace eprosima::fastcdr::exception; + +namespace eprosima { +namespace fastcdr { + +template<> +AMLIP_CPP_DllAPI size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const amlip::types::StatusDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.id(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + (uint32_t)data.node_kind(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(2), + (uint32_t)data.state(), current_alignment); + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template<> +AMLIP_CPP_DllAPI void serialize( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::StatusDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.id() + << eprosima::fastcdr::MemberId(1) << (uint32_t)data.node_kind() + << eprosima::fastcdr::MemberId(2) << (uint32_t)data.state() + ; + scdr.end_serialize_type(current_state); +} + +template<> +AMLIP_CPP_DllAPI void deserialize( + eprosima::fastcdr::Cdr& cdr, + amlip::types::StatusDataType& data) +{ + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.id(); + break; + + case 1: + dcdr >> data.node_kind(); + break; + + case 2: + dcdr >> data.state(); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/test/blackbox/communication/agent/agentTest.cpp b/amlip_cpp/test/blackbox/communication/agent/agentTest.cpp index 86f4a010..0f8f355e 100644 --- a/amlip_cpp/test/blackbox/communication/agent/agentTest.cpp +++ b/amlip_cpp/test/blackbox/communication/agent/agentTest.cpp @@ -18,20 +18,21 @@ #include #include -#include - -#include -#include - -#include +#include +#include #include #include #include #include #include -#include -#include + +#include + +#include +#include + +#include namespace test { diff --git a/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp b/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp index 288b1950..9611c22e 100644 --- a/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp +++ b/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp @@ -21,6 +21,7 @@ #include #include + #include #include @@ -145,6 +146,8 @@ TEST(modelManagerTest, ping_pong) eprosima::amlip::types::AmlipIdDataType id_sender("ModelManagerSender"); eprosima::amlip::node::ModelManagerSenderNode model_sender_node(id_sender); + logUser(AMLIPCPP_MANUAL_TEST, "Node sender created: " << model_sender_node << "."); + // Create statistics data std::string data_str = "hello world"; model_sender_node.publish_statistics("v1", data_str); @@ -201,7 +204,6 @@ TEST(modelManagerTest, long_string_statistics) logUser(AMLIPCPP_MANUAL_TEST, "Node sender created: " << model_sender_node << "."); - // Create waiter std::shared_ptr waiter = std::make_shared(false, true); diff --git a/amlip_cpp/test/blackbox/efficiency/workload_distribution/asyncMainComputingNodeTest.cpp b/amlip_cpp/test/blackbox/efficiency/workload_distribution/asyncMainComputingNodeTest.cpp index 3bb277bf..f95b026e 100644 --- a/amlip_cpp/test/blackbox/efficiency/workload_distribution/asyncMainComputingNodeTest.cpp +++ b/amlip_cpp/test/blackbox/efficiency/workload_distribution/asyncMainComputingNodeTest.cpp @@ -18,6 +18,9 @@ #include #include +#include +#include + #include #include #include @@ -25,9 +28,6 @@ #include #include -#include -#include - using namespace eprosima::amlip; namespace test { diff --git a/amlip_cpp/test/integration/communication/asyncMultiserviceTest.cpp b/amlip_cpp/test/integration/communication/asyncMultiserviceTest.cpp index f9c70754..0dcb1b05 100644 --- a/amlip_cpp/test/integration/communication/asyncMultiserviceTest.cpp +++ b/amlip_cpp/test/integration/communication/asyncMultiserviceTest.cpp @@ -19,10 +19,11 @@ #include #include -#include #include #include +#include + namespace test { constexpr const uint32_t N_SERVERS = 4; @@ -446,6 +447,106 @@ TEST(asyncMultiServiceTest, communicate_service_n_to_n) } } +namespace eprosima { +namespace fastcdr { + +template<> +size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const test::TestDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.data_size(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.has_been_allocated(), current_alignment); + + calculated_size += calculator.calculate_array_serialized_size(static_cast(data.data()), + data.data_size(), current_alignment); + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template<> +void serialize( + eprosima::fastcdr::Cdr& scdr, + const test::TestDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.data_size() + << eprosima::fastcdr::MemberId(1) << data.has_been_allocated() + ; + scdr.serialize_array(static_cast(data.data()), data.data_size()); + scdr.end_serialize_type(current_state); +} + +template<> +void deserialize( + eprosima::fastcdr::Cdr& cdr, + test::TestDataType& data) +{ + // If data has been already allocated (it has been already deserialized), we free it + if (data.has_been_allocated()) + { + free(data.data()); + } + + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.data_size(); + break; + + case 1: + bool aux; + dcdr >> aux; + data.has_been_allocated(aux); + break; + + case 2: + + // Store enough space to deserialize the data + data.data(malloc(data.data_size() * sizeof(uint8_t))); + // Deserialize array + dcdr.deserialize_array(static_cast(data.data()), data.data_size()); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +} // namespace fastcdr +} // namespace eprosima + int main( int argc, char** argv) diff --git a/amlip_cpp/test/integration/communication/directMessageTest.cpp b/amlip_cpp/test/integration/communication/directMessageTest.cpp index ea34f579..c99820a3 100644 --- a/amlip_cpp/test/integration/communication/directMessageTest.cpp +++ b/amlip_cpp/test/integration/communication/directMessageTest.cpp @@ -17,9 +17,10 @@ #include -#include #include +#include + namespace eprosima { namespace amlip { namespace dds { diff --git a/amlip_cpp/test/integration/communication/multiserviceTest.cpp b/amlip_cpp/test/integration/communication/multiserviceTest.cpp index 25eed4ab..370e8892 100644 --- a/amlip_cpp/test/integration/communication/multiserviceTest.cpp +++ b/amlip_cpp/test/integration/communication/multiserviceTest.cpp @@ -18,10 +18,11 @@ #include #include -#include #include #include +#include + namespace test { constexpr const uint32_t N_SERVERS = 4; @@ -178,6 +179,109 @@ TEST(MultiServiceTest, communicate_service_n_to_n) } } +#include +using namespace eprosima::fastcdr::exception; + +namespace eprosima { +namespace fastcdr { + +template<> +size_t calculate_serialized_size( + eprosima::fastcdr::CdrSizeCalculator& calculator, + const test::TestDataType& data, + size_t& current_alignment) +{ + static_cast(data); + + eprosima::fastcdr::EncodingAlgorithmFlag previous_encoding = calculator.get_encoding(); + size_t calculated_size {calculator.begin_calculate_type_serialized_size( + eprosima::fastcdr::CdrVersion::XCDRv2 == calculator.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + current_alignment)}; + + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(0), + data.data_size(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(1), + data.has_been_allocated(), current_alignment); + + calculated_size += calculator.calculate_array_serialized_size(static_cast(data.data()), + data.data_size(), current_alignment); + + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); + + return calculated_size; +} + +template<> +void serialize( + eprosima::fastcdr::Cdr& scdr, + const test::TestDataType& data) +{ + eprosima::fastcdr::Cdr::state current_state(scdr); + scdr.begin_serialize_type(current_state, + eprosima::fastcdr::CdrVersion::XCDRv2 == scdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR); + + scdr + << eprosima::fastcdr::MemberId(0) << data.data_size() + << eprosima::fastcdr::MemberId(1) << data.has_been_allocated() + ; + scdr.serialize_array(static_cast(data.data()), data.data_size()); + scdr.end_serialize_type(current_state); +} + +template<> +void deserialize( + eprosima::fastcdr::Cdr& cdr, + test::TestDataType& data) +{ + // If data has been already allocated (it has been already deserialized), we free it + if (data.has_been_allocated()) + { + free(data.data()); + } + + cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? + eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : + eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR, + [&data](eprosima::fastcdr::Cdr& dcdr, const eprosima::fastcdr::MemberId& mid) -> bool + { + bool ret_value = true; + switch (mid.id) + { + case 0: + dcdr >> data.data_size(); + break; + + case 1: + bool aux; + dcdr >> aux; + data.has_been_allocated(aux); + break; + + case 2: + + // Store enough space to deserialize the data + data.data(malloc(data.data_size() * sizeof(uint8_t))); + // Deserialize array + dcdr.deserialize_array(static_cast(data.data()), data.data_size()); + break; + + default: + ret_value = false; + break; + } + return ret_value; + }); +} + +} // namespace fastcdr +} // namespace eprosima + int main( int argc, char** argv) diff --git a/amlip_cpp/test/integration/communication/publicationTest.cpp b/amlip_cpp/test/integration/communication/publicationTest.cpp index 3ac1eef1..eaf7c682 100644 --- a/amlip_cpp/test/integration/communication/publicationTest.cpp +++ b/amlip_cpp/test/integration/communication/publicationTest.cpp @@ -16,7 +16,6 @@ #include #include -#include namespace eprosima { namespace amlip { diff --git a/amlip_cpp/test/manual/node/agent_client.cpp b/amlip_cpp/test/manual/node/agent_client.cpp index f36134ad..14418ee6 100644 --- a/amlip_cpp/test/manual/node/agent_client.cpp +++ b/amlip_cpp/test/manual/node/agent_client.cpp @@ -22,6 +22,7 @@ #include #include + #include #include diff --git a/amlip_cpp/test/manual/node/agent_repeater.cpp b/amlip_cpp/test/manual/node/agent_repeater.cpp index a4ed9c63..ce74d58a 100644 --- a/amlip_cpp/test/manual/node/agent_repeater.cpp +++ b/amlip_cpp/test/manual/node/agent_repeater.cpp @@ -22,6 +22,7 @@ #include #include + #include #include diff --git a/amlip_cpp/test/manual/node/agent_server.cpp b/amlip_cpp/test/manual/node/agent_server.cpp index 1718004b..7c917e37 100644 --- a/amlip_cpp/test/manual/node/agent_server.cpp +++ b/amlip_cpp/test/manual/node/agent_server.cpp @@ -22,6 +22,7 @@ #include #include + #include #include diff --git a/amlip_cpp/test/unittest/dds/ddsHandlerTest.cpp b/amlip_cpp/test/unittest/dds/ddsHandlerTest.cpp index 9e41fb58..45e40845 100644 --- a/amlip_cpp/test/unittest/dds/ddsHandlerTest.cpp +++ b/amlip_cpp/test/unittest/dds/ddsHandlerTest.cpp @@ -15,8 +15,9 @@ #include #include -#include #include + +#include #include namespace eprosima { diff --git a/amlip_cpp/test/unittest/dds/entitiesCreationTest.cpp b/amlip_cpp/test/unittest/dds/entitiesCreationTest.cpp index b81f7a97..0d089f20 100644 --- a/amlip_cpp/test/unittest/dds/entitiesCreationTest.cpp +++ b/amlip_cpp/test/unittest/dds/entitiesCreationTest.cpp @@ -15,9 +15,12 @@ #include #include -#include +#include + #include +#include + using namespace eprosima::amlip::dds; using namespace eprosima::amlip; diff --git a/amlip_cpp/test/unittest/dds/participantTest.cpp b/amlip_cpp/test/unittest/dds/participantTest.cpp index 1fb4734d..df19393e 100644 --- a/amlip_cpp/test/unittest/dds/participantTest.cpp +++ b/amlip_cpp/test/unittest/dds/participantTest.cpp @@ -15,6 +15,8 @@ #include #include +#include + #include constexpr const uint32_t TEST_ITERATIONS = 5; diff --git a/amlip_cpp/test/unittest/node/nodeCreationTest.cpp b/amlip_cpp/test/unittest/node/nodeCreationTest.cpp index f72885a6..d41abdac 100644 --- a/amlip_cpp/test/unittest/node/nodeCreationTest.cpp +++ b/amlip_cpp/test/unittest/node/nodeCreationTest.cpp @@ -15,35 +15,29 @@ #include #include -#include -#include -#include -#include +#include + +#include #include #include -#include +#include +#include +#include #include -#include -#include - -#include -#include -#include -#include - +#include #include #include -#include +#include namespace eprosima { namespace amlip { namespace node { namespace test { -class DummyNode : public ParentNode +class DummyNode : public eprosima::amlip::node::ParentNode { public: diff --git a/amlip_cpp/test/unittest/types/amlipIdTest.cpp b/amlip_cpp/test/unittest/types/amlipIdTest.cpp index 98d2dad4..b42af1ed 100644 --- a/amlip_cpp/test/unittest/types/amlipIdTest.cpp +++ b/amlip_cpp/test/unittest/types/amlipIdTest.cpp @@ -15,10 +15,10 @@ #include #include -#include - -#include #include +#include + +#include using namespace eprosima::amlip::types; using SerializedPayload_t = eprosima::fastrtps::rtps::SerializedPayload_t; @@ -33,7 +33,7 @@ TEST(amlipIdTest, create_id) AmlipIdDataType id = AmlipIdDataType::new_unique_id(name); ASSERT_TRUE(id.is_defined()); - ASSERT_EQ(id.name(), name.substr(0, eprosima::amlip::types::NAME_SIZE)); + ASSERT_EQ(id.name(), name); } /** @@ -60,7 +60,8 @@ TEST(amlipIdTest, serialization_deserialization) AmlipIdDataType id = AmlipIdDataType("TestNode"); AmlipGenericTopicDataType data_type; - SerializedPayload_t payload = SerializedPayload_t(64); + SerializedPayload_t payload(static_cast(data_type.getSerializedSizeProvider(static_cast( + &id))())); data_type.serialize(static_cast(&id), &payload); diff --git a/amlip_cpp/test/unittest/types/genericDataTypeTest.cpp b/amlip_cpp/test/unittest/types/genericDataTypeTest.cpp index eb70c0d4..28139ffa 100644 --- a/amlip_cpp/test/unittest/types/genericDataTypeTest.cpp +++ b/amlip_cpp/test/unittest/types/genericDataTypeTest.cpp @@ -15,11 +15,11 @@ #include #include -#include - -#include #include #include +#include + +#include using namespace eprosima::amlip::types; using SerializedPayload_t = eprosima::fastrtps::rtps::SerializedPayload_t; diff --git a/amlip_cpp/test/unittest/types/modelStatisticsTest.cpp b/amlip_cpp/test/unittest/types/modelStatisticsTest.cpp index 93490f2e..e38aba18 100644 --- a/amlip_cpp/test/unittest/types/modelStatisticsTest.cpp +++ b/amlip_cpp/test/unittest/types/modelStatisticsTest.cpp @@ -17,10 +17,10 @@ #include #include -#include - #include +#include + using namespace eprosima::amlip::types; using SerializedPayload_t = eprosima::fastrtps::rtps::SerializedPayload_t; diff --git a/amlip_swig/src/swig/amlip_swig/types/GenericDataType.i b/amlip_swig/src/swig/amlip_swig/types/GenericDataType.i index bf0a3308..cd9d7cc1 100644 --- a/amlip_swig/src/swig/amlip_swig/types/GenericDataType.i +++ b/amlip_swig/src/swig/amlip_swig/types/GenericDataType.i @@ -36,5 +36,7 @@ namespace std { #include %} +%include + // Include the class interfaces %include From 53d3b8afd3cc8551e6c73f0e4a89e39a667a08cf Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Mon, 1 Apr 2024 16:24:11 +0200 Subject: [PATCH 05/15] Add library Signed-off-by: Irene Bandera --- .../node/collaborative_learning/ModelManagerReceiverNode.hpp | 1 + .../node/collaborative_learning/ModelManagerSenderNode.hpp | 1 + amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp | 2 ++ amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp | 2 ++ 4 files changed, 6 insertions(+) diff --git a/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerReceiverNode.hpp b/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerReceiverNode.hpp index f00ec4a1..486355eb 100644 --- a/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerReceiverNode.hpp +++ b/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerReceiverNode.hpp @@ -20,6 +20,7 @@ #define AMLIPCPP__SRC_CPP_NODE_MODELMANAGERRECEIVERNODE_HPP #include +#include #include #include diff --git a/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerSenderNode.hpp b/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerSenderNode.hpp index 316c8c54..cbfc6be9 100644 --- a/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerSenderNode.hpp +++ b/amlip_cpp/include/amlip_cpp/node/collaborative_learning/ModelManagerSenderNode.hpp @@ -20,6 +20,7 @@ #define AMLIPCPP__SRC_CPP_NODE_MODELMANAGERSENDERNODE_HPP #include +#include #include #include diff --git a/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp b/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp index 1af59243..2465bd9f 100644 --- a/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp +++ b/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceClient.hpp @@ -19,6 +19,8 @@ #ifndef AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_ASYNCMULTISERVICECLIENT_HPP #define AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_ASYNCMULTISERVICECLIENT_HPP +#include + #include #include #include diff --git a/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp b/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp index 2f87854d..60fbd5e1 100644 --- a/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp +++ b/amlip_cpp/src/cpp/dds/multiservice/AsyncMultiServiceServer.hpp @@ -19,6 +19,8 @@ #ifndef AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_ASYNCMULTISERVICESERVER_HPP #define AMLIPCPP__SRC_CPP_DDS_MULTISERVICE_ASYNCMULTISERVICESERVER_HPP +#include + #include #include #include From 460e4b097c37f397dd33ebba17eda780a732cc56 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Mon, 1 Apr 2024 17:07:11 +0200 Subject: [PATCH 06/15] Update log consumer in main.cpp Signed-off-by: Irene Bandera --- tools/agent_tool/src/cpp/main.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/tools/agent_tool/src/cpp/main.cpp b/tools/agent_tool/src/cpp/main.cpp index 617292f3..0b9cc8d4 100644 --- a/tools/agent_tool/src/cpp/main.cpp +++ b/tools/agent_tool/src/cpp/main.cpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include @@ -211,14 +211,25 @@ int main( // Debug { + eprosima::utils::BaseLogConfiguration log_configuration; + + eprosima::utils::LogFilter filter; + + filter[eprosima::fastdds::dds::Log::Kind::Error].set_value(log_filter); + filter[eprosima::fastdds::dds::Log::Kind::Warning].set_value(log_filter); + filter[eprosima::fastdds::dds::Log::Kind::Info].set_value(log_filter); + + log_configuration.set(filter); + log_configuration.set(log_verbosity); + // Remove every consumer eprosima::utils::Log::ClearConsumers(); // Activate log with verbosity, as this will avoid running log thread with not desired kind - eprosima::utils::Log::SetVerbosity(log_verbosity); + eprosima::utils::Log::SetVerbosity(log_configuration.verbosity); eprosima::utils::Log::RegisterConsumer( - std::make_unique(log_filter, log_verbosity)); + std::make_unique(&log_configuration)); } { From f1acfe58503fffe2797c18a334d26b9f37831bc4 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Tue, 2 Apr 2024 07:58:03 +0200 Subject: [PATCH 07/15] Install swig in CI Signed-off-by: Irene Bandera --- .github/actions/project_dependencies/action.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/actions/project_dependencies/action.yml b/.github/actions/project_dependencies/action.yml index c314d111..0c55390f 100644 --- a/.github/actions/project_dependencies/action.yml +++ b/.github/actions/project_dependencies/action.yml @@ -40,6 +40,17 @@ runs: using: composite steps: + - name: Install swig in windows + if: runner.os == 'Windows' + shell: pwsh + run: choco install swig --allow-downgrade --version=4.0.2.04082020 + + - name: Install apt dependencies + uses: eProsima/eProsima-CI/ubuntu/install_apt_packages@v0 + if: runner.os == 'Linux' + with: + packages: swig + - name: Install Fast DDS dependencies uses: eProsima/eProsima-CI/multiplatform/install_fastdds_dependencies@v0 with: From b36e8dca5b9622635488a49225300c99e137134e Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Tue, 2 Apr 2024 08:23:13 +0200 Subject: [PATCH 08/15] Fix AmlipIdDataType initialization with std::array in nodeCreationTest Signed-off-by: Irene Bandera --- amlip_cpp/test/unittest/node/nodeCreationTest.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/amlip_cpp/test/unittest/node/nodeCreationTest.cpp b/amlip_cpp/test/unittest/node/nodeCreationTest.cpp index d41abdac..a8fbc64d 100644 --- a/amlip_cpp/test/unittest/node/nodeCreationTest.cpp +++ b/amlip_cpp/test/unittest/node/nodeCreationTest.cpp @@ -158,9 +158,11 @@ TEST(NodeCreationTest, create_computing) TEST(NodeCreationTest, create_model_sender) { // Create statistics data - eprosima::amlip::types::AmlipIdDataType id({"TestNode"}, {66, 11, 77, 44}); + std::array name = {'T', 'e', 's', 't', 'N', 'o', 'd', 'e'}; + std::array id = {66, 11, 77, 44}; + eprosima::amlip::types::AmlipIdDataType amlip_id(name, id); - node::ModelManagerSenderNode node(id); + node::ModelManagerSenderNode node(amlip_id); ASSERT_EQ(types::StateKind::stopped, node.current_state()); ASSERT_EQ(types::NodeKind::model_sender, node.node_kind()); From fbd611caf351bcc11f4772c583abb747da26da07 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Tue, 2 Apr 2024 08:50:01 +0200 Subject: [PATCH 09/15] Update colcon.meta Windows CI Signed-off-by: Irene Bandera --- .../configurations/Windows/colcon.meta | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/configurations/Windows/colcon.meta b/.github/workflows/configurations/Windows/colcon.meta index 6fe69c23..fb151dc4 100644 --- a/.github/workflows/configurations/Windows/colcon.meta +++ b/.github/workflows/configurations/Windows/colcon.meta @@ -11,6 +11,24 @@ ] }, "amlip_swig": + { + "cmake-args": + [ + "-DCMAKE_CXX_FLAGS='/WX /EHsc'", + "-Ax64", + "-T host=x64" + ] + }, + "amlip_py": + { + "cmake-args": + [ + "-DCMAKE_CXX_FLAGS='/WX /EHsc'", + "-Ax64", + "-T host=x64" + ] + }, + "amlip_agent": { "cmake-args": [ From 6c14390cdd8d2d24d47c29da19d0c495fd58c701 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Tue, 2 Apr 2024 09:48:05 +0200 Subject: [PATCH 10/15] Add logs in modelManagerTest Signed-off-by: Irene Bandera --- .../modelManagerTest.cpp | 81 +++++++++---------- 1 file changed, 38 insertions(+), 43 deletions(-) diff --git a/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp b/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp index 9611c22e..abbc0820 100644 --- a/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp +++ b/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp @@ -41,6 +41,8 @@ class TestModelListener : public eprosima::amlip::node::ModelListener virtual bool statistics_received ( const eprosima::amlip::types::ModelStatisticsDataType statistics) override { + logUser(AMLIPCPP_MANUAL_TEST, "Statistics received: " << statistics << " ."); + if (strcmp(statistics.name().c_str(), "v2") == 0) { std::string data; @@ -58,16 +60,9 @@ class TestModelListener : public eprosima::amlip::node::ModelListener EXPECT_EQ(statistics.to_string(), data); EXPECT_EQ(statistics.data_size(), data.length()); - waiter_->open(); - - return false; - } - else - { - // Decide if we want the model based on the statistics received - return true; } - + // Decide if we want the model based on the statistics received + return true; } virtual bool model_received ( @@ -140,7 +135,7 @@ TEST(modelManagerTest, ping_pong) eprosima::amlip::types::ModelRequestDataType data("MobileNet V1"); eprosima::amlip::node::ModelManagerReceiverNode model_receiver_node(id_receiver, data); - logUser(AMLIPCPP_MANUAL_TEST, "Node created: " << model_receiver_node << ". Creating model..."); + logUser(AMLIPCPP_MANUAL_TEST, "Node created: " << model_receiver_node << ". Creating sender..."); // Create ModelManagerSender Node eprosima::amlip::types::AmlipIdDataType id_sender("ModelManagerSender"); @@ -196,7 +191,7 @@ TEST(modelManagerTest, long_string_statistics) eprosima::amlip::types::ModelRequestDataType data("MobileNet V2"); eprosima::amlip::node::ModelManagerReceiverNode model_receiver_node(id_receiver, data); - logUser(AMLIPCPP_MANUAL_TEST, "Node receiver created: " << model_receiver_node << ". Creating sender..."); + logUser(AMLIPCPP_MANUAL_TEST, "Node created: " << model_receiver_node << ". Creating sender..."); // Create ModelManagerSender Node eprosima::amlip::types::AmlipIdDataType id_sender("ModelManagerSender"); @@ -204,6 +199,22 @@ TEST(modelManagerTest, long_string_statistics) logUser(AMLIPCPP_MANUAL_TEST, "Node sender created: " << model_sender_node << "."); + // Create statistics data + std::string data_str; + + std::ifstream file("../../../resources/el_quijote.txt"); + if (file.is_open()) + { + data_str = std::string((std::istreambuf_iterator(file)), (std::istreambuf_iterator())); + } + else + { + throw std::runtime_error("Failed to open file: ../../../resources/el_quijote.txt"); + } + + logUser(AMLIPCPP_MANUAL_TEST, "Publishing statistics..."); + model_sender_node.publish_statistics("v2", data_str, data_str.length()); + // Create waiter std::shared_ptr waiter = std::make_shared(false, true); @@ -219,21 +230,6 @@ TEST(modelManagerTest, long_string_statistics) model_receiver_node.start(listener); model_sender_node.start(replier); - // Create statistics data - std::string data_str; - - std::ifstream file("../../../resources/el_quijote.txt"); - if (file.is_open()) - { - data_str = std::string((std::istreambuf_iterator(file)), (std::istreambuf_iterator())); - } - else - { - throw std::runtime_error("Failed to open file: ../../../resources/el_quijote.txt"); - } - - model_sender_node.publish_statistics("v2", data_str); - // Wait solution waiter->wait(); @@ -264,7 +260,7 @@ TEST(modelManagerTest, long_vector_statistics) eprosima::amlip::types::ModelRequestDataType data("MobileNet V2"); eprosima::amlip::node::ModelManagerReceiverNode model_receiver_node(id_receiver, data); - logUser(AMLIPCPP_MANUAL_TEST, "Node receiver created: " << model_receiver_node << ". Creating sender..."); + logUser(AMLIPCPP_MANUAL_TEST, "Node created: " << model_receiver_node << ". Creating sender..."); // Create ModelManagerSender Node eprosima::amlip::types::AmlipIdDataType id_sender("ModelManagerSender"); @@ -272,22 +268,6 @@ TEST(modelManagerTest, long_vector_statistics) logUser(AMLIPCPP_MANUAL_TEST, "Node sender created: " << model_sender_node << "."); - - // Create waiter - std::shared_ptr waiter = - std::make_shared(false, true); - - // Create listener - std::shared_ptr listener = - std::make_shared(waiter); - - std::shared_ptr replier = - std::make_shared(); - - // Start nodes - model_receiver_node.start(listener); - model_sender_node.start(replier); - // Create statistics data std::string data_str; @@ -310,6 +290,21 @@ TEST(modelManagerTest, long_vector_statistics) model_sender_node.publish_statistics("v2", data_vector); + // Create waiter + std::shared_ptr waiter = + std::make_shared(false, true); + + // Create listener + std::shared_ptr listener = + std::make_shared(waiter); + + std::shared_ptr replier = + std::make_shared(); + + // Start nodes + model_receiver_node.start(listener); + model_sender_node.start(replier); + // Wait solution waiter->wait(); From 6d88d8a46610adcecc9625a9936f7d4d5f220a9a Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Tue, 2 Apr 2024 16:30:16 +0200 Subject: [PATCH 11/15] Update amlip.repos file Signed-off-by: Irene Bandera --- amlip.repos | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/amlip.repos b/amlip.repos index b38b49bb..daf1b07b 100644 --- a/amlip.repos +++ b/amlip.repos @@ -6,11 +6,11 @@ repositories: fastcdr: type: git url: https://github.com/eProsima/Fast-CDR.git - version: 1.1.x + version: master fastdds: type: git url: https://github.com/eProsima/Fast-DDS.git - version: 2.11.x + version: master dev-utils: type: git url: https://github.com/eProsima/dev-utils.git From 43433718e93235108b7cd4ade92c270dc09863c7 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Fri, 5 Apr 2024 09:20:32 +0200 Subject: [PATCH 12/15] Add serialize_key function for data types and refactor AmlipGenericTopicDataType to use FastCDR v2 Signed-off-by: Irene Bandera --- .../amlip_cpp/types/GenericDataType.hpp | 44 +--- .../amlip_cpp/types/InterfaceDataType.hpp | 57 ------ .../amlip_cpp/types/id/AmlipIdDataType.hpp | 44 +--- .../types/model/ModelStatisticsDataType.hpp | 50 +---- .../amlip_cpp/types/status/StatusDataType.hpp | 48 +---- amlip_cpp/src/cpp/types/GenericDataType.cpp | 50 +---- .../src/cpp/types/GenericDataTypeCdrAux.hpp | 32 +++ amlip_cpp/src/cpp/types/InterfaceDataType.cpp | 28 --- amlip_cpp/src/cpp/types/TemplatesDataType.hpp | 188 ++---------------- .../src/cpp/types/TemplatesDataTypeCdrAux.hpp | 42 ++++ .../src/cpp/types/id/AmlipIdDataType.cpp | 33 --- .../cpp/types/id/AmlipIdDataTypeCdrAux.hpp | 31 +++ .../types/id/impl/AmlipIdDataTypeCdrAux.ipp | 8 + .../types/impl/AmlipGenericTopicDataType.ipp | 26 ++- .../cpp}/types/impl/GenericDataTypeCdrAux.ipp | 8 + .../src/cpp/types/impl/TemplatesDataType.ipp | 164 ++------------- .../types/impl/TemplatesDataTypeCdrAux.ipp | 29 ++- .../types/model/ModelStatisticsDataType.cpp | 55 +---- .../model/ModelStatisticsDataTypeCdrAux.hpp | 31 +++ .../impl/ModelStatisticsDataTypeCdrAux.ipp | 8 + .../multiservice/MsReferenceDataType.cpp | 40 +--- .../multiservice/MsReferenceDataType.hpp | 47 +---- .../MsReferenceDataTypeCdrAux.hpp | 31 +++ .../types/multiservice/MsRequestDataType.cpp | 39 +--- .../types/multiservice/MsRequestDataType.hpp | 46 +---- .../multiservice/MsRequestDataTypeCdrAux.hpp | 31 +++ .../impl/MsReferenceDataTypeCdrAux.ipp | 8 + .../impl/MsRequestDataTypeCdrAux.ipp | 8 + .../src/cpp/types/status/StatusDataType.cpp | 39 +--- .../cpp/types/status/StatusDataTypeCdrAux.hpp | 31 +++ .../status/impl/StatusDataTypeCdrAux.ipp | 8 + .../modelManagerTest.cpp | 53 +++-- 32 files changed, 414 insertions(+), 943 deletions(-) create mode 100644 amlip_cpp/src/cpp/types/GenericDataTypeCdrAux.hpp create mode 100644 amlip_cpp/src/cpp/types/TemplatesDataTypeCdrAux.hpp create mode 100644 amlip_cpp/src/cpp/types/id/AmlipIdDataTypeCdrAux.hpp rename amlip_cpp/{include/amlip_cpp => src/cpp}/types/impl/GenericDataTypeCdrAux.ipp (96%) create mode 100644 amlip_cpp/src/cpp/types/model/ModelStatisticsDataTypeCdrAux.hpp create mode 100644 amlip_cpp/src/cpp/types/multiservice/MsReferenceDataTypeCdrAux.hpp create mode 100644 amlip_cpp/src/cpp/types/multiservice/MsRequestDataTypeCdrAux.hpp create mode 100644 amlip_cpp/src/cpp/types/status/StatusDataTypeCdrAux.hpp diff --git a/amlip_cpp/include/amlip_cpp/types/GenericDataType.hpp b/amlip_cpp/include/amlip_cpp/types/GenericDataType.hpp index ded260e3..57465acd 100644 --- a/amlip_cpp/include/amlip_cpp/types/GenericDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/GenericDataType.hpp @@ -159,46 +159,6 @@ class GenericDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * @param cdr CDR serialization object. - */ - AMLIP_CPP_DllAPI void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * @return Serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_cdr_serialized_size( - const GenericDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - */ - AMLIP_CPP_DllAPI static bool is_key_defined(); - /** * @brief Whether the type is bounded */ @@ -225,6 +185,10 @@ class GenericDataType : public InterfaceDataType AMLIP_CPP_DllAPI std::vector to_vector() const noexcept; + static uint32_t max_cdr_typesize_; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: void* data_; diff --git a/amlip_cpp/include/amlip_cpp/types/InterfaceDataType.hpp b/amlip_cpp/include/amlip_cpp/types/InterfaceDataType.hpp index f728c6ad..3e2d52f9 100644 --- a/amlip_cpp/include/amlip_cpp/types/InterfaceDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/InterfaceDataType.hpp @@ -47,63 +47,6 @@ class AMLIP_CPP_DllAPI InterfaceDataType { public: - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize_key( - eprosima::fastcdr::Cdr& cdr) const = 0; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * - * @return Serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_cdr_serialized_size( - const InterfaceDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - * - * @warning this method must be overriden in child class. - */ - static bool is_key_defined(); - /** * @brief Whether the type is bounded * diff --git a/amlip_cpp/include/amlip_cpp/types/id/AmlipIdDataType.hpp b/amlip_cpp/include/amlip_cpp/types/id/AmlipIdDataType.hpp index b71a07af..7917b168 100644 --- a/amlip_cpp/include/amlip_cpp/types/id/AmlipIdDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/id/AmlipIdDataType.hpp @@ -230,46 +230,6 @@ class AmlipIdDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * @param cdr CDR serialization object. - */ - AMLIP_CPP_DllAPI void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * @return Serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_cdr_serialized_size( - const AmlipIdDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - */ - AMLIP_CPP_DllAPI static bool is_key_defined(); - /** * @brief Whether the type is bounded */ @@ -292,6 +252,10 @@ class AmlipIdDataType : public InterfaceDataType AMLIP_CPP_DllAPI static bool construct_sample( void* memory); + static constexpr uint32_t max_cdr_typesize_ {132UL}; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: std::array name_; diff --git a/amlip_cpp/include/amlip_cpp/types/model/ModelStatisticsDataType.hpp b/amlip_cpp/include/amlip_cpp/types/model/ModelStatisticsDataType.hpp index 8fe95e67..3aba9296 100644 --- a/amlip_cpp/include/amlip_cpp/types/model/ModelStatisticsDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/model/ModelStatisticsDataType.hpp @@ -35,11 +35,6 @@ namespace types { using ByteType = uint8_t; -//! Number of octets conforming the alphanumerical identifier \c name_ -constexpr const uint32_t STATISTICS_NAME_SIZE = 28; -//! Number of octets conforming the alphanumerical identifier \c data_ -constexpr const uint32_t DEFAULT_PREALLOCATED_SIZE_ = 16; - /*! * @brief This class represents the structure ModelStatisticsDataType, which implements \c InterfaceDataType and hence serves * as a communication interface to \c ModelStatistics class. @@ -245,46 +240,6 @@ class ModelStatisticsDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * @param cdr CDR serialization object. - */ - AMLIP_CPP_DllAPI void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * @return Serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_cdr_serialized_size( - const ModelStatisticsDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - */ - AMLIP_CPP_DllAPI static bool is_key_defined(); - /** * @brief Whether the type is bounded */ @@ -307,6 +262,10 @@ class ModelStatisticsDataType : public InterfaceDataType AMLIP_CPP_DllAPI static bool construct_sample( void* memory); + static uint32_t max_cdr_typesize_; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: std::string name_; @@ -318,6 +277,7 @@ class ModelStatisticsDataType : public InterfaceDataType AmlipIdDataType server_id_; static const char* TYPE_NAME_; + }; //! \c ModelStatisticsDataType to stream serializator diff --git a/amlip_cpp/include/amlip_cpp/types/status/StatusDataType.hpp b/amlip_cpp/include/amlip_cpp/types/status/StatusDataType.hpp index f9095ba7..fbbdaae1 100644 --- a/amlip_cpp/include/amlip_cpp/types/status/StatusDataType.hpp +++ b/amlip_cpp/include/amlip_cpp/types/status/StatusDataType.hpp @@ -97,46 +97,6 @@ class StatusDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * @param cdr CDR serialization object. - */ - AMLIP_CPP_DllAPI void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * @return Serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_cdr_serialized_size( - const StatusDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - AMLIP_CPP_DllAPI static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - */ - AMLIP_CPP_DllAPI static bool is_key_defined(); - /** * @brief Whether the type is bounded */ @@ -166,6 +126,10 @@ class StatusDataType : public InterfaceDataType */ AMLIP_CPP_DllAPI static std::string type_name(); + static constexpr uint32_t max_cdr_typesize_ {140UL}; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: //! Internal variable Id @@ -177,8 +141,8 @@ class StatusDataType : public InterfaceDataType //! Internal variable State Kind StateKind state_; - //! Name of the DDSDataType for topics that uses this Data Type - static const char* DATA_TYPE_NAME_; // "status" + static const char* TYPE_NAME_; + }; //! \c StatusDataType to stream serializator diff --git a/amlip_cpp/src/cpp/types/GenericDataType.cpp b/amlip_cpp/src/cpp/types/GenericDataType.cpp index 909abbf7..bd58b420 100644 --- a/amlip_cpp/src/cpp/types/GenericDataType.cpp +++ b/amlip_cpp/src/cpp/types/GenericDataType.cpp @@ -40,7 +40,7 @@ namespace amlip { namespace types { const char* GenericDataType::TYPE_NAME_ = "GENERIC"; -const size_t GenericDataType::DEFAULT_PREALLOCATED_SIZE_ = 16; +uint32_t GenericDataType::max_cdr_typesize_ = 132UL; GenericDataType::GenericDataType( void* data, @@ -219,52 +219,6 @@ void GenericDataType::has_been_allocated( has_been_allocated_.store(take_ownership); } -void GenericDataType::serialize_key( - eprosima::fastcdr::Cdr&) const -{ -} - -size_t GenericDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - // It needs an upper bound, but it will not be used - current_alignment += DEFAULT_PREALLOCATED_SIZE_ + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); - - return current_alignment - initial_alignment; -} - -size_t GenericDataType::get_cdr_serialized_size( - const GenericDataType& data, - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - - if (data.data_size() > 0) - { - current_alignment += data.data_size() + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); - } - - return current_alignment - initial_alignment; -} - -size_t GenericDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - return current_alignment; -} - -bool GenericDataType::is_key_defined() -{ - return false; -} - bool GenericDataType::is_bounded() { return false; @@ -305,4 +259,4 @@ std::ostream& operator <<( } /* namespace eprosima */ // Include auxiliary functions like for serializing/deserializing. -#include +#include diff --git a/amlip_cpp/src/cpp/types/GenericDataTypeCdrAux.hpp b/amlip_cpp/src/cpp/types/GenericDataTypeCdrAux.hpp new file mode 100644 index 00000000..71a34b18 --- /dev/null +++ b/amlip_cpp/src/cpp/types/GenericDataTypeCdrAux.hpp @@ -0,0 +1,32 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file GenericDataTypeCdrAux.ipp + * This source file contains the definition of a generic type that contains void* data. + */ + +#pragma once + +#include + +namespace eprosima { +namespace fastcdr { + +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::GenericDataType& data); + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/InterfaceDataType.cpp b/amlip_cpp/src/cpp/types/InterfaceDataType.cpp index 3bee9d31..6d932511 100644 --- a/amlip_cpp/src/cpp/types/InterfaceDataType.cpp +++ b/amlip_cpp/src/cpp/types/InterfaceDataType.cpp @@ -24,34 +24,6 @@ namespace eprosima { namespace amlip { namespace types { -size_t InterfaceDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - throw eprosima::utils::InconsistencyException( - "Subclasses of InterfaceDataType must implement get_max_cdr_serialized_size."); -} - -size_t InterfaceDataType::get_cdr_serialized_size( - const InterfaceDataType&, - size_t current_alignment) -{ - throw eprosima::utils::InconsistencyException( - "Subclasses of InterfaceDataType must implement get_cdr_serialized_size."); -} - -size_t InterfaceDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - throw eprosima::utils::InconsistencyException( - "Subclasses of InterfaceDataType must implement get_key_max_cdr_serialized_size."); -} - -bool InterfaceDataType::is_key_defined() -{ - throw eprosima::utils::InconsistencyException( - "Subclasses of InterfaceDataType must implement is_key_defined."); -} - bool InterfaceDataType::is_bounded() { throw eprosima::utils::InconsistencyException( diff --git a/amlip_cpp/src/cpp/types/TemplatesDataType.hpp b/amlip_cpp/src/cpp/types/TemplatesDataType.hpp index 9357b723..6aba859d 100644 --- a/amlip_cpp/src/cpp/types/TemplatesDataType.hpp +++ b/amlip_cpp/src/cpp/types/TemplatesDataType.hpp @@ -58,62 +58,8 @@ class MsDataType : public MsReferenceDataType MsReferenceDataType&& reference, T&& data); - - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * - * @return Serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_cdr_serialized_size( - const MsDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - * - * @warning this method must be overriden in child class. - */ - static bool is_key_defined(); + ///// + // InterfaceDataType methods /** * @brief Whether the type is bounded @@ -157,9 +103,13 @@ class MsDataType : public MsReferenceDataType void data( T new_value); + static uint32_t max_cdr_typesize_; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: - static const char* DATA_TYPE_PREFIX_NAME_; + static const char* TYPE_NAME_; T data_; }; @@ -301,62 +251,6 @@ class RpcRequestDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * - * @return Serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_cdr_serialized_size( - const RpcRequestDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - * - * @warning this method must be overriden in child class. - */ - static bool is_key_defined(); - /** * @brief Whether the type is bounded * @@ -406,6 +300,10 @@ class RpcRequestDataType : public InterfaceDataType void data( T new_value); + static uint32_t max_cdr_typesize_; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: AmlipIdDataType client_id_; @@ -414,7 +312,7 @@ class RpcRequestDataType : public InterfaceDataType AmlipIdDataType server_id_; - static const char* DATA_TYPE_PREFIX_NAME_; // "rpc_request" + static const char* TYPE_NAME_; // "rpc_request" T data_; @@ -563,62 +461,6 @@ class RpcReplyDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * - * @param cdr CDR serialization object. - * - * @warning this method must be overriden in child class. - */ - virtual void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * - * @return Serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_cdr_serialized_size( - const RpcReplyDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * - * @param current_alignment Buffer alignment. - * - * @return Maximum serialized size. - * - * @warning this method must be overriden in child class. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - * - * @warning this method must be overriden in child class. - */ - static bool is_key_defined(); - /** * @brief Whether the type is bounded * @@ -668,6 +510,10 @@ class RpcReplyDataType : public InterfaceDataType void data( T new_value); + static uint32_t max_cdr_typesize_; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: AmlipIdDataType client_id_; @@ -676,7 +522,7 @@ class RpcReplyDataType : public InterfaceDataType AmlipIdDataType server_id_; - static const char* DATA_TYPE_PREFIX_NAME_; + static const char* TYPE_NAME_; T data_; }; diff --git a/amlip_cpp/src/cpp/types/TemplatesDataTypeCdrAux.hpp b/amlip_cpp/src/cpp/types/TemplatesDataTypeCdrAux.hpp new file mode 100644 index 00000000..314fe1be --- /dev/null +++ b/amlip_cpp/src/cpp/types/TemplatesDataTypeCdrAux.hpp @@ -0,0 +1,42 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file TemplatesDataTypeCdrAux.hpp + */ + +#pragma once + +#include + +namespace eprosima { +namespace fastcdr { + +template +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsDataType& data); + +template +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::RpcRequestDataType& data); + +template +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::RpcReplyDataType& data); + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/id/AmlipIdDataType.cpp b/amlip_cpp/src/cpp/types/id/AmlipIdDataType.cpp index 1855ded7..b313728c 100644 --- a/amlip_cpp/src/cpp/types/id/AmlipIdDataType.cpp +++ b/amlip_cpp/src/cpp/types/id/AmlipIdDataType.cpp @@ -301,39 +301,6 @@ std::array AmlipIdDataType::random_id_() return rand_id; } -void AmlipIdDataType::serialize_key( - eprosima::fastcdr::Cdr&) const -{ -} - -size_t AmlipIdDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - current_alignment += ((NAME_SIZE) * 1) + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); - current_alignment += ((RAND_SIZE) * 1) + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); - return current_alignment - initial_alignment; -} - -size_t AmlipIdDataType::get_cdr_serialized_size( - const AmlipIdDataType&, - size_t current_alignment) -{ - // As the data type is plain, the max size and the size for a data is the same - return get_max_cdr_serialized_size(current_alignment); -} - -size_t AmlipIdDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - return current_alignment; -} - -bool AmlipIdDataType::is_key_defined() -{ - return false; -} - bool AmlipIdDataType::is_bounded() { return true; diff --git a/amlip_cpp/src/cpp/types/id/AmlipIdDataTypeCdrAux.hpp b/amlip_cpp/src/cpp/types/id/AmlipIdDataTypeCdrAux.hpp new file mode 100644 index 00000000..45e6014e --- /dev/null +++ b/amlip_cpp/src/cpp/types/id/AmlipIdDataTypeCdrAux.hpp @@ -0,0 +1,31 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file AmlipIdDataTypeCdrAux.hpp + */ + +#pragma once + +#include + +namespace eprosima { +namespace fastcdr { + +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::AmlipIdDataType& data); + +} // namespace fastcdr +} // namespace eprosima diff --git a/amlip_cpp/src/cpp/types/id/impl/AmlipIdDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/id/impl/AmlipIdDataTypeCdrAux.ipp index 576133e0..902efc05 100644 --- a/amlip_cpp/src/cpp/types/id/impl/AmlipIdDataTypeCdrAux.ipp +++ b/amlip_cpp/src/cpp/types/id/impl/AmlipIdDataTypeCdrAux.ipp @@ -106,5 +106,13 @@ AMLIP_CPP_DllAPI void deserialize( }); } +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::AmlipIdDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + } // namespace fastcdr } // namespace eprosima diff --git a/amlip_cpp/src/cpp/types/impl/AmlipGenericTopicDataType.ipp b/amlip_cpp/src/cpp/types/impl/AmlipGenericTopicDataType.ipp index 4fdb77f1..d14ba0e3 100644 --- a/amlip_cpp/src/cpp/types/impl/AmlipGenericTopicDataType.ipp +++ b/amlip_cpp/src/cpp/types/impl/AmlipGenericTopicDataType.ipp @@ -27,7 +27,13 @@ #include -#include +#include +#include +#include +#include +#include +#include +#include namespace eprosima { namespace amlip { @@ -41,12 +47,11 @@ template AmlipGenericTopicDataType::AmlipGenericTopicDataType() { setName(T::type_name().c_str()); - auto type_size = T::get_max_cdr_serialized_size(); - type_size += eprosima::fastcdr::Cdr::alignment(type_size, 4); /* possible submessage alignment */ - m_typeSize = static_cast(type_size) + 4; /*encapsulation*/ - m_isGetKeyDefined = T::is_key_defined(); - size_t keyLength = T::get_key_max_cdr_serialized_size() > 16 ? - T::get_key_max_cdr_serialized_size() : 16; + uint32_t type_size = T::max_cdr_typesize_; + type_size += static_cast(eprosima::fastcdr::Cdr::alignment(type_size, 4)); /* possible submessage alignment */ + m_typeSize = type_size + 4; /*encapsulation*/ + m_isGetKeyDefined = false; + uint32_t keyLength = T::max_key_cdr_typesize_ > 16 ? T::max_key_cdr_typesize_ : 16; key_buffer_ = reinterpret_cast(malloc(keyLength)); memset(key_buffer_, 0, keyLength); } @@ -167,13 +172,12 @@ bool AmlipGenericTopicDataType::getKey( // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(key_buffer_), - T::get_key_max_cdr_serialized_size()); + T::max_key_cdr_typesize_); // Object that serializes the data. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); - static_cast(ser); - static_cast(*p_type); - if (force_md5 || T::get_key_max_cdr_serialized_size() > 16) + eprosima::fastcdr::serialize_key(ser, *p_type); + if (force_md5 || T::max_key_cdr_typesize_ > 16) { md5_.init(); md5_.update(key_buffer_, static_cast(ser.get_serialized_data_length())); diff --git a/amlip_cpp/include/amlip_cpp/types/impl/GenericDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/impl/GenericDataTypeCdrAux.ipp similarity index 96% rename from amlip_cpp/include/amlip_cpp/types/impl/GenericDataTypeCdrAux.ipp rename to amlip_cpp/src/cpp/types/impl/GenericDataTypeCdrAux.ipp index adcd4439..d64533d7 100644 --- a/amlip_cpp/include/amlip_cpp/types/impl/GenericDataTypeCdrAux.ipp +++ b/amlip_cpp/src/cpp/types/impl/GenericDataTypeCdrAux.ipp @@ -123,5 +123,13 @@ AMLIP_CPP_DllAPI void deserialize( }); } +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::GenericDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + } /* namespace fastcdr */ } /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/impl/TemplatesDataType.ipp b/amlip_cpp/src/cpp/types/impl/TemplatesDataType.ipp index f67ca1aa..ef7717ca 100644 --- a/amlip_cpp/src/cpp/types/impl/TemplatesDataType.ipp +++ b/amlip_cpp/src/cpp/types/impl/TemplatesDataType.ipp @@ -24,7 +24,9 @@ namespace amlip { namespace types { template -const char* MsDataType::DATA_TYPE_PREFIX_NAME_ = "ms_data_"; +const char* MsDataType::TYPE_NAME_ = "ms_data_"; +template +uint32_t MsDataType::max_cdr_typesize_ = 400UL; template MsDataType::MsDataType() @@ -60,52 +62,6 @@ MsDataType::MsDataType( { } -template -void MsDataType::serialize_key( - eprosima::fastcdr::Cdr& cdr) const -{ -} - -template -size_t MsDataType::get_max_cdr_serialized_size( - size_t current_alignment /* = 0 */) -{ - size_t initial_alignment = current_alignment; - - current_alignment += MsReferenceDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_max_cdr_serialized_size(current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t MsDataType::get_cdr_serialized_size( - const MsDataType& data, - size_t current_alignment /* = 0 */) -{ - size_t initial_alignment = current_alignment; - - current_alignment += MsReferenceDataType::get_cdr_serialized_size(data, current_alignment); - - current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t MsDataType::get_key_max_cdr_serialized_size( - size_t current_alignment /* = 0 */) -{ - return current_alignment; -} - -template -bool MsDataType::is_key_defined() -{ - return false; -} - template bool MsDataType::is_bounded() { @@ -137,7 +93,7 @@ template std::string MsDataType::type_name() { // NOTE: there is no easy way to concatenate 2 const chars - std::string result(DATA_TYPE_PREFIX_NAME_); + std::string result(TYPE_NAME_); result.append(T::type_name()); return result; @@ -163,7 +119,9 @@ void MsDataType::data( } template -const char* RpcRequestDataType::DATA_TYPE_PREFIX_NAME_ = "rpc_request"; +const char* RpcRequestDataType::TYPE_NAME_ = "rpc_request"; +template +uint32_t RpcRequestDataType::max_cdr_typesize_ = 400UL; template RpcRequestDataType::RpcRequestDataType() @@ -330,56 +288,6 @@ void RpcRequestDataType::server_id( server_id_ = new_value; } -template -void RpcRequestDataType::serialize_key( - eprosima::fastcdr::Cdr&) const -{ -} - -template -size_t RpcRequestDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_max_cdr_serialized_size(current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t RpcRequestDataType::get_cdr_serialized_size( - const RpcRequestDataType& data, - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t RpcRequestDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - return current_alignment; -} - -template -bool RpcRequestDataType::is_key_defined() -{ - return false; -} - template bool RpcRequestDataType::is_bounded() { @@ -411,7 +319,7 @@ template std::string RpcRequestDataType::type_name() { // NOTE: there is no easy way to concatenate 2 const chars - std::string result(DATA_TYPE_PREFIX_NAME_); + std::string result(TYPE_NAME_); result.append(T::type_name()); return result; @@ -446,7 +354,9 @@ std::ostream& operator <<( } template -const char* RpcReplyDataType::DATA_TYPE_PREFIX_NAME_ = "rpc_reply"; +const char* RpcReplyDataType::TYPE_NAME_ = "rpc_reply"; +template +uint32_t RpcReplyDataType::max_cdr_typesize_ = 400UL; template RpcReplyDataType::RpcReplyDataType() @@ -612,56 +522,6 @@ void RpcReplyDataType::server_id( server_id_ = new_value; } -template -void RpcReplyDataType::serialize_key( - eprosima::fastcdr::Cdr& cdr) const -{ -} - -template -size_t RpcReplyDataType::get_max_cdr_serialized_size( - size_t current_alignment /* = 0 */) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_max_cdr_serialized_size(current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t RpcReplyDataType::get_cdr_serialized_size( - const RpcReplyDataType& data, - size_t current_alignment /* = 0 */) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - current_alignment += T::get_cdr_serialized_size(data.data(), current_alignment); - - return current_alignment - initial_alignment; -} - -template -size_t RpcReplyDataType::get_key_max_cdr_serialized_size( - size_t current_alignment /* = 0 */) -{ - return current_alignment; -} - -template -bool RpcReplyDataType::is_key_defined() -{ - return false; -} - template bool RpcReplyDataType::is_bounded() { @@ -693,7 +553,7 @@ template std::string RpcReplyDataType::type_name() { // NOTE: there is no easy way to concatenate 2 const chars - std::string result(DATA_TYPE_PREFIX_NAME_); + std::string result(TYPE_NAME_); result.append(T::type_name()); return result; diff --git a/amlip_cpp/src/cpp/types/impl/TemplatesDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/impl/TemplatesDataTypeCdrAux.ipp index a2dd9a91..3685e921 100644 --- a/amlip_cpp/src/cpp/types/impl/TemplatesDataTypeCdrAux.ipp +++ b/amlip_cpp/src/cpp/types/impl/TemplatesDataTypeCdrAux.ipp @@ -13,7 +13,7 @@ // limitations under the License. /*! - * @file TemplatesDataTypeCdrAux.cpp + * @file TemplatesDataTypeCdrAux.ipp */ #pragma once @@ -175,6 +175,15 @@ AMLIP_CPP_DllAPI void deserialize( }); } +template +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + template AMLIP_CPP_DllAPI size_t calculate_serialized_size( eprosima::fastcdr::CdrSizeCalculator& calculator, @@ -263,6 +272,15 @@ AMLIP_CPP_DllAPI void deserialize( }); } +template +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::RpcRequestDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + template AMLIP_CPP_DllAPI size_t calculate_serialized_size( eprosima::fastcdr::CdrSizeCalculator& calculator, @@ -351,5 +369,14 @@ AMLIP_CPP_DllAPI void deserialize( }); } +template +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::RpcReplyDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + } /* namespace fastcdr */ } /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/model/ModelStatisticsDataType.cpp b/amlip_cpp/src/cpp/types/model/ModelStatisticsDataType.cpp index e310e540..f6257b4c 100644 --- a/amlip_cpp/src/cpp/types/model/ModelStatisticsDataType.cpp +++ b/amlip_cpp/src/cpp/types/model/ModelStatisticsDataType.cpp @@ -37,6 +37,7 @@ namespace amlip { namespace types { const char* ModelStatisticsDataType::TYPE_NAME_ = "AMLIP-MODEL-STATISTICS"; +uint32_t ModelStatisticsDataType::max_cdr_typesize_ = 264UL; ModelStatisticsDataType::ModelStatisticsDataType() : name_("ModelStatisticsDataTypeName") @@ -332,60 +333,6 @@ void ModelStatisticsDataType::has_been_allocated( has_been_allocated_.store(take_ownership); } -void ModelStatisticsDataType::serialize_key( - eprosima::fastcdr::Cdr&) const -{ -} - -size_t ModelStatisticsDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); // - current_alignment += ((STATISTICS_NAME_SIZE) * 1) + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); // name - - current_alignment += ((DEFAULT_PREALLOCATED_SIZE_) * 1) + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); // data - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); // data_size - - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); // has_been_allocated_ - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); // server_id_ - - return current_alignment - initial_alignment; -} - -size_t ModelStatisticsDataType::get_cdr_serialized_size( - const ModelStatisticsDataType& data, - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); // - current_alignment += ((STATISTICS_NAME_SIZE) * 1) + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); // name - - if (data.data_size() > 0) - { - current_alignment += ((data.data_size()) * 1) + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); // data_ - } - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); // data_size - - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); // has_been_allocated_ - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); // server_id_ - - return current_alignment - initial_alignment; -} - -size_t ModelStatisticsDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - return current_alignment; -} - -bool ModelStatisticsDataType::is_key_defined() -{ - return false; -} - bool ModelStatisticsDataType::is_bounded() { return false; diff --git a/amlip_cpp/src/cpp/types/model/ModelStatisticsDataTypeCdrAux.hpp b/amlip_cpp/src/cpp/types/model/ModelStatisticsDataTypeCdrAux.hpp new file mode 100644 index 00000000..8f3f1471 --- /dev/null +++ b/amlip_cpp/src/cpp/types/model/ModelStatisticsDataTypeCdrAux.hpp @@ -0,0 +1,31 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file ModelStatisticsDataTypeCdrAux.hpp + */ + +#pragma once + +#include + +namespace eprosima { +namespace fastcdr { + +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::ModelStatisticsDataType& data); + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/model/impl/ModelStatisticsDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/model/impl/ModelStatisticsDataTypeCdrAux.ipp index adf5c924..ec5646a6 100644 --- a/amlip_cpp/src/cpp/types/model/impl/ModelStatisticsDataTypeCdrAux.ipp +++ b/amlip_cpp/src/cpp/types/model/impl/ModelStatisticsDataTypeCdrAux.ipp @@ -127,5 +127,13 @@ AMLIP_CPP_DllAPI void deserialize( data.has_been_allocated(true); } +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::ModelStatisticsDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + } /* namespace fastcdr */ } /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.cpp b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.cpp index 742b04e5..57a11a72 100644 --- a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.cpp +++ b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.cpp @@ -30,7 +30,7 @@ namespace eprosima { namespace amlip { namespace types { -const char* MsReferenceDataType::DATA_TYPE_NAME_ = "ms_reference"; +const char* MsReferenceDataType::TYPE_NAME_ = "ms_reference"; MsReferenceDataType::MsReferenceDataType() { @@ -141,42 +141,6 @@ void MsReferenceDataType::server_id( server_id_ = new_value; } -void MsReferenceDataType::serialize_key( - eprosima::fastcdr::Cdr&) const -{ -} - -size_t MsReferenceDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - - return current_alignment - initial_alignment; -} - -size_t MsReferenceDataType::get_cdr_serialized_size( - const MsReferenceDataType& request, - size_t current_alignment) -{ - // As the data type is plain, the max size and the size for a data is the same - return get_max_cdr_serialized_size(current_alignment); -} - -size_t MsReferenceDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - return current_alignment; -} - -bool MsReferenceDataType::is_key_defined() -{ - return false; -} - bool MsReferenceDataType::is_bounded() { return true; @@ -196,7 +160,7 @@ bool MsReferenceDataType::construct_sample( std::string MsReferenceDataType::type_name() { - return DATA_TYPE_NAME_; + return TYPE_NAME_; } MsRequestDataType MsReferenceDataType::request() const diff --git a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.hpp b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.hpp index ab20c4f7..59efb809 100644 --- a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.hpp +++ b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataType.hpp @@ -125,46 +125,6 @@ class MsReferenceDataType : public MsRequestDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * @param cdr CDR serialization object. - */ - void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * @return Serialized size. - */ - static size_t get_cdr_serialized_size( - const MsReferenceDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - */ - static bool is_key_defined(); - /** * @brief Whether the type is bounded */ @@ -197,11 +157,16 @@ class MsReferenceDataType : public MsRequestDataType //! Return the Request related with this reference MsRequestDataType request() const; + static constexpr uint32_t max_cdr_typesize_ {168UL}; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: AmlipIdDataType server_id_; - static const char* DATA_TYPE_NAME_; // "ms_reference" + static const char* TYPE_NAME_; // "ms_reference" + }; //! \c MsReferenceDataType to stream serializator diff --git a/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataTypeCdrAux.hpp b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataTypeCdrAux.hpp new file mode 100644 index 00000000..2a0534d3 --- /dev/null +++ b/amlip_cpp/src/cpp/types/multiservice/MsReferenceDataTypeCdrAux.hpp @@ -0,0 +1,31 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file MsReferenceDataTypeCdrAux.hpp + */ + +#pragma once + +#include + +namespace eprosima { +namespace fastcdr { + +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsReferenceDataType& data); + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.cpp b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.cpp index 1f1121c9..3bcbd2b3 100644 --- a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.cpp +++ b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.cpp @@ -30,7 +30,7 @@ namespace eprosima { namespace amlip { namespace types { -const char* MsRequestDataType::DATA_TYPE_NAME_ = "ms_request"; +const char* MsRequestDataType::TYPE_NAME_ = "ms_request"; MsRequestDataType::MsRequestDataType() { @@ -141,41 +141,6 @@ void MsRequestDataType::task_id( task_id_ = new_value; } -void MsRequestDataType::serialize_key( - eprosima::fastcdr::Cdr&) const -{ -} - -size_t MsRequestDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - - return current_alignment - initial_alignment; -} - -size_t MsRequestDataType::get_cdr_serialized_size( - const MsRequestDataType&, - size_t current_alignment) -{ - // As the data type is plain, the max size and the size for a data is the same - return get_max_cdr_serialized_size(current_alignment); -} - -size_t MsRequestDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - return current_alignment; -} - -bool MsRequestDataType::is_key_defined() -{ - return false; -} - bool MsRequestDataType::is_bounded() { return true; @@ -195,7 +160,7 @@ bool MsRequestDataType::construct_sample( std::string MsRequestDataType::type_name() { - return DATA_TYPE_NAME_; + return TYPE_NAME_; } std::ostream& operator <<( diff --git a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.hpp b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.hpp index 58f27c13..7b136cd9 100644 --- a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.hpp +++ b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataType.hpp @@ -143,46 +143,6 @@ class MsRequestDataType : public InterfaceDataType ///// // InterfaceDataType methods - /*! - * @brief This function serializes the key members of an object using CDR serialization. - * @param cdr CDR serialization object. - */ - void serialize_key( - eprosima::fastcdr::Cdr& cdr) const override; - - /*! - * @brief This function returns the maximum serialized size of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - static size_t get_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function returns the serialized size of a data depending on the buffer alignment. - * @param data Data which is calculated its serialized size. - * @param current_alignment Buffer alignment. - * @return Serialized size. - */ - static size_t get_cdr_serialized_size( - const MsRequestDataType& data, - size_t current_alignment = 0); - - /*! - * @brief This function returns the maximum serialized size of the Key of an object - * depending on the buffer alignment. - * @param current_alignment Buffer alignment. - * @return Maximum serialized size. - */ - static size_t get_key_max_cdr_serialized_size( - size_t current_alignment = 0); - - /*! - * @brief This function tells you if the Key has been defined for this type - */ - static bool is_key_defined(); - /** * @brief Whether the type is bounded */ @@ -212,13 +172,17 @@ class MsRequestDataType : public InterfaceDataType */ static std::string type_name(); + static constexpr uint32_t max_cdr_typesize_ {136UL}; + + static constexpr uint32_t max_key_cdr_typesize_ {0UL}; + protected: AmlipIdDataType client_id_; TaskId task_id_; - static const char* DATA_TYPE_NAME_; // "ms_request" + static const char* TYPE_NAME_; // "ms_request" }; diff --git a/amlip_cpp/src/cpp/types/multiservice/MsRequestDataTypeCdrAux.hpp b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataTypeCdrAux.hpp new file mode 100644 index 00000000..a21f5e99 --- /dev/null +++ b/amlip_cpp/src/cpp/types/multiservice/MsRequestDataTypeCdrAux.hpp @@ -0,0 +1,31 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file MsRequestDataTypeCdrAux.hpp + */ + +#pragma once + +#include + +namespace eprosima { +namespace fastcdr { + +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsRequestDataType& data); + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/multiservice/impl/MsReferenceDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/multiservice/impl/MsReferenceDataTypeCdrAux.ipp index fe39de74..98bc2d00 100644 --- a/amlip_cpp/src/cpp/types/multiservice/impl/MsReferenceDataTypeCdrAux.ipp +++ b/amlip_cpp/src/cpp/types/multiservice/impl/MsReferenceDataTypeCdrAux.ipp @@ -111,5 +111,13 @@ AMLIP_CPP_DllAPI void deserialize( }); } +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsReferenceDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + } /* namespace fastcdr */ } /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/multiservice/impl/MsRequestDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/multiservice/impl/MsRequestDataTypeCdrAux.ipp index d6179a57..f4dafd54 100644 --- a/amlip_cpp/src/cpp/types/multiservice/impl/MsRequestDataTypeCdrAux.ipp +++ b/amlip_cpp/src/cpp/types/multiservice/impl/MsRequestDataTypeCdrAux.ipp @@ -102,5 +102,13 @@ AMLIP_CPP_DllAPI void deserialize( }); } +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::MsRequestDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + } /* namespace fastcdr */ } /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/status/StatusDataType.cpp b/amlip_cpp/src/cpp/types/status/StatusDataType.cpp index 3e078a54..ddcce55d 100644 --- a/amlip_cpp/src/cpp/types/status/StatusDataType.cpp +++ b/amlip_cpp/src/cpp/types/status/StatusDataType.cpp @@ -26,7 +26,7 @@ namespace eprosima { namespace amlip { namespace types { -const char* StatusDataType::DATA_TYPE_NAME_ = "status"; +const char* StatusDataType::TYPE_NAME_ = "status"; StatusDataType::StatusDataType( const AmlipIdDataType& id, @@ -98,41 +98,6 @@ std::string StatusDataType::to_string() const noexcept return utils::generic_to_string(*this); } -void StatusDataType::serialize_key( - eprosima::fastcdr::Cdr&) const -{ -} - -size_t StatusDataType::get_max_cdr_serialized_size( - size_t current_alignment) -{ - size_t initial_alignment = current_alignment; - - current_alignment += AmlipIdDataType::get_max_cdr_serialized_size(current_alignment); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); - - return current_alignment - initial_alignment; -} - -size_t StatusDataType::get_cdr_serialized_size( - const StatusDataType&, - size_t current_alignment) -{ - return get_max_cdr_serialized_size(current_alignment); -} - -size_t StatusDataType::get_key_max_cdr_serialized_size( - size_t current_alignment) -{ - return current_alignment; -} - -bool StatusDataType::is_key_defined() -{ - return false; -} - bool StatusDataType::is_bounded() { return true; @@ -151,7 +116,7 @@ bool StatusDataType::construct_sample( std::string StatusDataType::type_name() { - return DATA_TYPE_NAME_; + return TYPE_NAME_; } std::ostream& operator <<( diff --git a/amlip_cpp/src/cpp/types/status/StatusDataTypeCdrAux.hpp b/amlip_cpp/src/cpp/types/status/StatusDataTypeCdrAux.hpp new file mode 100644 index 00000000..260ec720 --- /dev/null +++ b/amlip_cpp/src/cpp/types/status/StatusDataTypeCdrAux.hpp @@ -0,0 +1,31 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/*! + * @file StatusDataTypeCdrAux.hpp + */ + +#pragma once + +#include + +namespace eprosima { +namespace fastcdr { + +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::StatusDataType& data); + +} /* namespace fastcdr */ +} /* namespace eprosima */ diff --git a/amlip_cpp/src/cpp/types/status/impl/StatusDataTypeCdrAux.ipp b/amlip_cpp/src/cpp/types/status/impl/StatusDataTypeCdrAux.ipp index c9ec809d..c85f0615 100644 --- a/amlip_cpp/src/cpp/types/status/impl/StatusDataTypeCdrAux.ipp +++ b/amlip_cpp/src/cpp/types/status/impl/StatusDataTypeCdrAux.ipp @@ -110,5 +110,13 @@ AMLIP_CPP_DllAPI void deserialize( }); } +void serialize_key( + eprosima::fastcdr::Cdr& scdr, + const amlip::types::StatusDataType& data) +{ + static_cast(scdr); + static_cast(data); +} + } /* namespace fastcdr */ } /* namespace eprosima */ diff --git a/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp b/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp index abbc0820..3346a06f 100644 --- a/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp +++ b/amlip_cpp/test/blackbox/communication/collaborative_learning/modelManagerTest.cpp @@ -145,6 +145,7 @@ TEST(modelManagerTest, ping_pong) // Create statistics data std::string data_str = "hello world"; + logUser(AMLIPCPP_MANUAL_TEST, "Publishing statistics..."); model_sender_node.publish_statistics("v1", data_str); // Create waiter @@ -182,9 +183,20 @@ TEST(modelManagerTest, long_string_statistics) // Activate log eprosima::utils::Log::SetVerbosity(eprosima::utils::Log::Kind::Info); { - // Managers always send same model in this test + std::string data_str; + std::ifstream file("../../../resources/el_quijote.txt"); + if (file.is_open()) + { + data_str = std::string((std::istreambuf_iterator(file)), (std::istreambuf_iterator())); + } + else + { + throw std::runtime_error("Failed to open file: ../../../resources/el_quijote.txt"); + } + eprosima::amlip::types::ModelStatisticsDataType::max_cdr_typesize_ += data_str.length(); + // Create ModelManagerReceiver Node eprosima::amlip::types::AmlipIdDataType id_receiver("ModelManagerReceiver"); // NOTE: this data must be created before nodes or nodes must stop before this is destroyed @@ -200,18 +212,6 @@ TEST(modelManagerTest, long_string_statistics) logUser(AMLIPCPP_MANUAL_TEST, "Node sender created: " << model_sender_node << "."); // Create statistics data - std::string data_str; - - std::ifstream file("../../../resources/el_quijote.txt"); - if (file.is_open()) - { - data_str = std::string((std::istreambuf_iterator(file)), (std::istreambuf_iterator())); - } - else - { - throw std::runtime_error("Failed to open file: ../../../resources/el_quijote.txt"); - } - logUser(AMLIPCPP_MANUAL_TEST, "Publishing statistics..."); model_sender_node.publish_statistics("v2", data_str, data_str.length()); @@ -251,9 +251,20 @@ TEST(modelManagerTest, long_vector_statistics) // Activate log eprosima::utils::Log::SetVerbosity(eprosima::utils::Log::Kind::Info); { - // Managers always send same model in this test + std::string data_str; + std::ifstream file("../../../resources/el_quijote.txt"); + if (file.is_open()) + { + data_str = std::string((std::istreambuf_iterator(file)), (std::istreambuf_iterator())); + } + else + { + throw std::runtime_error("Failed to open file: ../../../resources/el_quijote.txt"); + } + eprosima::amlip::types::ModelStatisticsDataType::max_cdr_typesize_ += data_str.length(); + // Create ModelManagerReceiver Node eprosima::amlip::types::AmlipIdDataType id_receiver("ModelManagerReceiver"); // NOTE: this data must be created before nodes or nodes must stop before this is destroyed @@ -269,25 +280,13 @@ TEST(modelManagerTest, long_vector_statistics) logUser(AMLIPCPP_MANUAL_TEST, "Node sender created: " << model_sender_node << "."); // Create statistics data - std::string data_str; - - std::ifstream file("../../../resources/el_quijote.txt"); - if (file.is_open()) - { - data_str = std::string((std::istreambuf_iterator(file)), (std::istreambuf_iterator())); - } - else - { - throw std::runtime_error("Failed to open file: ../../../resources/el_quijote.txt"); - } - std::vector data_vector; for (char c : data_str) { data_vector.push_back(static_cast(c)); } - + logUser(AMLIPCPP_MANUAL_TEST, "Publishing statistics..."); model_sender_node.publish_statistics("v2", data_vector); // Create waiter From 00ffdeee682977e937b07698b7903a4963cfbbe7 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Wed, 21 Feb 2024 12:24:19 +0100 Subject: [PATCH 13/15] Add amlip_swig_js package Signed-off-by: Irene Bandera --- amlip_swig_js/CMakeLists.txt | 96 ++++++++ amlip_swig_js/README.md | 11 + amlip_swig_js/package.xml | 30 +++ amlip_swig_js/project_settings.cmake | 35 +++ ...(UseSWIG_TARGET_NAME_PREFERENCE STAN.cmake | 225 ++++++++++++++++++ amlip_swig_js/src/swig/CMakeLists.txt | 76 ++++++ amlip_swig_js/src/swig/amlip_swig_js.i | 52 ++++ .../src/swig/amlip_swig_js/node/AgentNode.i | 29 +++ .../src/swig/amlip_swig_js/node/MainNode.i | 27 +++ .../src/swig/amlip_swig_js/node/ParentNode.i | 27 +++ .../amlip_swig_js/types/GenericDataType.i | 42 ++++ .../amlip_swig_js/types/InterfaceDataType.i | 23 ++ .../amlip_swig_js/types/id/AmlipIdDataType.i | 50 ++++ .../src/swig/amlip_swig_js/types/id/TaskId.i | 27 +++ .../amlip_swig_js/types/job/JobDataType.i | 37 +++ .../types/job/JobSolutionDataType.i | 37 +++ .../amlip_swig_js/types/status/NodeKind.i | 31 +++ .../amlip_swig_js/types/status/StateKind.i | 31 +++ .../types/status/StatusDataType.i | 48 ++++ amlip_swig_js/test/CMakeLists.txt | 16 ++ amlip_swig_js/test/api/CMakeLists.txt | 23 ++ amlip_swig_js/test/api/import_test.js | 35 +++ 22 files changed, 1008 insertions(+) create mode 100644 amlip_swig_js/CMakeLists.txt create mode 100644 amlip_swig_js/README.md create mode 100644 amlip_swig_js/package.xml create mode 100644 amlip_swig_js/project_settings.cmake create mode 100644 amlip_swig_js/set (UseSWIG_TARGET_NAME_PREFERENCE STAN.cmake create mode 100644 amlip_swig_js/src/swig/CMakeLists.txt create mode 100644 amlip_swig_js/src/swig/amlip_swig_js.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/AgentNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/MainNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/ParentNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/GenericDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/InterfaceDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/id/AmlipIdDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/id/TaskId.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/job/JobDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/job/JobSolutionDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/status/NodeKind.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/status/StateKind.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/status/StatusDataType.i create mode 100644 amlip_swig_js/test/CMakeLists.txt create mode 100644 amlip_swig_js/test/api/CMakeLists.txt create mode 100644 amlip_swig_js/test/api/import_test.js diff --git a/amlip_swig_js/CMakeLists.txt b/amlip_swig_js/CMakeLists.txt new file mode 100644 index 00000000..66f40eb3 --- /dev/null +++ b/amlip_swig_js/CMakeLists.txt @@ -0,0 +1,96 @@ +# Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +cmake_minimum_required(VERSION 3.15) + +# SWIG: use standard target name. +if(POLICY CMP0078) + cmake_policy(SET CMP0078 NEW) +endif() + +# SWIG: use SWIG_MODULE_NAME property. +if(POLICY CMP0086) + cmake_policy(SET CMP0086 NEW) +endif() + +# Done this to set machine architecture and be able to call cmake_utils +enable_language(CXX) + +############################################################################### +# Find package cmake_utils +############################################################################### +# Package cmake_utils is required to get every cmake macro needed +find_package(cmake_utils REQUIRED) + +############################################################################### +# Project +############################################################################### +# Configure project by info set in project_settings.cmake +# - Load project_settings variables +# - Read version +# - Set installation paths +configure_project() + +# Call explictly project +project( + ${MODULE_NAME} + VERSION + ${MODULE_VERSION} + DESCRIPTION + ${MODULE_DESCRIPTION} +) + +############################################################################### +# C++ Project +############################################################################### +# Configure CPP project for dependencies and required flags: +# - Set CMake Build Type +# - Set C++ version +# - Set shared libraries by default +# - Find external packages and thirdparties +# - Activate Code coverage if flag CODE_COVERAGE +# - Configure log depending on LOG_INFO flag and CMake type +configure_project_cpp() + +# Compile SWIG library +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) + +set(CMAKE_SWIG_FLAGS "") + +# Set the path to the language-specific module file (e.g., for JavaScript) +# find_package(Javascript REQUIRED) +# list(APPEND CMAKE_MODULE_PATH +# ${CMAKE_CURRENT_SOURCE_DIR}/node_modules/node-cmake +# ) +# find_package(NodeJS REQUIRED) +# include_directories(/usr/include/nodejs) +include_directories(/home/irenebm/.nvm/versions/node/v11.15.0/include/node/) +# Set the path to the language-specific module file (e.g., for JavaScript) + +add_subdirectory(src/swig) + +############################################################################### +# Test +############################################################################### +# Compile tests if CMake options requires it +compile_test_library( + "${PROJECT_SOURCE_DIR}/test" # Test directory +) + +############################################################################### +# Packaging +############################################################################### +# Install package +eprosima_packaging() diff --git a/amlip_swig_js/README.md b/amlip_swig_js/README.md new file mode 100644 index 00000000..7ec80f9e --- /dev/null +++ b/amlip_swig_js/README.md @@ -0,0 +1,11 @@ +# eProsima AML-IP SWIG JAVASCRIPT module + +`amlip_swig` subpackage. + +> :warning: **TODO** + +## Windows support + +> :warning: **At this stage, this project is not supported for Windows.** + +However, it could be compiled using SWIG and used for some Windows platforms under user responsibility. diff --git a/amlip_swig_js/package.xml b/amlip_swig_js/package.xml new file mode 100644 index 00000000..409d90bf --- /dev/null +++ b/amlip_swig_js/package.xml @@ -0,0 +1,30 @@ + + + + amlip_swig_js + 0.1.0 + + eprosima AML IP SWIG + + Raul Sánchez-Mateos + Irene Bandera + Juan López + Apache 2.0 + + https://www.eprosima.com/ + https://github.com/eProsima/AML-IP/issues + https://github.com/eProsima/AML-IP + + cmake + + + cmake_utils + cpp_utils + amlip_cpp + ddspipe_participants + + + cmake + + + diff --git a/amlip_swig_js/project_settings.cmake b/amlip_swig_js/project_settings.cmake new file mode 100644 index 00000000..9f44a944 --- /dev/null +++ b/amlip_swig_js/project_settings.cmake @@ -0,0 +1,35 @@ +# Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +############################################################################### +# Set settings for project amlip_swig for SWIG code +############################################################################### + +set(MODULE_NAME + amlip_swig_js) + +set(MODULE_SUMMARY + "SWIG library to create python bindings from amlip_cpp.") + +set(MODULE_FIND_PACKAGES + amlip_cpp + cpp_utils + ddspipe_core + ddspipe_participants + ddsrouter_core + ) + +set(MODULE_DEPENDENCIES + ${MODULE_FIND_PACKAGES} + ) diff --git a/amlip_swig_js/set (UseSWIG_TARGET_NAME_PREFERENCE STAN.cmake b/amlip_swig_js/set (UseSWIG_TARGET_NAME_PREFERENCE STAN.cmake new file mode 100644 index 00000000..5f1fb391 --- /dev/null +++ b/amlip_swig_js/set (UseSWIG_TARGET_NAME_PREFERENCE STAN.cmake @@ -0,0 +1,225 @@ +set (UseSWIG_TARGET_NAME_PREFERENCE STANDARD) +set(SWIG_JAVASCRIPT_EXTRA_FILE_EXTENSIONS ".js") + +cmake_policy(GET CMP0078 target_name_policy) +if (target_name_policy STREQUAL "NEW") + set (UseSWIG_TARGET_NAME_PREFERENCE STANDARD) +else() + if (NOT target_name_policy) + cmake_policy(GET_WARNING CMP0078 _cmp0078_warning) + message(AUTHOR_WARNING "${_cmp0078_warning}\n") + endif() + if (NOT DEFINED UseSWIG_TARGET_NAME_PREFERENCE) + set (UseSWIG_TARGET_NAME_PREFERENCE LEGACY) + elseif (NOT UseSWIG_TARGET_NAME_PREFERENCE MATCHES "^(LEGACY|STANDARD)$") + message (FATAL_ERROR "UseSWIG_TARGET_NAME_PREFERENCE: ${UseSWIG_TARGET_NAME_PREFERENCE}: invalid value. 'LEGACY' or 'STANDARD' is expected.") + endif() +endif() + +if (NOT DEFINED UseSWIG_MODULE_VERSION) + set (UseSWIG_MODULE_VERSION 1) +elseif (NOT UseSWIG_MODULE_VERSION MATCHES "^(1|2)$") + message (FATAL_ERROR "UseSWIG_MODULE_VERSION: ${UseSWIG_MODULE_VERSION}: invalid value. 1 or 2 is expected.") +endif() + +# set (SWIG_MODULE_${PROJECT_NAME}_NOPROXY FALSE) +swig_module_initialize(${PROJECT_NAME} javascript) +string(TOUPPER "javascript" SWIG_MODULE_${PROJECT_NAME}_LANGUAGE) +string(TOLOWER "javascript" SWIG_MODULE_${PROJECT_NAME}_SWIG_LANGUAGE_FLAG) + +# if (NOT DEFINED SWIG_MODULE_${PROJECT_NAME}_NOPROXY) +# set (SWIG_MODULE_${PROJECT_NAME}_NOPROXY FALSE) +# endif() +# if ("-noproxy" IN_LIST CMAKE_SWIG_FLAGS) +# set (SWIG_MODULE_${PROJECT_NAME}_NOPROXY TRUE) +# endif () +# set (SWIG_MODULE_${PROJECT_NAME}_NOPROXY FALSE) +# if (SWIG_MODULE_${PROJECT_NAME}_NOPROXY AND +# NOT ("-noproxy" IN_LIST CMAKE_SWIG_FLAGS OR "-noproxy" IN_LIST SWIG_MODULE_${PROJECT_NAME}_EXTRA_FLAGS)) +# list (APPEND SWIG_MODULE_${PROJECT_NAME}_EXTRA_FLAGS "-noproxy") +# endif() +if(SWIG_MODULE_${PROJECT_NAME}_LANGUAGE STREQUAL "UNKNOWN") + message(FATAL_ERROR "SWIG Error: Language javascript not found") +elseif(SWIG_MODULE_${PROJECT_NAME}_LANGUAGE STREQUAL "PERL" AND + NOT "-shadow" IN_LIST SWIG_MODULE_${PROJECT_NAME}_EXTRA_FLAGS) + list(APPEND SWIG_MODULE_${PROJECT_NAME}_EXTRA_FLAGS "-shadow") +endif() + +# if (TARGET ${PROJECT_NAME}) +# # a target with same name is already defined. +# # call NOW add_library command to raise the most useful error message +# add_library(${PROJECT_NAME}) +# return() +# endif() + +# compute real target name. +set(target_name "${PROJECT_NAME}") + +set (workingdir "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${target_name}.dir") +# set special variable to pass extra information to command SWIG_ADD_SOURCE_TO_MODULE +# which cannot be changed due to legacy compatibility +set (SWIG_WORKING_DIR "${workingdir}") +set (SWIG_TARGET_NAME "${target_name}") + +if (CMAKE_SWIG_OUTDIR) + set (outputdir "${CMAKE_SWIG_OUTDIR}") +else() + if (UseSWIG_MODULE_VERSION VERSION_GREATER 1) + set (outputdir "${workingdir}/javascript.files") + else() + set (outputdir "${CMAKE_CURRENT_BINARY_DIR}") + endif() +endif() + +if (SWIG_OUTFILE_DIR) + set (outfiledir "${SWIG_OUTFILE_DIR}") +else() + if (CMAKE_SWIG_OUTDIR) + set (outfiledir "${outputdir}") + else() + set (outfiledir "${workingdir}") + endif() +endif() + +# set again, locally, predefined variables to ensure compatibility +# with command SWIG_ADD_SOURCE_TO_MODULE +set(CMAKE_SWIG_OUTDIR "${outputdir}") +set(SWIG_OUTFILE_DIR "${outfiledir}") + +# See if the user has specified source extensions for swig files? +if (NOT DEFINED SWIG_SOURCE_FILE_EXTENSIONS) + # Assume the default (*.i) file extension for Swig source files + set(SWIG_SOURCE_FILE_EXTENSIONS ".i") +endif() + +if (CMAKE_GENERATOR MATCHES "Make|Ninja|Xcode|Visual Studio (1[1-9]|[2-9][0-9])") + # For Makefiles, Ninja, Xcode and Visual Studio generators, + # use SWIG generated dependencies if requested + if (NOT DEFINED SWIG_USE_SWIG_DEPENDENCIES) + set (SWIG_USE_SWIG_DEPENDENCIES OFF) + endif() +else() + set (SWIG_USE_SWIG_DEPENDENCIES OFF) +endif() + +# Generate a regex out of file extensions. +string(REGEX REPLACE "([$^.*+?|()-])" "\\\\\\1" swig_source_ext_regex "${SWIG_SOURCE_FILE_EXTENSIONS}") +list (JOIN swig_source_ext_regex "|" swig_source_ext_regex) +string (PREPEND swig_source_ext_regex "(") +string (APPEND swig_source_ext_regex ")$") + +set(swig_dot_i_sources ${PROJECT_NAME}.i) +list(FILTER swig_dot_i_sources INCLUDE REGEX ${swig_source_ext_regex}) +if (NOT swig_dot_i_sources) + message(FATAL_ERROR "SWIG_ADD_LIBRARY: no SWIG interface files specified") +endif() +set(swig_other_sources ${PROJECT_NAME}.i) +list(REMOVE_ITEM swig_other_sources ${swig_dot_i_sources}) + +set(swig_generated_sources) +set(swig_generated_timestamps) +set(swig_generated_outdirs "${outputdir}") +list(LENGTH swig_dot_i_sources swig_sources_count) +if (swig_sources_count GREATER "1") + # option -interface cannot be used + set(SWIG_USE_INTERFACE FALSE) +else() + set(SWIG_USE_INTERFACE TRUE) +endif() +foreach(swig_it IN LISTS swig_dot_i_sources) + SWIG_ADD_SOURCE_TO_MODULE(${PROJECT_NAME} swig_generated_source "${swig_it}") + list (APPEND swig_generated_sources "${swig_generated_source}") + if(swig_timestamp) + list (APPEND swig_generated_timestamps "${swig_timestamp}") + endif() + get_source_file_property(swig_source_file_outdir "${swig_it}" OUTPUT_DIR) + if (swig_source_file_outdir) + list (APPEND swig_generated_outdirs "${swig_source_file_outdir}") + endif() +endforeach() +list(REMOVE_DUPLICATES swig_generated_outdirs) +set_property (DIRECTORY APPEND PROPERTY + ADDITIONAL_CLEAN_FILES ${swig_generated_sources} ${swig_generated_timestamps}) +if (UseSWIG_MODULE_VERSION VERSION_GREATER 1) + set_property (DIRECTORY APPEND PROPERTY ADDITIONAL_CLEAN_FILES ${swig_generated_outdirs}) +endif() + +add_library(${target_name} + SHARED + ${swig_generated_sources} + ${swig_other_sources}) +if(swig_generated_timestamps) + # see IMPLICIT_DEPENDS above + add_custom_target(${PROJECT_NAME}_swig_compilation DEPENDS ${swig_generated_timestamps}) + add_dependencies(${target_name} ${PROJECT_NAME}_swig_compilation) +endif() + +# assume empty prefix because we expect the module to be dynamically loaded +set_target_properties (${target_name} PROPERTIES PREFIX "") +set_target_properties (${target_name} PROPERTIES SUFFIX ".js") + +# target property SWIG_SUPPORT_FILES_DIRECTORY specify output directories of support files +set_property (TARGET ${target_name} PROPERTY SWIG_SUPPORT_FILES_DIRECTORY ${swig_generated_outdirs}) +# target property SWIG_SUPPORT_FILES lists principal proxy support files +if (NOT SWIG_MODULE_${PROJECT_NAME}_NOPROXY) + string(TOUPPER "javascript" swig_uppercase_language) + set(swig_all_support_files) + foreach (swig_it IN LISTS SWIG_${swig_uppercase_language}_EXTRA_FILE_EXTENSIONS) + set (swig_support_files ${swig_generated_sources}) + list (FILTER swig_support_files INCLUDE REGEX ".*${swig_it}$") + list(APPEND swig_all_support_files ${swig_support_files}) + endforeach() + if (swig_all_support_files) + list(REMOVE_DUPLICATES swig_all_support_files) + endif() + set_property (TARGET ${target_name} PROPERTY SWIG_SUPPORT_FILES ${swig_all_support_files}) +endif() + +# to ensure legacy behavior, export some variables +set (SWIG_MODULE_${PROJECT_NAME}_LANGUAGE "${SWIG_MODULE_${PROJECT_NAME}_LANGUAGE}" PARENT_SCOPE) +set (SWIG_MODULE_${PROJECT_NAME}_SWIG_LANGUAGE_FLAG "${SWIG_MODULE_${PROJECT_NAME}_SWIG_LANGUAGE_FLAG}" PARENT_SCOPE) +set (SWIG_MODULE_${PROJECT_NAME}_REAL_NAME "${target_name}" PARENT_SCOPE) +set (SWIG_MODULE_${PROJECT_NAME}_NOPROXY "${SWIG_MODULE_${PROJECT_NAME}_NOPROXY}" PARENT_SCOPE) +set (SWIG_MODULE_${PROJECT_NAME}_EXTRA_FLAGS "${SWIG_MODULE_${PROJECT_NAME}_EXTRA_FLAGS}" PARENT_SCOPE) +# the last one is a bit crazy but it is documented, so... +# NOTA: works as expected if only ONE input file is specified +set (swig_generated_file_fullname "${swig_generated_file_fullname}" PARENT_SCOPE) + +SET (JAVASCRIPT_MODULE_PATH + ${LIB_INSTALL_DIR}/node_modules/${PROJECT_NAME} + ) + +# target_include_directories(${PROJECT_NAME} PRIVATE) +target_link_libraries(${PROJECT_NAME} amlip_cpp) + +# Install +install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}-targets + DESTINATION ${JAVASCRIPT_MODULE_PATH} + ) +get_property(support_files TARGET ${PROJECT_NAME} PROPERTY SWIG_SUPPORT_FILES) +install(FILES ${support_files} DESTINATION ${JAVASCRIPT_MODULE_PATH}) + +export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-targets.cmake) + +install(EXPORT ${PROJECT_NAME}-targets + DESTINATION ${LIB_INSTALL_DIR}/cmake/${PROJECT_NAME}/ + ) + +# Create CMake config file. +include(CMakePackageConfigHelpers) + +configure_package_config_file( + ${cmake_utils_CONFIG_TEMPLATES_PATH}/library-Config.cmake.in + ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-config.cmake + INSTALL_DESTINATION ${LIB_INSTALL_DIR}/cmake/${PROJECT_NAME} + PATH_VARS LIB_INSTALL_DIR + ) +write_basic_package_version_file(${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-config-version.cmake + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion + ) +install(FILES ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-config.cmake + ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-config-version.cmake + DESTINATION ${LIB_INSTALL_DIR}/cmake/${PROJECT_NAME} + ) diff --git a/amlip_swig_js/src/swig/CMakeLists.txt b/amlip_swig_js/src/swig/CMakeLists.txt new file mode 100644 index 00000000..ccbb2c63 --- /dev/null +++ b/amlip_swig_js/src/swig/CMakeLists.txt @@ -0,0 +1,76 @@ +# Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +############################################################################### +# Compile JavaScript wrapper with SWIG +############################################################################### + +message(STATUS "Configuring AMLIP_SWIG wrapper for Javascript...") + +set_source_files_properties( + ${PROJECT_NAME}.i + PROPERTIES CPLUSPLUS ON + USE_TARGET_INCLUDE_DIRECTORIES TRUE + SWIG_FLAGS -node + ) + +swig_add_library(${PROJECT_NAME} + TYPE SHARED + LANGUAGE javascript + SOURCES ${PROJECT_NAME}.i + ) + +if(UNIX AND CMAKE_SIZEOF_VOID_P EQUAL 8) + set_property(TARGET ${PROJECT_NAME} PROPERTY SWIG_COMPILE_DEFINITIONS SWIGWORDSIZE64) +endif() + +target_link_libraries(${PROJECT_NAME} + amlip_cpp + ) + +SET (JAVASCRIPT_MODULE_PATH + ${LIB_INSTALL_DIR}/node_modules/${PROJECT_NAME} +) + +# Install +install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}-targets + DESTINATION ${JAVASCRIPT_MODULE_PATH} + ) +get_property(support_files TARGET ${PROJECT_NAME} PROPERTY SWIG_SUPPORT_FILES) +install(FILES ${support_files} DESTINATION ${JAVASCRIPT_MODULE_PATH}) + +export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-targets.cmake) + +install(EXPORT ${PROJECT_NAME}-targets + DESTINATION ${LIB_INSTALL_DIR}/cmake/${PROJECT_NAME}/ + ) + +# Create CMake config file. +include(CMakePackageConfigHelpers) + +configure_package_config_file( + ${cmake_utils_CONFIG_TEMPLATES_PATH}/library-Config.cmake.in + ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-config.cmake + INSTALL_DESTINATION ${LIB_INSTALL_DIR}/cmake/${PROJECT_NAME} + PATH_VARS LIB_INSTALL_DIR + ) +write_basic_package_version_file(${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-config-version.cmake + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion + ) +install(FILES ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-config.cmake + ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-config-version.cmake + DESTINATION ${LIB_INSTALL_DIR}/cmake/${PROJECT_NAME} + ) diff --git a/amlip_swig_js/src/swig/amlip_swig_js.i b/amlip_swig_js/src/swig/amlip_swig_js.i new file mode 100644 index 00000000..9e548ba8 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js.i @@ -0,0 +1,52 @@ +// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +%module(directors="1", threads="1") amlip_swig_js + +// Macro delcarations +// Any macro used on the header files will give an error if it is not redefined here +#define AMLIP_CPP_DllAPI + +// SWIG helper modules +// %include "cpointer.i" +%include "stdint.i" +// %include "std_array.i" +// %include "std_list.i" +// %include "std_set.i" +// %include "std_string.i" +// %include "std_shared_ptr.i" +%include "std_vector.i" + +// Definition of internal types +typedef short int16_t; +typedef int int32_t; +typedef long int64_t; +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long uint64_t; + +// IMPORTANT: the order of these includes is relevant, and must keep same order of cpp declarations. +// types +%include "amlip_swig_js/types/InterfaceDataType.i" +%include "amlip_swig_js/types/GenericDataType.i" +// %include "amlip_swig_js/types/id/AmlipIdDataType.i" +// %include "amlip_swig_js/types/id/TaskId.i" +// %include "amlip_swig_js/types/status/NodeKind.i" +// %include "amlip_swig_js/types/status/StateKind.i" +// %include "amlip_swig_js/types/status/StatusDataType.i" + +// // node +// %include "amlip_swig_js/node/ParentNode.i" +// %include "amlip_swig_js/node/MainNode.i" diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/AgentNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/AgentNode.i new file mode 100644 index 00000000..b23110af --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/AgentNode.i @@ -0,0 +1,29 @@ +// Copyright 2023 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class AgentNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::agent::AgentNode::default_router_configuration(); + +%{ +#include +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/MainNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/MainNode.i new file mode 100644 index 00000000..435a3916 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/MainNode.i @@ -0,0 +1,27 @@ +// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class MainNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%{ +#include +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/ParentNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/ParentNode.i new file mode 100644 index 00000000..2ded4283 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/ParentNode.i @@ -0,0 +1,27 @@ +// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class ParentNode +//////////////////////////////////////////////////////// + +// Import needed classes +%include "amlip_swig_js/types/status/StatusDataType.i" + +%{ +#include +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/GenericDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/GenericDataType.i new file mode 100644 index 00000000..2139e121 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/GenericDataType.i @@ -0,0 +1,42 @@ +// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class GenericDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/InterfaceDataType.hpp"; + +namespace std { + %template(bytes) vector; +} + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +// Ignore overloaded methods that have no application on Python +// Otherwise they will issue a warning +%ignore eprosima::amlip::types::GenericDataType::GenericDataType(GenericDataType&&); +%ignore eprosima::amlip::types::operator <<(std::ostream &,const GenericDataType&); + +%{ +#include +%} + +%include + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/InterfaceDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/InterfaceDataType.i new file mode 100644 index 00000000..87630778 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/InterfaceDataType.i @@ -0,0 +1,23 @@ +// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class InterfaceDataType +//////////////////////////////////////////////////////// + +%{ +#include +%} + +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/id/AmlipIdDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/id/AmlipIdDataType.i new file mode 100644 index 00000000..a99531ac --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/id/AmlipIdDataType.i @@ -0,0 +1,50 @@ +// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class AmlipIdDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/InterfaceDataType.hpp"; + +// namespace std { +// %template(rand_id) array; +// } + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +// Ignore overloaded methods that have no application on Python +// Otherwise they will issue a warning +%ignore eprosima::amlip::types::AmlipIdDataType::AmlipIdDataType(AmlipIdDataType&&); +%ignore eprosima::amlip::types::AmlipIdDataType::AmlipIdDataType(std::array< uint8_t,28> &&,std::array< uint8_t,4 > &&); +%ignore eprosima::amlip::types::operator <<(std::ostream &,const AmlipIdDataType&); + +// Declare the to string method +%extend eprosima::amlip::types::AmlipIdDataType { + std::string __str__() const + { + return $self->to_string(); + } +} + +%{ +#include +%} + +// Include the class interfaces +%include +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/id/TaskId.i b/amlip_swig_js/src/swig/amlip_swig_js/types/id/TaskId.i new file mode 100644 index 00000000..245b5935 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/id/TaskId.i @@ -0,0 +1,27 @@ + +// Copyright 2023 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class TaskId +//////////////////////////////////////////////////////// + +%{ +#include + +using TaskId = eprosima::amlip::types::TaskId; +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobDataType.i new file mode 100644 index 00000000..16ec5556 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobDataType.i @@ -0,0 +1,37 @@ +// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class JobDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/GenericDataType.hpp"; + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +%{ +#include + +using JobDataType = eprosima::amlip::types::JobDataType; +%} + +// Include the class interfaces +%include + +%pythoncode %{ +JobDataType = GenericDataType +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobSolutionDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobSolutionDataType.i new file mode 100644 index 00000000..df692b30 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobSolutionDataType.i @@ -0,0 +1,37 @@ +// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class JobSolutionDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/GenericDataType.hpp"; + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +%{ +#include + +using JobSolutionDataType = eprosima::amlip::types::JobSolutionDataType; +%} + +// Include the class interfaces +%include + +%pythoncode %{ +JobSolutionDataType = GenericDataType +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/status/NodeKind.i b/amlip_swig_js/src/swig/amlip_swig_js/types/status/NodeKind.i new file mode 100644 index 00000000..a75e7418 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/status/NodeKind.i @@ -0,0 +1,31 @@ +// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class NodeKind +//////////////////////////////////////////////////////// + +// Import +%import(module="amlip_swig_js") "cpp_utils/macros/custom_enumeration.hpp"; + +// Ignore overloaded methods that have no application on Python +// Otherwise they will issue a warning +%ignore eprosima::amlip::types::operator <<(std::ostream &,const NodeKind&); +%ignore eprosima::amlip::types::to_string(const NodeKind&); + +%{ +#include +%} + +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/status/StateKind.i b/amlip_swig_js/src/swig/amlip_swig_js/types/status/StateKind.i new file mode 100644 index 00000000..d96f1135 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/status/StateKind.i @@ -0,0 +1,31 @@ +// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class StateKind +//////////////////////////////////////////////////////// + +// Import +%import(module="amlip_swig_js") "cpp_utils/macros/custom_enumeration.hpp"; + +// Ignore overloaded methods that have no application on Python +// Otherwise they will issue a warning +%ignore eprosima::amlip::types::operator <<(std::ostream &,const StateKind&); +%ignore eprosima::amlip::types::to_string(const StateKind&); + +%{ +#include +%} + +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/status/StatusDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/status/StatusDataType.i new file mode 100644 index 00000000..0fb661c2 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/status/StatusDataType.i @@ -0,0 +1,48 @@ +// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class StatusDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/InterfaceDataType.hpp"; + +// Include the class interfaces +// %include + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +// Ignore overloaded methods that have no application on Python +// Otherwise they will issue a warning +%ignore eprosima::amlip::types::StatusDataType::StatusDataType(StatusDataType&&); +%ignore eprosima::amlip::types::operator <<(std::ostream &,const StatusDataType&); + +// Declare the to string method +%extend eprosima::amlip::types::StatusDataType { + std::string __str__() const + { + return $self->to_string(); + } +} + +%{ +#include +%} + +// Include needed headers +%include +%include diff --git a/amlip_swig_js/test/CMakeLists.txt b/amlip_swig_js/test/CMakeLists.txt new file mode 100644 index 00000000..71007d2c --- /dev/null +++ b/amlip_swig_js/test/CMakeLists.txt @@ -0,0 +1,16 @@ +# Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Add subdirectory with tests +add_subdirectory(api) diff --git a/amlip_swig_js/test/api/CMakeLists.txt b/amlip_swig_js/test/api/CMakeLists.txt new file mode 100644 index 00000000..5e66705c --- /dev/null +++ b/amlip_swig_js/test/api/CMakeLists.txt @@ -0,0 +1,23 @@ +# Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Add API Tests +add_test( + NAME + api_tests + COMMAND + node ${CMAKE_CURRENT_SOURCE_DIR}/import_test.js + WORKING_DIRECTORY + ${CMAKE_CURRENT_SOURCE_DIR} +) diff --git a/amlip_swig_js/test/api/import_test.js b/amlip_swig_js/test/api/import_test.js new file mode 100644 index 00000000..3424fa49 --- /dev/null +++ b/amlip_swig_js/test/api/import_test.js @@ -0,0 +1,35 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Test that importing amlip_swig_js does not give any error. + +const assert = require('assert'); + +try { + require('/home/irenebm/eprosima/annapurna/AML-IP-ws/install/amlip_swig_js/lib/node_modules/amlip_swig_js/amlip_swig_js.so'); +} catch (error) { + console.error('Error importing amlip_swig_js:', error); + assert(false, 'Error importing amlip_swig_js') +} + +// try { +// require('/home/irenebm/eprosima/annapurna/AML-IP-ws/install/amlip_swig_js/lib/node_modules/amlip_swig_js/amlip_swig_js.so'); +// // If the module imports without throwing an error, the test passes +// expect(true).toBe(true); +// } catch (error) { +// // If an error occurs during import, fail the test and log the error +// console.error('Error importing amlip_swig_js:', error); +// // Fail the test explicitly +// expect(true).toBe(false); +// } From de6119103ec73f11de02ca7505613a3cd7038083 Mon Sep 17 00:00:00 2001 From: Irene Bandera Date: Wed, 27 Mar 2024 14:57:23 +0100 Subject: [PATCH 14/15] Add JavaScript bindings for amlip_cpp Signed-off-by: Irene Bandera --- amlip_swig_js/CMakeLists.txt | 10 - amlip_swig_js/binding.gyp | 29 + amlip_swig_js/package.json | 28 + amlip_swig_js/package.xml | 7 +- amlip_swig_js/project_settings.cmake | 11 +- amlip_swig_js/src/swig/CMakeLists.txt | 13 +- amlip_swig_js/src/swig/amlip_swig_js.i | 61 +- .../amlip_swig_js/node/AsyncComputingNode.i | 88 + .../swig/amlip_swig_js/node/AsyncEdgeNode.i | 85 + .../amlip_swig_js/node/AsyncInferenceNode.i | 89 + .../swig/amlip_swig_js/node/AsyncMainNode.i | 85 + .../swig/amlip_swig_js/node/ComputingNode.i | 56 + .../src/swig/amlip_swig_js/node/EdgeNode.i | 27 + .../swig/amlip_swig_js/node/InferenceNode.i | 57 + .../src/swig/amlip_swig_js/node/MainNode.i | 2 +- .../node/ModelManagerReceiverNode.i | 96 + .../node/ModelManagerSenderNode.i | 90 + .../src/swig/amlip_swig_js/node/StatusNode.i | 55 + .../amlip_swig_js/types/address/Address.i | 30 + .../amlip_swig_js/types/id/AmlipIdDataType.i | 6 +- .../types/inference/InferenceDataType.i | 33 + .../inference/InferenceSolutionDataType.i | 33 + .../amlip_swig_js/types/job/JobDataType.i | 6 +- .../types/job/JobSolutionDataType.i | 6 +- .../types/model/ModelReplyDataType.i | 33 + .../types/model/ModelRequestDataType.i | 33 + .../types/model/ModelStatisticsDataType.i | 50 + .../types/status/StatusDataType.i | 5 +- amlip_swig_js/test/api/CMakeLists.txt | 8 +- amlip_swig_js/test/api/import_test.js | 33 +- .../api/nodes/async_computing_node_test.js | 52 + .../test/api/nodes/async_edge_node_test.js | 52 + .../api/nodes/async_inference_node_test.js | 52 + .../test/api/nodes/async_main_node_test.js | 52 + .../test/api/nodes/computing_node_test.js | 50 + .../test/api/nodes/edge_node_test.js | 33 + .../test/api/nodes/inference_node_test.js | 33 + .../test/api/nodes/main_node_test.js | 50 + .../nodes/modelmanagerreceiver_node_test.js | 56 + .../api/nodes/modelmanagersender_node_test.js | 52 + .../test/api/nodes/status_node_test.js | 50 + .../test/api/types/create_types_test.js | 398 + amlip_swig_js/test/manual/async_computing.js | 39 + amlip_swig_js/test/manual/async_edge.js | 47 + amlip_swig_js/test/manual/async_inference.js | 39 + amlip_swig_js/test/manual/async_main.js | 47 + amlip_swig_js/test/manual/computing.js | 30 + amlip_swig_js/test/manual/edge.js | 32 + amlip_swig_js/test/manual/inference.js | 30 + amlip_swig_js/test/manual/main.js | 32 + .../test/manual/model_manager_receiver.js | 46 + .../test/manual/model_manager_sender.js | 50 + amlip_swig_js/test/manual/status.js | 41 + thirdparty/node/node.h | 834 ++ thirdparty/node/node_version.h | 122 + thirdparty/node/v8-platform.h | 395 + thirdparty/node/v8-version.h | 20 + thirdparty/node/v8.h | 10788 ++++++++++++++++ thirdparty/node/v8config.h | 425 + 59 files changed, 15022 insertions(+), 90 deletions(-) create mode 100644 amlip_swig_js/binding.gyp create mode 100644 amlip_swig_js/package.json create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/AsyncComputingNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/AsyncEdgeNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/AsyncInferenceNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/AsyncMainNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/ComputingNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/EdgeNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/InferenceNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/ModelManagerReceiverNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/ModelManagerSenderNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/node/StatusNode.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/address/Address.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/inference/InferenceDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/inference/InferenceSolutionDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelReplyDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelRequestDataType.i create mode 100644 amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelStatisticsDataType.i create mode 100644 amlip_swig_js/test/api/nodes/async_computing_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/async_edge_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/async_inference_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/async_main_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/computing_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/edge_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/inference_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/main_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/modelmanagerreceiver_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/modelmanagersender_node_test.js create mode 100644 amlip_swig_js/test/api/nodes/status_node_test.js create mode 100644 amlip_swig_js/test/api/types/create_types_test.js create mode 100644 amlip_swig_js/test/manual/async_computing.js create mode 100644 amlip_swig_js/test/manual/async_edge.js create mode 100644 amlip_swig_js/test/manual/async_inference.js create mode 100644 amlip_swig_js/test/manual/async_main.js create mode 100644 amlip_swig_js/test/manual/computing.js create mode 100644 amlip_swig_js/test/manual/edge.js create mode 100644 amlip_swig_js/test/manual/inference.js create mode 100644 amlip_swig_js/test/manual/main.js create mode 100644 amlip_swig_js/test/manual/model_manager_receiver.js create mode 100644 amlip_swig_js/test/manual/model_manager_sender.js create mode 100644 amlip_swig_js/test/manual/status.js create mode 100644 thirdparty/node/node.h create mode 100644 thirdparty/node/node_version.h create mode 100644 thirdparty/node/v8-platform.h create mode 100644 thirdparty/node/v8-version.h create mode 100644 thirdparty/node/v8.h create mode 100644 thirdparty/node/v8config.h diff --git a/amlip_swig_js/CMakeLists.txt b/amlip_swig_js/CMakeLists.txt index 66f40eb3..7c33305a 100644 --- a/amlip_swig_js/CMakeLists.txt +++ b/amlip_swig_js/CMakeLists.txt @@ -69,16 +69,6 @@ include(${SWIG_USE_FILE}) set(CMAKE_SWIG_FLAGS "") -# Set the path to the language-specific module file (e.g., for JavaScript) -# find_package(Javascript REQUIRED) -# list(APPEND CMAKE_MODULE_PATH -# ${CMAKE_CURRENT_SOURCE_DIR}/node_modules/node-cmake -# ) -# find_package(NodeJS REQUIRED) -# include_directories(/usr/include/nodejs) -include_directories(/home/irenebm/.nvm/versions/node/v11.15.0/include/node/) -# Set the path to the language-specific module file (e.g., for JavaScript) - add_subdirectory(src/swig) ############################################################################### diff --git a/amlip_swig_js/binding.gyp b/amlip_swig_js/binding.gyp new file mode 100644 index 00000000..21bca1cd --- /dev/null +++ b/amlip_swig_js/binding.gyp @@ -0,0 +1,29 @@ +{ + "targets": [ + { + "target_name": "amlip_swig_js", + "sources": [ + "../../../build/amlip_swig_js/src/swig/CMakeFiles/amlip_swig_js.dir/amlip_swig_jsJAVASCRIPT_wrap.cxx" + ], + "include_dirs" : [ "amlip_swig_js 0.1.0 - eprosima AML IP SWIG + eProsima AML IP JavaScript wrapper with SWIG Raul Sánchez-Mateos - Irene Bandera + Irene Bandera Juan López Apache 2.0 @@ -16,13 +16,14 @@ https://github.com/eProsima/AML-IP cmake - cmake_utils cpp_utils amlip_cpp ddspipe_participants + jest + cmake diff --git a/amlip_swig_js/project_settings.cmake b/amlip_swig_js/project_settings.cmake index 9f44a944..3476589a 100644 --- a/amlip_swig_js/project_settings.cmake +++ b/amlip_swig_js/project_settings.cmake @@ -13,7 +13,7 @@ # limitations under the License. ############################################################################### -# Set settings for project amlip_swig for SWIG code +# Set settings for project amlip_swig_js for SWIG code ############################################################################### set(MODULE_NAME @@ -23,13 +23,20 @@ set(MODULE_SUMMARY "SWIG library to create python bindings from amlip_cpp.") set(MODULE_FIND_PACKAGES - amlip_cpp cpp_utils ddspipe_core ddspipe_participants ddsrouter_core + amlip_cpp ) set(MODULE_DEPENDENCIES ${MODULE_FIND_PACKAGES} ) + +set(MODULE_THIRDPARTY_HEADERONLY + node + ) + +set(MODULE_THIRDPARTY_PATH + "../thirdparty") diff --git a/amlip_swig_js/src/swig/CMakeLists.txt b/amlip_swig_js/src/swig/CMakeLists.txt index ccbb2c63..c8bcf306 100644 --- a/amlip_swig_js/src/swig/CMakeLists.txt +++ b/amlip_swig_js/src/swig/CMakeLists.txt @@ -35,21 +35,18 @@ if(UNIX AND CMAKE_SIZEOF_VOID_P EQUAL 8) set_property(TARGET ${PROJECT_NAME} PROPERTY SWIG_COMPILE_DEFINITIONS SWIGWORDSIZE64) endif() -target_link_libraries(${PROJECT_NAME} - amlip_cpp +target_link_libraries(${PROJECT_NAME} PRIVATE + amlip_cpp ) -SET (JAVASCRIPT_MODULE_PATH - ${LIB_INSTALL_DIR}/node_modules/${PROJECT_NAME} -) - # Install install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}-targets - DESTINATION ${JAVASCRIPT_MODULE_PATH} + DESTINATION ${CMAKE_INSTALL_PREFIX} ) + get_property(support_files TARGET ${PROJECT_NAME} PROPERTY SWIG_SUPPORT_FILES) -install(FILES ${support_files} DESTINATION ${JAVASCRIPT_MODULE_PATH}) +install(FILES ${support_files} DESTINATION ${CMAKE_INSTALL_PREFIX}) export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_BINARY_DIR}/cmake/config/${PROJECT_NAME}-targets.cmake) diff --git a/amlip_swig_js/src/swig/amlip_swig_js.i b/amlip_swig_js/src/swig/amlip_swig_js.i index 9e548ba8..9b1d7622 100644 --- a/amlip_swig_js/src/swig/amlip_swig_js.i +++ b/amlip_swig_js/src/swig/amlip_swig_js.i @@ -1,4 +1,4 @@ -// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,41 +12,52 @@ // See the License for the specific language governing permissions and // limitations under the License. -%module(directors="1", threads="1") amlip_swig_js +%module amlip_swig_js // Macro delcarations // Any macro used on the header files will give an error if it is not redefined here #define AMLIP_CPP_DllAPI // SWIG helper modules -// %include "cpointer.i" +%include "cpointer.i" %include "stdint.i" -// %include "std_array.i" -// %include "std_list.i" -// %include "std_set.i" -// %include "std_string.i" -// %include "std_shared_ptr.i" +%include "std_string.i" %include "std_vector.i" - -// Definition of internal types -typedef short int16_t; -typedef int int32_t; -typedef long int64_t; -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; -typedef unsigned long uint64_t; +%include "std_unique_ptr.i" // IMPORTANT: the order of these includes is relevant, and must keep same order of cpp declarations. // types %include "amlip_swig_js/types/InterfaceDataType.i" %include "amlip_swig_js/types/GenericDataType.i" -// %include "amlip_swig_js/types/id/AmlipIdDataType.i" -// %include "amlip_swig_js/types/id/TaskId.i" -// %include "amlip_swig_js/types/status/NodeKind.i" -// %include "amlip_swig_js/types/status/StateKind.i" -// %include "amlip_swig_js/types/status/StatusDataType.i" +%include "amlip_swig_js/types/id/AmlipIdDataType.i" +%include "amlip_swig_js/types/id/TaskId.i" +%include "amlip_swig_js/types/status/NodeKind.i" +%include "amlip_swig_js/types/status/StateKind.i" +%include "amlip_swig_js/types/status/StatusDataType.i" +%include "amlip_swig_js/types/job/JobDataType.i" +%include "amlip_swig_js/types/job/JobSolutionDataType.i" +%include "amlip_swig_js/types/inference/InferenceDataType.i" +%include "amlip_swig_js/types/inference/InferenceSolutionDataType.i" +%include "amlip_swig_js/types/model/ModelRequestDataType.i" +%include "amlip_swig_js/types/model/ModelReplyDataType.i" +%include "amlip_swig_js/types/model/ModelStatisticsDataType.i" +%include "amlip_swig_js/types/address/Address.i" -// // node -// %include "amlip_swig_js/node/ParentNode.i" -// %include "amlip_swig_js/node/MainNode.i" +// node +%include "amlip_swig_js/node/ParentNode.i" +%include "amlip_swig_js/node/StatusNode.i" +%include "amlip_swig_js/node/MainNode.i" +%include "amlip_swig_js/node/ComputingNode.i" +%include "amlip_swig_js/node/AsyncMainNode.i" +%include "amlip_swig_js/node/AsyncComputingNode.i" +%include "amlip_swig_js/node/EdgeNode.i" +%include "amlip_swig_js/node/AsyncEdgeNode.i" +%include "amlip_swig_js/node/InferenceNode.i" +%include "amlip_swig_js/node/AsyncInferenceNode.i" +%include "amlip_swig_js/node/ModelManagerSenderNode.i" +%include "amlip_swig_js/node/ModelManagerReceiverNode.i" +// TODO +// %include "amlip_swig_js/node/AgentNode.i" +// %include "amlip_swig_js/node/ClientNode.i" +// %include "amlip_swig_js/node/ServerNode.i" +// %include "amlip_swig_js/node/RepeaterNode.i" diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncComputingNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncComputingNode.i new file mode 100644 index 00000000..ae4bf0e9 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncComputingNode.i @@ -0,0 +1,88 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class AsyncComputingNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::JobReplier; + +%unique_ptr(JobReplierJS); + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +class JobReplierJS : public eprosima::amlip::node::JobReplier +{ +public: + + JobReplierJS() + { + // Do nothing + } + + virtual ~JobReplierJS() + { + // Do nothing + } + + virtual eprosima::amlip::types::JobSolutionDataType process_job( + const eprosima::amlip::types::JobDataType& job, + const eprosima::amlip::types::TaskId& task_id, + const eprosima::amlip::types::AmlipIdDataType& client_id) + { + std::string job_solution = job.to_string(); + std::transform(job_solution.begin(), job_solution.end(), job_solution.begin(), + [](unsigned char c){ return std::tolower(c); } + ); + std::cout << "Data received from client: " << client_id + << " with id: " << task_id + << " job: " << job.to_string() + << " inference: " << job_solution << std::endl; + return eprosima::amlip::types::JobSolutionDataType(job_solution); + } +}; + +class AsyncComputingNodeJS : public eprosima::amlip::node::AsyncComputingNode +{ +public: + + AsyncComputingNodeJS( + const char* name, + std::unique_ptr& replier, + uint32_t domain_id) + : eprosima::amlip::node::AsyncComputingNode(name, std::move(replier), domain_id) + { + // Do nothing + } + + AsyncComputingNodeJS( + const char* name, + std::unique_ptr& replier) + : eprosima::amlip::node::AsyncComputingNode(name, std::move(replier)) + { + // Do nothing + } +}; + +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncEdgeNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncEdgeNode.i new file mode 100644 index 00000000..23334d8c --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncEdgeNode.i @@ -0,0 +1,85 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class AsyncEdgeNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::InferenceSolutionListener; + +%unique_ptr(InferenceSolutionListenerJS) + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +bool block_edge_ = true; + +class InferenceSolutionListenerJS : public eprosima::amlip::node::InferenceSolutionListener +{ +public: + + InferenceSolutionListenerJS() + { + // Do nothing + } + + virtual ~InferenceSolutionListenerJS() + { + // Do nothing + } + + void inference_received( + const eprosima::amlip::types::InferenceSolutionDataType& solution, + const eprosima::amlip::types::TaskId& task_id, + const eprosima::amlip::types::AmlipIdDataType& server_id) override + { + std::cout << "Inference solution received for task : " << task_id + << " answered from server : " << server_id + << " . Solution : " << solution << " ." << std::endl; + block_edge_ = false; + } +}; + +// Transfers a unique_ptr in JavaScript to a shared_ptr in C++ +class AsyncEdgeNodeJS : public eprosima::amlip::node::AsyncEdgeNode +{ +public: + + AsyncEdgeNodeJS( + const char* name, + std::unique_ptr& listener, + uint32_t domain_id) + : eprosima::amlip::node::AsyncEdgeNode(name, std::move(listener), domain_id) + { + // Do nothing + } + + AsyncEdgeNodeJS( + const char* name, + std::unique_ptr& listener) + : eprosima::amlip::node::AsyncEdgeNode(name, std::move(listener)) + { + // Do nothing + } +}; +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncInferenceNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncInferenceNode.i new file mode 100644 index 00000000..1b250d1a --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncInferenceNode.i @@ -0,0 +1,89 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class AsyncInferenceNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::InferenceReplier; + +%unique_ptr(InferenceReplierJS); + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +class InferenceReplierJS : public eprosima::amlip::node::InferenceReplier +{ +public: + + InferenceReplierJS() + { + // Do nothing + } + + virtual ~InferenceReplierJS() + { + // Do nothing + } + + eprosima::amlip::types::InferenceSolutionDataType process_inference( + const eprosima::amlip::types::InferenceDataType& inference, + const eprosima::amlip::types::TaskId& task_id, + const eprosima::amlip::types::AmlipIdDataType& client_id) override + { + std::string inference_solution = inference.to_string(); + std::transform(inference_solution.begin(), inference_solution.end(), inference_solution.begin(), + [](unsigned char c){ return std::tolower(c); } + ); + std::cout << "Data received from client: " << client_id + << " with id: " << task_id + << " job: " << inference.to_string() + << " inference: " << inference_solution << std::endl; + return eprosima::amlip::types::InferenceSolutionDataType(inference_solution); + } +}; + +class AsyncInferenceNodeJS : public eprosima::amlip::node::AsyncInferenceNode +{ +public: + + AsyncInferenceNodeJS( + const char* name, + std::unique_ptr& replier, + uint32_t domain_id) + : eprosima::amlip::node::AsyncInferenceNode(name, std::move(replier), domain_id) + { + // Do nothing + } + + AsyncInferenceNodeJS( + const char* name, + std::unique_ptr& replier) + : eprosima::amlip::node::AsyncInferenceNode(name, std::move(replier)) + { + // Do nothing + } + +}; + +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncMainNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncMainNode.i new file mode 100644 index 00000000..32da96ed --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/AsyncMainNode.i @@ -0,0 +1,85 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class AsyncMainNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::SolutionListener; + +%unique_ptr(SolutionListenerJS) + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +bool block_main_ = true; + +class SolutionListenerJS : public eprosima::amlip::node::SolutionListener +{ +public: + + SolutionListenerJS() + { + // Do nothing + } + + virtual ~SolutionListenerJS() + { + // Do nothing + } + + void solution_received( + const eprosima::amlip::types::JobSolutionDataType& solution, + const eprosima::amlip::types::TaskId& task_id, + const eprosima::amlip::types::AmlipIdDataType& server_id) override + { + std::cout << "Solution received for task : " << task_id + << " answered from server : " << server_id + << " . Solution : " << solution << " ." << std::endl; + block_main_ = false; + } + +}; + +// Transfers a unique_ptr in JavaScript to a shared_ptr in C++ +class AsyncMainNodeJS : public eprosima::amlip::node::AsyncMainNode +{ +public: + AsyncMainNodeJS( + const char* name, + std::unique_ptr& listener, + uint32_t domain_id) + : eprosima::amlip::node::AsyncMainNode(name, std::move(listener), domain_id) + { + // Do nothing + } + + AsyncMainNodeJS( + const char* name, + std::unique_ptr& listener) + : eprosima::amlip::node::AsyncMainNode(name, std::move(listener)) + { + // Do nothing + } +}; +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/ComputingNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/ComputingNode.i new file mode 100644 index 00000000..c31a2c50 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/ComputingNode.i @@ -0,0 +1,56 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class ComputingNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::JobListener; + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +class JobListenerJS : public eprosima::amlip::node::JobListener +{ +public: + JobListenerJS() + { + // Do nothing + } + + virtual ~JobListenerJS() + { + // Do nothing + } + + virtual eprosima::amlip::types::JobSolutionDataType process_job(const eprosima::amlip::types::JobDataType& job) const + { + std::string job_solution = job.to_string(); + std::transform(job_solution.begin(), job_solution.end(), job_solution.begin(), + [](unsigned char c){ return std::tolower(c); } + ); + return eprosima::amlip::types::JobSolutionDataType(job_solution); + } +}; + +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/EdgeNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/EdgeNode.i new file mode 100644 index 00000000..475f97de --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/EdgeNode.i @@ -0,0 +1,27 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class EdgeNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%{ +#include +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/InferenceNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/InferenceNode.i new file mode 100644 index 00000000..72520be5 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/InferenceNode.i @@ -0,0 +1,57 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class InferenceNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::InferenceListener; + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +class InferenceListenerJS : public eprosima::amlip::node::InferenceListener +{ +public: + + InferenceListenerJS() + { + // Do nothing + } + + virtual ~InferenceListenerJS() + { + // Do nothing + } + + eprosima::amlip::types::InferenceSolutionDataType process_inference(const eprosima::amlip::types::InferenceDataType& inference) const override + { + std::string inference_solution = inference.to_string(); + std::transform(inference_solution.begin(), inference_solution.end(), inference_solution.begin(), + [](unsigned char c){ return std::tolower(c); } + ); + return eprosima::amlip::types::InferenceSolutionDataType(inference_solution); + } +}; + +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/MainNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/MainNode.i index 435a3916..d2a8e291 100644 --- a/amlip_swig_js/src/swig/amlip_swig_js/node/MainNode.i +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/MainNode.i @@ -1,4 +1,4 @@ -// Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/ModelManagerReceiverNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/ModelManagerReceiverNode.i new file mode 100644 index 00000000..a2e11962 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/ModelManagerReceiverNode.i @@ -0,0 +1,96 @@ +// Copyright 2023 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class ModelManagerReceiverNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::ModelListener; + +%unique_ptr(ModelListenerJS); + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +bool block_modelmanagerreceiver_ = true; + +class ModelListenerJS : public eprosima::amlip::node::ModelListener +{ +public: + + ModelListenerJS() + { + // Do nothing + } + + virtual ~ModelListenerJS() + { + // Do nothing + } + + bool statistics_received( + const eprosima::amlip::types::ModelStatisticsDataType statistics) override + { + std::cout << "Statistics received: " << statistics.to_string() << " ." << std::endl; + // Decide if we want the model based on the statistics received + return true; + } + + bool model_received( + const eprosima::amlip::types::ModelReplyDataType model) override + { + std::cout << "Reply received: " << model.to_string() << " ." << std::endl; + block_modelmanagerreceiver_ = false; + + return true; + } +}; + +class ModelManagerReceiverNodeJS : public eprosima::amlip::node::ModelManagerReceiverNode +{ +public: + + ModelManagerReceiverNodeJS( + eprosima::amlip::types::AmlipIdDataType id, + eprosima::amlip::types::ModelRequestDataType data, + uint32_t domain_id) + : eprosima::amlip::node::ModelManagerReceiverNode(id, data, domain_id) + { + // Do nothing + } + + ModelManagerReceiverNodeJS( + eprosima::amlip::types::AmlipIdDataType id, + eprosima::amlip::types::ModelRequestDataType data) + : eprosima::amlip::node::ModelManagerReceiverNode(id, data) + { + // Do nothing + } + + void start( + std::unique_ptr& listener) + { + eprosima::amlip::node::ModelManagerReceiverNode::start(std::move(listener)); + } +}; +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/ModelManagerSenderNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/ModelManagerSenderNode.i new file mode 100644 index 00000000..7465184f --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/ModelManagerSenderNode.i @@ -0,0 +1,90 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class ModelManagerSenderNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::ModelReplier; + +%unique_ptr(ModelReplierJS) + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +bool block_modelmanagersender_ = true; + +class ModelReplierJS : public eprosima::amlip::node::ModelReplier +{ +public: + + ModelReplierJS() + { + // Do nothing + } + + virtual ~ModelReplierJS() + { + // Do nothing + } + + eprosima::amlip::types::ModelReplyDataType fetch_model( + const eprosima::amlip::types::ModelRequestDataType request) override + { + std::cout << "Request received: " << request.to_string() << std::endl; + std::string reply = request.to_string(); + std::transform(reply.begin(), reply.end(), reply.begin(), + [](unsigned char c){ return std::tolower(c); } + ); + block_modelmanagersender_ = false; + + return eprosima::amlip::types::ModelReplyDataType(reply); + } +}; + +class ModelManagerSenderNodeJS : public eprosima::amlip::node::ModelManagerSenderNode +{ +public: + + ModelManagerSenderNodeJS( + eprosima::amlip::types::AmlipIdDataType id, + uint32_t domain_id) + : eprosima::amlip::node::ModelManagerSenderNode(id, domain_id) + { + // Do nothing + } + + ModelManagerSenderNodeJS( + eprosima::amlip::types::AmlipIdDataType id) + : eprosima::amlip::node::ModelManagerSenderNode(id) + { + // Do nothing + } + + void start( + std::unique_ptr& replier) + { + eprosima::amlip::node::ModelManagerSenderNode::start(std::move(replier)); + } +}; +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/node/StatusNode.i b/amlip_swig_js/src/swig/amlip_swig_js/node/StatusNode.i new file mode 100644 index 00000000..4dbc1e31 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/node/StatusNode.i @@ -0,0 +1,55 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class StatusNode +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/node/ParentNode.hpp"; + +%ignore eprosima::amlip::node::StatusListener; + +// Ignore the process_status_async function with std::function +%ignore eprosima::amlip::node::StatusNode::process_status_async(const std::function&); + +%{ +#include +%} + +// Include the class interfaces +%include + +%inline %{ + +class StatusListenerJS : public eprosima::amlip::node::StatusListener +{ +public: + + StatusListenerJS() + { + // Do nothing + } + + virtual ~StatusListenerJS() + { + // Do nothing + } + + void status_received(const eprosima::amlip::types::StatusDataType& status) const override + { + std::cout << "Status received : " << status << std::endl; + } +}; +%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/address/Address.i b/amlip_swig_js/src/swig/amlip_swig_js/types/address/Address.i new file mode 100644 index 00000000..6b3ded62 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/address/Address.i @@ -0,0 +1,30 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class Address +//////////////////////////////////////////////////////// + +// Any macro used on the header files will give an error if it is not redefined here +#define DDSPIPE_PARTICIPANTS_DllAPI + +%{ +#include +%} + +// Ignore overloaded methods that have no application on Python +%ignore eprosima::ddspipe::participants::types::operator <<(std::ostream &,const Address&); + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/id/AmlipIdDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/id/AmlipIdDataType.i index a99531ac..9223dc96 100644 --- a/amlip_swig_js/src/swig/amlip_swig_js/types/id/AmlipIdDataType.i +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/id/AmlipIdDataType.i @@ -1,4 +1,4 @@ -// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,10 +19,6 @@ // Import parent class %import(module="amlip_swig_js") "amlip_cpp/types/InterfaceDataType.hpp"; -// namespace std { -// %template(rand_id) array; -// } - // Assignemt operators are ignored, as there is no such thing in Python. // Trying to export them issues a warning %ignore *::operator=; diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/inference/InferenceDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/inference/InferenceDataType.i new file mode 100644 index 00000000..e8ee627a --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/inference/InferenceDataType.i @@ -0,0 +1,33 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class InferenceDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/GenericDataType.hpp"; + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +%{ +#include + +using InferenceDataType = eprosima::amlip::types::InferenceDataType; +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/inference/InferenceSolutionDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/inference/InferenceSolutionDataType.i new file mode 100644 index 00000000..11db2e1b --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/inference/InferenceSolutionDataType.i @@ -0,0 +1,33 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class InferenceSolutionDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/GenericDataType.hpp"; + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +%{ +#include + +using InferenceSolutionDataType = eprosima::amlip::types::InferenceSolutionDataType; +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobDataType.i index 16ec5556..cbc92e94 100644 --- a/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobDataType.i +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobDataType.i @@ -1,4 +1,4 @@ -// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -31,7 +31,3 @@ using JobDataType = eprosima::amlip::types::JobDataType; // Include the class interfaces %include - -%pythoncode %{ -JobDataType = GenericDataType -%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobSolutionDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobSolutionDataType.i index df692b30..728fae03 100644 --- a/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobSolutionDataType.i +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/job/JobSolutionDataType.i @@ -1,4 +1,4 @@ -// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -31,7 +31,3 @@ using JobSolutionDataType = eprosima::amlip::types::JobSolutionDataType; // Include the class interfaces %include - -%pythoncode %{ -JobSolutionDataType = GenericDataType -%} diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelReplyDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelReplyDataType.i new file mode 100644 index 00000000..c5ba56b6 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelReplyDataType.i @@ -0,0 +1,33 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class ModelReplyDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/GenericDataType.hpp"; + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +%{ +#include + +using ModelReplyDataType = eprosima::amlip::types::ModelReplyDataType; +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelRequestDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelRequestDataType.i new file mode 100644 index 00000000..f44a048e --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelRequestDataType.i @@ -0,0 +1,33 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class ModelRequestDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/GenericDataType.hpp"; + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +%{ +#include + +using ModelRequestDataType = eprosima::amlip::types::ModelRequestDataType; +%} + +// Include the class interfaces +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelStatisticsDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelStatisticsDataType.i new file mode 100644 index 00000000..d292f931 --- /dev/null +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/model/ModelStatisticsDataType.i @@ -0,0 +1,50 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//////////////////////////////////////////////////////// +// Binding for class ModelStatisticsDataType +//////////////////////////////////////////////////////// + +// Import parent class +%import(module="amlip_swig_js") "amlip_cpp/types/InterfaceDataType.hpp"; + +namespace std { + %template(bytes) vector; +} + +// Assignemt operators are ignored, as there is no such thing in Python. +// Trying to export them issues a warning +%ignore *::operator=; + +// Ignore overloaded methods that have no application on Python +// Otherwise they will issue a warning +%ignore eprosima::amlip::types::ModelStatisticsDataType::ModelStatisticsDataType(ModelStatisticsDataType&&); +%ignore eprosima::amlip::types::operator <<(std::ostream &,const ModelStatisticsDataType&); + +// Declare the to string method +%extend eprosima::amlip::types::ModelStatisticsDataType { + std::string __str__() const + { + return $self->to_string(); + } +} + +%{ +#include + +%} + +// Include the class interfaces +%include +%include diff --git a/amlip_swig_js/src/swig/amlip_swig_js/types/status/StatusDataType.i b/amlip_swig_js/src/swig/amlip_swig_js/types/status/StatusDataType.i index 0fb661c2..c8a2a5ef 100644 --- a/amlip_swig_js/src/swig/amlip_swig_js/types/status/StatusDataType.i +++ b/amlip_swig_js/src/swig/amlip_swig_js/types/status/StatusDataType.i @@ -1,4 +1,4 @@ -// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,9 +19,6 @@ // Import parent class %import(module="amlip_swig_js") "amlip_cpp/types/InterfaceDataType.hpp"; -// Include the class interfaces -// %include - // Assignemt operators are ignored, as there is no such thing in Python. // Trying to export them issues a warning %ignore *::operator=; diff --git a/amlip_swig_js/test/api/CMakeLists.txt b/amlip_swig_js/test/api/CMakeLists.txt index 5e66705c..77ee2692 100644 --- a/amlip_swig_js/test/api/CMakeLists.txt +++ b/amlip_swig_js/test/api/CMakeLists.txt @@ -13,11 +13,13 @@ # limitations under the License. # Add API Tests -add_test( +add_custom_target(run_js_tests NAME api_tests COMMAND - node ${CMAKE_CURRENT_SOURCE_DIR}/import_test.js + bash -c "npm install && npm run test" WORKING_DIRECTORY - ${CMAKE_CURRENT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR} + COMMENT + "Running JavaScript tests with Jest" ) diff --git a/amlip_swig_js/test/api/import_test.js b/amlip_swig_js/test/api/import_test.js index 3424fa49..1e458d54 100644 --- a/amlip_swig_js/test/api/import_test.js +++ b/amlip_swig_js/test/api/import_test.js @@ -12,24 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Test that importing amlip_swig_js does not give any error. - const assert = require('assert'); -try { - require('/home/irenebm/eprosima/annapurna/AML-IP-ws/install/amlip_swig_js/lib/node_modules/amlip_swig_js/amlip_swig_js.so'); -} catch (error) { - console.error('Error importing amlip_swig_js:', error); - assert(false, 'Error importing amlip_swig_js') -} - -// try { -// require('/home/irenebm/eprosima/annapurna/AML-IP-ws/install/amlip_swig_js/lib/node_modules/amlip_swig_js/amlip_swig_js.so'); -// // If the module imports without throwing an error, the test passes -// expect(true).toBe(true); -// } catch (error) { -// // If an error occurs during import, fail the test and log the error -// console.error('Error importing amlip_swig_js:', error); -// // Fail the test explicitly -// expect(true).toBe(false); -// } +// Test that importing amlip_swig_js does not give any error. +test('Import amlip_swig_js module', () => { + console.log('TEST: Import amlip_swig_js module') + try { + require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + // If the module imports without throwing an error, the test passes + assert(true, 'amlip_swig_js module imports without errors') + console.log('amlip_swig_js module imports without errors') + } catch (error) { + // If an error occurs during import, fail the test and log the error + console.error('Error importing amlip_swig_js:', error); + assert(false, 'Error importing amlip_swig_js') + } +}); diff --git a/amlip_swig_js/test/api/nodes/async_computing_node_test.js b/amlip_swig_js/test/api/nodes/async_computing_node_test.js new file mode 100644 index 00000000..3ad58ddb --- /dev/null +++ b/amlip_swig_js/test/api/nodes/async_computing_node_test.js @@ -0,0 +1,52 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an AsyncComputingNodeJS does not give any error. +test('Create AsyncComputingNodeJS', () => { + console.log('TEST: Create AsyncComputingNodeJS') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const replier = new amlip_swig_js.JobReplierJS() + const asynccomputingNode = new amlip_swig_js.AsyncComputingNodeJS('async_computing_node_test', replier); + // If the AsyncComputingNodeJS is created without throwing an error, the test passes + assert(true, 'AsyncComputingNodeJS is created without errors') + console.log('AsyncComputingNodeJS is created without errors') + assert(asynccomputingNode instanceof amlip_swig_js.AsyncComputingNodeJS, 'asynccomputingNode is an instance of AsyncComputingNodeJS') + console.log('asynccomputingNode is an instance of AsyncComputingNodeJS') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AsyncComputingNodeJS:', error) + assert(false, 'Error creating AsyncComputingNodeJS') + } +}); + +test('Create AsyncComputingNodeJS with domain', () => { + console.log('TEST: Create AsyncComputingNodeJS with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const replier = new amlip_swig_js.JobReplierJS() + const asynccomputingNode = new amlip_swig_js.AsyncComputingNodeJS('async_computing_node_test', replier, 166); + // If the AsyncComputingNodeJS is created without throwing an error, the test passes + assert(true, 'AsyncComputingNodeJS is created with domain without errors') + console.log('AsyncComputingNodeJS is created with domain without errors') + assert(asynccomputingNode instanceof amlip_swig_js.AsyncComputingNodeJS, 'asynccomputingNode is an instance of AsyncComputingNodeJS') + console.log('asynccomputingNode is an instance of AsyncComputingNodeJS') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AsyncComputingNodeJS with domain:', error) + assert(false, 'Error creating AsyncComputingNodeJS with domain') + } +}); diff --git a/amlip_swig_js/test/api/nodes/async_edge_node_test.js b/amlip_swig_js/test/api/nodes/async_edge_node_test.js new file mode 100644 index 00000000..7feb7b88 --- /dev/null +++ b/amlip_swig_js/test/api/nodes/async_edge_node_test.js @@ -0,0 +1,52 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an AsyncEdgeNode does not give any error. +test('Create AsyncEdgeNode', () => { + console.log('TEST: Create AsyncEdgeNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const listener = new amlip_swig_js.InferenceSolutionListenerJS() + const asyncedgeNode = new amlip_swig_js.AsyncEdgeNodeJS('async_edge_node_test', listener); + // If the AsyncEdgeNode is created without throwing an error, the test passes + assert(true, 'AsyncEdgeNode is created without errors') + console.log('AsyncEdgeNode is created without errors') + assert(asyncedgeNode instanceof amlip_swig_js.AsyncEdgeNodeJS, 'asyncedgeNode is an instance of AsyncEdgeNode') + console.log('asyncedgeNode is an instance of AsyncEdgeNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AsyncEdgeNode:', error) + assert(false, 'Error creating AsyncEdgeNode') + } +}); + +test('Create AsyncEdgeNode with domain', () => { + console.log('TEST: Create AsyncEdgeNode with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const listener = new amlip_swig_js.InferenceSolutionListenerJS() + const asyncedgeNode = new amlip_swig_js.AsyncEdgeNodeJS('async_edge_node_test', listener, 166); + // If the AsyncEdgeNode is created without throwing an error, the test passes + assert(true, 'AsyncEdgeNode is created with domain without errors') + console.log('AsyncEdgeNode is created with domain without errors') + assert(asyncedgeNode instanceof amlip_swig_js.AsyncEdgeNodeJS, 'asyncedgeNode is an instance of AsyncEdgeNode') + console.log('asyncedgeNode is an instance of AsyncEdgeNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AsyncEdgeNode with domain:', error) + assert(false, 'Error creating AsyncEdgeNode with domain') + } +}); diff --git a/amlip_swig_js/test/api/nodes/async_inference_node_test.js b/amlip_swig_js/test/api/nodes/async_inference_node_test.js new file mode 100644 index 00000000..a552d039 --- /dev/null +++ b/amlip_swig_js/test/api/nodes/async_inference_node_test.js @@ -0,0 +1,52 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an AsyncInferenceNodeJS does not give any error. +test('Create AsyncInferenceNodeJS', () => { + console.log('TEST: Create AsyncInferenceNodeJS') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const replier = new amlip_swig_js.InferenceReplierJS() + const asyncinferenceNode = new amlip_swig_js.AsyncInferenceNodeJS('async_inference_node_test', replier); + // If the AsyncInferenceNodeJS is created without throwing an error, the test passes + assert(true, 'AsyncInferenceNodeJS is created without errors') + console.log('AsyncInferenceNodeJS is created without errors') + assert(asyncinferenceNode instanceof amlip_swig_js.AsyncInferenceNodeJS, 'asyncinferenceNode is an instance of AsyncInferenceNodeJS') + console.log('asyncinferenceNode is an instance of AsyncInferenceNodeJS') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AsyncInferenceNodeJS:', error) + assert(false, 'Error creating AsyncInferenceNodeJS') + } +}); + +test('Create AsyncInferenceNodeJS with domain', () => { + console.log('TEST: Create AsyncInferenceNodeJS with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const replier = new amlip_swig_js.InferenceReplierJS() + const asyncinferenceNode = new amlip_swig_js.AsyncInferenceNodeJS('async_inference_node_test', replier, 166); + // If the AsyncInferenceNodeJS is created without throwing an error, the test passes + assert(true, 'AsyncInferenceNodeJS is created with domain without errors') + console.log('AsyncInferenceNodeJS is created with domain without errors') + assert(asyncinferenceNode instanceof amlip_swig_js.AsyncInferenceNodeJS, 'asyncinferenceNode is an instance of AsyncInferenceNodeJS') + console.log('asyncinferenceNode is an instance of AsyncInferenceNodeJS') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AsyncInferenceNodeJS with domain:', error) + assert(false, 'Error creating AsyncInferenceNodeJS with domain') + } +}); diff --git a/amlip_swig_js/test/api/nodes/async_main_node_test.js b/amlip_swig_js/test/api/nodes/async_main_node_test.js new file mode 100644 index 00000000..8bef3b03 --- /dev/null +++ b/amlip_swig_js/test/api/nodes/async_main_node_test.js @@ -0,0 +1,52 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an AsyncMainNode does not give any error. +test('Create AsyncMainNode', () => { + console.log('TEST: Create AsyncMainNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const listener = new amlip_swig_js.SolutionListenerJS() + const asyncmainNode = new amlip_swig_js.AsyncMainNodeJS('async_main_node_test', listener); + // If the AsyncMainNode is created without throwing an error, the test passes + assert(true, 'AsyncMainNode is created without errors') + console.log('AsyncMainNode is created without errors') + assert(asyncmainNode instanceof amlip_swig_js.AsyncMainNodeJS, 'asyncmainNode is an instance of AsyncMainNode') + console.log('asyncmainNode is an instance of MainNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AsyncMainNode:', error) + assert(false, 'Error creating AsyncMainNode') + } +}); + +test('Create AsyncMainNode with domain', () => { + console.log('TEST: Create AsyncMainNode with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const listener = new amlip_swig_js.SolutionListenerJS() + const asyncmainNode = new amlip_swig_js.AsyncMainNodeJS('async_main_node_test', listener, 166); + // If the AsyncMainNode is created without throwing an error, the test passes + assert(true, 'AsyncMainNode is created with domain without errors') + console.log('AsyncMainNode is created with domain without errors') + assert(asyncmainNode instanceof amlip_swig_js.AsyncMainNodeJS, 'asyncmainNode is an instance of AsyncMainNode') + console.log('asyncmainNode is an instance of AsyncMainNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AsyncMainNode with domain:', error) + assert(false, 'Error creating AsyncMainNode with domain') + } +}); diff --git a/amlip_swig_js/test/api/nodes/computing_node_test.js b/amlip_swig_js/test/api/nodes/computing_node_test.js new file mode 100644 index 00000000..7db56d15 --- /dev/null +++ b/amlip_swig_js/test/api/nodes/computing_node_test.js @@ -0,0 +1,50 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an ComputingNode does not give any error. +test('Create ComputingNode', () => { + console.log('TEST: Create ComputingNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const computingNode = new amlip_swig_js.ComputingNode('computing_node_test'); + // If the ComputingNode is created without throwing an error, the test passes + assert(true, 'ComputingNode is created without errors') + console.log('ComputingNode is created without errors') + assert(computingNode instanceof amlip_swig_js.ComputingNode, 'computingNode is an instance of ComputingNode') + console.log('computingNode is an instance of ComputingNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ComputingNode:', error) + assert(false, 'Error creating ComputingNode') + } +}); + +test('Create ComputingNode with domain', () => { + console.log('TEST: Create ComputingNode with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const computingNode = new amlip_swig_js.ComputingNode('computing_node_test', 166); + // If the ComputingNode is created without throwing an error, the test passes + assert(true, 'ComputingNode is created with domain without errors') + console.log('ComputingNode is created with domain without errors') + assert(computingNode instanceof amlip_swig_js.ComputingNode, 'computingNode is an instance of ComputingNode') + console.log('computingNode is an instance of ComputingNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ComputingNode with domain:', error) + assert(false, 'Error creating ComputingNode with domain') + } +}); diff --git a/amlip_swig_js/test/api/nodes/edge_node_test.js b/amlip_swig_js/test/api/nodes/edge_node_test.js new file mode 100644 index 00000000..5bc28e62 --- /dev/null +++ b/amlip_swig_js/test/api/nodes/edge_node_test.js @@ -0,0 +1,33 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an EdgeNode does not give any error. +test('Create EdgeNode', () => { + console.log('TEST: Create EdgeNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const edgeNode = new amlip_swig_js.EdgeNode('edge_node_test'); + // If the EdgeNode is created without throwing an error, the test passes + assert(true, 'EdgeNode is created without errors') + console.log('EdgeNode is created without errors') + assert(edgeNode instanceof amlip_swig_js.EdgeNode, 'edgeNode is an instance of EdgeNode') + console.log('edgeNode is an instance of EdgeNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating EdgeNode:', error) + assert(false, 'Error creating EdgeNode') + } +}); diff --git a/amlip_swig_js/test/api/nodes/inference_node_test.js b/amlip_swig_js/test/api/nodes/inference_node_test.js new file mode 100644 index 00000000..9b091e3f --- /dev/null +++ b/amlip_swig_js/test/api/nodes/inference_node_test.js @@ -0,0 +1,33 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an InferenceNode does not give any error. +test('Create InferenceNode', () => { + console.log('TEST: Create InferenceNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const inferenceNode = new amlip_swig_js.InferenceNode('inference_node_test'); + // If the InferenceNode is created without throwing an error, the test passes + assert(true, 'InferenceNode is created without errors') + console.log('InferenceNode is created without errors') + assert(inferenceNode instanceof amlip_swig_js.InferenceNode, 'inferenceNode is an instance of InferenceNode') + console.log('inferenceNode is an instance of InferenceNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating InferenceNode:', error) + assert(false, 'Error creating InferenceNode') + } +}); diff --git a/amlip_swig_js/test/api/nodes/main_node_test.js b/amlip_swig_js/test/api/nodes/main_node_test.js new file mode 100644 index 00000000..4f8eb61c --- /dev/null +++ b/amlip_swig_js/test/api/nodes/main_node_test.js @@ -0,0 +1,50 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an MainNode does not give any error. +test('Create MainNode', () => { + console.log('TEST: Create MainNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const mainNode = new amlip_swig_js.MainNode('main_node_test'); + // If the MainNode is created without throwing an error, the test passes + assert(true, 'MainNode is created without errors') + console.log('MainNode is created without errors') + assert(mainNode instanceof amlip_swig_js.MainNode, 'mainNode is an instance of MainNode') + console.log('mainNode is an instance of MainNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating MainNode:', error) + assert(false, 'Error creating MainNode') + } +}); + +test('Create MainNode with domain', () => { + console.log('TEST: Create MainNode with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const mainNode = new amlip_swig_js.MainNode('main_node_test', 166); + // If the MainNode is created without throwing an error, the test passes + assert(true, 'MainNode is created with domain without errors') + console.log('MainNode is created with domain without errors') + assert(mainNode instanceof amlip_swig_js.MainNode, 'mainNode is an instance of MainNode') + console.log('mainNode is an instance of MainNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating MainNode with domain:', error) + assert(false, 'Error creating MainNode with domain') + } +}); diff --git a/amlip_swig_js/test/api/nodes/modelmanagerreceiver_node_test.js b/amlip_swig_js/test/api/nodes/modelmanagerreceiver_node_test.js new file mode 100644 index 00000000..74467a44 --- /dev/null +++ b/amlip_swig_js/test/api/nodes/modelmanagerreceiver_node_test.js @@ -0,0 +1,56 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an ModelManagerReceiverNode does not give any error. +test('Create ModelManagerReceiverNode', () => { + console.log('TEST: Create ModelManagerReceiverNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const id = new amlip_swig_js.AmlipIdDataType('modelmanagerreceiver_node_test') + class ModelRequestDataType extends amlip_swig_js.GenericDataType {} + const data = new ModelRequestDataType('modelRequestDataType_test'); + const modelmanagerreceiverNode = new amlip_swig_js.ModelManagerReceiverNodeJS(id, data); + // If the ModelManagerReceiverNode is created without throwing an error, the test passes + assert(true, 'ModelManagerReceiverNode is created without errors') + console.log('ModelManagerReceiverNode is created without errors') + assert(modelmanagerreceiverNode instanceof amlip_swig_js.ModelManagerReceiverNodeJS, 'modelmanagerreceiverNode is an instance of ModelManagerReceiverNodeJS') + console.log('modelmanagerreceiverNode is an instance of ModelManagerReceiverNodeJS') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelManagerReceiverNode:', error) + assert(false, 'Error creating ModelManagerReceiverNode') + } +}); + +test('Create ModelManagerReceiverNode with domain', () => { + console.log('TEST: Create ModelManagerReceiverNode with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const id = new amlip_swig_js.AmlipIdDataType('modelmanagerreceiver_node_test') + class ModelRequestDataType extends amlip_swig_js.GenericDataType {} + const data = new ModelRequestDataType('modelRequestDataType_test'); + const modelmanagerreceiverNode = new amlip_swig_js.ModelManagerReceiverNodeJS(id, data, 166); + // If the ModelManagerReceiverNode is created without throwing an error, the test passes + assert(true, 'ModelManagerReceiverNode is created with domain without errors') + console.log('ModelManagerReceiverNode is created with domain without errors') + assert(modelmanagerreceiverNode instanceof amlip_swig_js.ModelManagerReceiverNodeJS, 'modelmanagerreceiverNode is an instance of ModelManagerReceiverNodeJS') + console.log('modelmanagerreceiverNode is an instance of ModelManagerReceiverNodeJS') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelManagerReceiverNode with domain:', error) + assert(false, 'Error creating ModelManagerReceiverNode with domain') + } +}); diff --git a/amlip_swig_js/test/api/nodes/modelmanagersender_node_test.js b/amlip_swig_js/test/api/nodes/modelmanagersender_node_test.js new file mode 100644 index 00000000..587233ec --- /dev/null +++ b/amlip_swig_js/test/api/nodes/modelmanagersender_node_test.js @@ -0,0 +1,52 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an ModelManagerSenderNode does not give any error. +test('Create ModelManagerSenderNode', () => { + console.log('TEST: Create ModelManagerSenderNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const id = new amlip_swig_js.AmlipIdDataType('modelmanagersender_node_test') + const modelmanagersenderNode = new amlip_swig_js.ModelManagerSenderNodeJS(id); + // If the ModelManagerSenderNode is created without throwing an error, the test passes + assert(true, 'ModelManagerSenderNode is created without errors') + console.log('ModelManagerSenderNode is created without errors') + assert(modelmanagersenderNode instanceof amlip_swig_js.ModelManagerSenderNodeJS, 'modelmanagersenderNode is an instance of ModelManagerSenderNodeJS') + console.log('modelmanagersenderNode is an instance of ModelManagerSenderNodeJS') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelManagerSenderNode:', error) + assert(false, 'Error creating ModelManagerSenderNode') + } +}); + +test('Create ModelManagerSenderNode with domain', () => { + console.log('TEST: Create ModelManagerSenderNode with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const id = new amlip_swig_js.AmlipIdDataType('modelmanagersender_node_test') + const modelmanagersenderNode = new amlip_swig_js.ModelManagerSenderNodeJS(id, 166); + // If the ModelManagerSenderNode is created without throwing an error, the test passes + assert(true, 'ModelManagerSenderNode is created with domain without errors') + console.log('ModelManagerSenderNode is created with domain without errors') + assert(modelmanagersenderNode instanceof amlip_swig_js.ModelManagerSenderNodeJS, 'modelmanagersenderNode is an instance of ModelManagerSenderNodeJS') + console.log('modelmanagersenderNode is an instance of ModelManagerSenderNodeJS') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelManagerSenderNode with domain:', error) + assert(false, 'Error creating ModelManagerSenderNode with domain') + } +}); diff --git a/amlip_swig_js/test/api/nodes/status_node_test.js b/amlip_swig_js/test/api/nodes/status_node_test.js new file mode 100644 index 00000000..5c968946 --- /dev/null +++ b/amlip_swig_js/test/api/nodes/status_node_test.js @@ -0,0 +1,50 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an StatusNode does not give any error. +test('Create StatusNode', () => { + console.log('TEST: Create StatusNode') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const statusNode = new amlip_swig_js.StatusNode('status_node_test'); + // If the StatusNode is created without throwing an error, the test passes + assert(true, 'StatusNode is created without errors') + console.log('StatusNode is created without errors') + assert(statusNode instanceof amlip_swig_js.StatusNode, 'statusNode is an instance of StatusNode') + console.log('statusNode is an instance of StatusNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating StatusNode:', error) + assert(false, 'Error creating StatusNode') + } +}); + +test('Create StatusNode with domain', () => { + console.log('TEST: Create StatusNode with domain') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const statusNode = new amlip_swig_js.StatusNode('status_node_test', 166); + // If the StatusNode is created without throwing an error, the test passes + assert(true, 'StatusNode is created with domain without errors') + console.log('StatusNode is created with domain without errors') + assert(statusNode instanceof amlip_swig_js.StatusNode, 'statusNode is an instance of StatusNode') + console.log('statusNode is an instance of StatusNode') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating StatusNode with domain:', error) + assert(false, 'Error creating StatusNode with domain') + } +}); diff --git a/amlip_swig_js/test/api/types/create_types_test.js b/amlip_swig_js/test/api/types/create_types_test.js new file mode 100644 index 00000000..760f4d1e --- /dev/null +++ b/amlip_swig_js/test/api/types/create_types_test.js @@ -0,0 +1,398 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const assert = require('assert'); + +// Test that create an AmlipIdDataType does not give any error. +test('Create AmlipIdDataType', () => { + console.log('TEST: Create AmlipIdDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const amlipIdDataType = new amlip_swig_js.AmlipIdDataType(); + // If the AmlipIdDataType is created without throwing an error, the test passes + assert(true, 'AmlipIdDataType is created without errors') + console.log('AmlipIdDataType is created without errors') + assert(amlipIdDataType instanceof amlip_swig_js.AmlipIdDataType, 'amlipIdDataType is an instance of AmlipIdDataType') + console.log('amlipIdDataType is an instance of AmlipIdDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AmlipIdDataType:', error); + assert(false, 'Error creating AmlipIdDataType') + } +}); + +test('Create AmlipIdDataType with name', () => { + console.log('TEST: Create AmlipIdDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const amlipIdDataType = new amlip_swig_js.AmlipIdDataType('amlipIdDataType_test'); + // If the AmlipIdDataType is created without throwing an error, the test passes + assert(true, 'AmlipIdDataType is created with name without errors') + console.log('AmlipIdDataType is created with name without errors') + assert(amlipIdDataType instanceof amlip_swig_js.AmlipIdDataType, 'amlipIdDataType is an instance of AmlipIdDataType') + console.log('amlipIdDataType is an instance of AmlipIdDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating AmlipIdDataType with name:', error); + assert(false, 'Error creating AmlipIdDataType with name') + } +}); + +// Test that create an GenericDataType does not give any error. +test('Create GenericDataType', () => { + console.log('TEST: Create GenericDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const genericDataType = new amlip_swig_js.GenericDataType(); + // If the GenericDataType is created without throwing an error, the test passes + assert(true, 'GenericDataType is created without errors') + console.log('GenericDataType is created without errors') + assert(genericDataType instanceof amlip_swig_js.GenericDataType, 'genericDataType is an instance of GenericDataType') + console.log('genericDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating GenericDataType:', error); + assert(false, 'Error creating GenericDataType') + } +}); + +test('Create GenericDataType with name', () => { + console.log('TEST: Create GenericDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const genericDataType = new amlip_swig_js.GenericDataType('genericDataType_test'); + // If the GenericDataType is created without throwing an error, the test passes + assert(true, 'GenericDataType is created with name without errors') + console.log('GenericDataType is created with name without errors') + assert(genericDataType instanceof amlip_swig_js.GenericDataType, 'genericDataType is an instance of GenericDataType') + console.log('genericDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating GenericDataType with name:', error); + assert(false, 'Error creating GenericDataType with name') + } +}); + +// Test that create an StatusDataType does not give any error. +test('Create StatusDataType', () => { + console.log('TEST: Create StatusDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const statusDataType = new amlip_swig_js.StatusDataType(); + // If the statusDataType is created without throwing an error, the test passes + assert(true, 'StatusDataType is created without errors') + console.log('StatusDataType is created without errors') + assert(statusDataType instanceof amlip_swig_js.StatusDataType, 'statusDataType is an instance of StatusDataType') + console.log('statusDataType is an instance of StatusDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating StatusDataType:', error); + assert(false, 'Error creating StatusDataType') + } +}); + +// Test that create an GenericDataType does not give any error. +test('Create StatusDataType with id, node_kind and state', () => { + console.log('TEST: Create StatusDataType with id, node_kind and state') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const id = new amlip_swig_js.AmlipIdDataType(); + const node_kind = amlip_swig_js.NodeKind_undetermined; + const state = amlip_swig_js.StateKind_unknown; + const statusDataType = new amlip_swig_js.StatusDataType(id, node_kind, state); + // If the statusDataType is created without throwing an error, the test passes + assert(true, 'StatusDataType is created with id, node_kind and state without errors') + console.log('StatusDataType is created with id, node_kind and state without errors') + assert(statusDataType instanceof amlip_swig_js.StatusDataType, 'statusDataType is an instance of StatusDataType') + console.log('statusDataType is an instance of StatusDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating StatusDataType with id, node_kind and state:', error); + assert(false, 'Error creating StatusDataType with id, node_kind and state') + } +}); + +// Test that create a JobDataType does not give any error. +test('Create JobDataType', () => { + console.log('TEST: Create JobDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class JobDataType extends amlip_swig_js.GenericDataType {} + const jobDataType = new JobDataType(); + // If the jobDataType is created without throwing an error, the test passes + assert(true, 'JobDataType is created without errors') + console.log('JobDataType is created without errors') + assert(jobDataType instanceof amlip_swig_js.GenericDataType, 'jobDataType is an instance of GenericDataType') + console.log('jobDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating JobDataType:', error); + assert(false, 'Error creating JobDataType') + } +}); + +test('Create JobDataType with name', () => { + console.log('TEST: Create JobDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class JobDataType extends amlip_swig_js.GenericDataType {} + const jobDataType = new JobDataType('jobDataType_test'); + // If the jobDataType is created without throwing an error, the test passes + assert(true, 'JobDataType is created with name without errors') + console.log('JobDataType is created with name without errors') + assert(jobDataType instanceof amlip_swig_js.GenericDataType, 'jobDataType is an instance of GenericDataType') + console.log('jobDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating JobDataType with name:', error); + assert(false, 'Error creating JobDataType with name') + } +}); + +// Test that create a JobSolutionDataType does not give any error. +test('Create JobSolutionDataType', () => { + console.log('TEST: Create JobSolutionDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class JobSolutionDataType extends amlip_swig_js.GenericDataType {} + const jobSolutionDataType = new JobSolutionDataType(); + // If the jobSolutionDataType is created without throwing an error, the test passes + assert(true, 'JobSolutionDataType is created without errors') + console.log('JobSolutionDataType is created without errors') + assert(jobSolutionDataType instanceof amlip_swig_js.GenericDataType, 'jobSolutionDataType is an instance of GenericDataType') + console.log('jobSolutionDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating JobSolutionDataType:', error); + assert(false, 'Error creating JobSolutionDataType') + } +}); + +test('Create JobSolutionDataType', () => { + console.log('TEST: Create JobSolutionDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class JobSolutionDataType extends amlip_swig_js.GenericDataType {} + const jobSolutionDataType = new JobSolutionDataType('jobSolutionDataType_test'); + // If the jobSolutionDataType is created without throwing an error, the test passes + assert(true, 'JobSolutionDataType is created with name without errors') + console.log('JobSolutionDataType is created with name without errors') + assert(jobSolutionDataType instanceof amlip_swig_js.GenericDataType, 'jobSolutionDataType is an instance of GenericDataType') + console.log('jobSolutionDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating JobSolutionDataType with name:', error); + assert(false, 'Error creating JobSolutionDataType with name') + } +}); + +// Test that create an InferenceDataType does not give any error. +test('Create InferenceDataType', () => { + console.log('TEST: Create InferenceDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class InferenceDataType extends amlip_swig_js.GenericDataType {} + const inferenceDataType = new InferenceDataType(); + // If the inferenceDataType is created without throwing an error, the test passes + assert(true, 'InferenceDataType is created without errors') + console.log('InferenceDataType is created without errors') + assert(inferenceDataType instanceof amlip_swig_js.GenericDataType, 'inferenceDataType is an instance of GenericDataType') + console.log('inferenceDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating InferenceDataType:', error); + assert(false, 'Error creating InferenceDataType') + } +}); + +test('Create InferenceDataType with name', () => { + console.log('TEST: Create InferenceDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class InferenceDataType extends amlip_swig_js.GenericDataType {} + const inferenceDataType = new InferenceDataType('inferenceDataType_test'); + // If the inferenceDataType is created without throwing an error, the test passes + assert(true, 'InferenceDataType is created with name without errors') + console.log('InferenceDataType is created with name without errors') + assert(inferenceDataType instanceof amlip_swig_js.GenericDataType, 'inferenceDataType is an instance of GenericDataType') + console.log('inferenceDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating InferenceDataType with name:', error); + assert(false, 'Error creating InferenceDataType with name') + } +}); + +// Test that create an InferenceSolutionDataType does not give any error. +test('Create InferenceSolutionDataType', () => { + console.log('TEST: Create InferenceSolutionDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class InferenceSolutionDataType extends amlip_swig_js.GenericDataType {} + const inferenceSolutionDataType = new InferenceSolutionDataType(); + // If the inferenceSolutionDataType is created without throwing an error, the test passes + assert(true, 'InferenceSolutionDataType is created without errors') + console.log('InferenceSolutionDataType is created without errors') + assert(inferenceSolutionDataType instanceof amlip_swig_js.GenericDataType, 'inferenceSolutionDataType is an instance of GenericDataType') + console.log('inferenceSolutionDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating InferenceSolutionDataType:', error); + assert(false, 'Error creating InferenceSolutionDataType') + } +}); + +test('Create InferenceSolutionDataType with name', () => { + console.log('TEST: Create InferenceSolutionDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class InferenceSolutionDataType extends amlip_swig_js.GenericDataType {} + const inferenceSolutionDataType = new InferenceSolutionDataType('inferenceSolutionDataType_test'); + // If the inferenceSolutionDataType is created without throwing an error, the test passes + assert(true, 'InferenceSolutionDataType is created with name without errors') + console.log('InferenceSolutionDataType is created with name without errors') + assert(inferenceSolutionDataType instanceof amlip_swig_js.GenericDataType, 'inferenceSolutionDataType is an instance of GenericDataType') + console.log('inferenceSolutionDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating InferenceSolutionDataType with name:', error); + assert(false, 'Error creating InferenceSolutionDataType with name') + } +}); + +// Test that create a ModelRequestDataType does not give any error. +test('Create ModelRequestDataType', () => { + console.log('TEST: Create ModelRequestDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class ModelRequestDataType extends amlip_swig_js.GenericDataType {} + const modelRequestDataType = new ModelRequestDataType(); + // If the modelRequestDataType is created without throwing an error, the test passes + assert(true, 'ModelRequestDataType is created without errors') + console.log('ModelRequestDataType is created without errors') + assert(modelRequestDataType instanceof amlip_swig_js.GenericDataType, 'modelRequestDataType is an instance of GenericDataType') + console.log('modelRequestDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelRequestDataType:', error); + assert(false, 'Error creating ModelRequestDataType') + } +}); + +test('Create ModelRequestDataType with name', () => { + console.log('TEST: Create ModelRequestDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class ModelRequestDataType extends amlip_swig_js.GenericDataType {} + const modelRequestDataType = new ModelRequestDataType('modelRequestDataType_test'); + // If the modelRequestDataType is created without throwing an error, the test passes + assert(true, 'ModelRequestDataType is created with name without errors') + console.log('ModelRequestDataType is created with name without errors') + assert(modelRequestDataType instanceof amlip_swig_js.GenericDataType, 'modelRequestDataType is an instance of GenericDataType') + console.log('modelRequestDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelRequestDataType with name:', error); + assert(false, 'Error creating ModelRequestDataType with name') + } +}); + +// Test that create a ModelReplyDataType does not give any error. +test('Create ModelReplyDataType', () => { + console.log('TEST: Create ModelReplyDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class ModelReplyDataType extends amlip_swig_js.GenericDataType {} + const modelReplyDataType = new ModelReplyDataType(); + // If the modelReplyDataType is created without throwing an error, the test passes + assert(true, 'ModelReplyDataType is created without errors') + console.log('ModelReplyDataType is created without errors') + assert(modelReplyDataType instanceof amlip_swig_js.GenericDataType, 'modelReplyDataType is an instance of GenericDataType') + console.log('modelReplyDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelReplyDataType:', error); + assert(false, 'Error creating ModelReplyDataType') + } +}); + +test('Create ModelReplyDataType with name', () => { + console.log('TEST: Create ModelReplyDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + class ModelReplyDataType extends amlip_swig_js.GenericDataType {} + const modelReplyDataType = new ModelReplyDataType('modelReplyDataType_test'); + // If the modelReplyDataType is created without throwing an error, the test passes + assert(true, 'ModelReplyDataType is created with name without errors') + console.log('ModelReplyDataType is created with name without errors') + assert(modelReplyDataType instanceof amlip_swig_js.GenericDataType, 'modelReplyDataType is an instance of GenericDataType') + console.log('modelReplyDataType is an instance of GenericDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelReplyDataType with name:', error); + assert(false, 'Error creating ModelReplyDataType with name') + } +}); + +// Test that create a ModelStatisticsDataType does not give any error. +test('Create ModelStatisticsDataType', () => { + console.log('TEST: Create ModelStatisticsDataType') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const modelStatisticsDataType = new amlip_swig_js.ModelStatisticsDataType(); + // If the modelStatisticsDataType is created without throwing an error, the test passes + assert(true, 'ModelStatisticsDataType is created without errors') + console.log('ModelStatisticsDataType is created without errors') + assert(modelStatisticsDataType instanceof amlip_swig_js.ModelStatisticsDataType, 'modelStatisticsDataType is an instance of ModelStatisticsDataType') + console.log('modelStatisticsDataType is an instance of ModelStatisticsDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelStatisticsDataType:', error); + assert(false, 'Error creating ModelStatisticsDataType') + } +}); + +test('Create ModelStatisticsDataType with name', () => { + console.log('TEST: Create ModelStatisticsDataType with name') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const modelStatisticsDataType = new amlip_swig_js.ModelStatisticsDataType('modelStatisticsDataType_test'); + // If the modelStatisticsDataType is created without throwing an error, the test passes + assert(true, 'ModelStatisticsDataType is created with name without errors') + console.log('ModelStatisticsDataType is created with name without errors') + assert(modelStatisticsDataType instanceof amlip_swig_js.ModelStatisticsDataType, 'modelStatisticsDataType is an instance of ModelStatisticsDataType') + console.log('modelStatisticsDataType is an instance of ModelStatisticsDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelStatisticsDataType with name:', error); + assert(false, 'Error creating ModelStatisticsDataType with name') + } +}); + +test('Create ModelStatisticsDataType with name and bytes', () => { + console.log('TEST: Create ModelStatisticsDataType with name and bytes') + try { + const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + const modelStatisticsDataType = new amlip_swig_js.ModelStatisticsDataType('modelStatisticsDataType_test', 'hello world'); + // If the modelStatisticsDataType is created without throwing an error, the test passes + assert(true, 'ModelStatisticsDataType is created with name and bytes without errors') + console.log('ModelStatisticsDataType is created with name and bytes without errors') + assert(modelStatisticsDataType instanceof amlip_swig_js.ModelStatisticsDataType, 'modelStatisticsDataType is an instance of ModelStatisticsDataType') + console.log('modelStatisticsDataType is an instance of ModelStatisticsDataType') + } catch (error) { + // If an error occurs during creation, fail the test and log the error + console.error('Error creating ModelStatisticsDataType with name and bytes:', error); + assert(false, 'Error creating ModelStatisticsDataType with name and bytes') + } +}); diff --git a/amlip_swig_js/test/manual/async_computing.js b/amlip_swig_js/test/manual/async_computing.js new file mode 100644 index 00000000..e7b3100e --- /dev/null +++ b/amlip_swig_js/test/manual/async_computing.js @@ -0,0 +1,39 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const express = require('express'); +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +const app = express(); + +const server = app.listen(() => { + // Do nothing +}); + +console.log('Starting Manual Test Async Computing Node JS execution. Creating Node...') +const replier = new amlip_swig_js.JobReplierJS() +const async_computing_node = new amlip_swig_js.AsyncComputingNodeJS('async_computing_node_test', replier); +console.log('Node created.') + +console.log('Already processing jobs. Waiting SIGINT (C^)...') +async_computing_node.run() + +process.once('SIGINT', () => { + console.log('Received SIGINT. '); + async_computing_node.stop() + server.close(() => { + console.log('Finishing Manual Test Async Computing Node JS execution.'); + process.exit(0); + }); +}); diff --git a/amlip_swig_js/test/manual/async_edge.js b/amlip_swig_js/test/manual/async_edge.js new file mode 100644 index 00000000..3e34505d --- /dev/null +++ b/amlip_swig_js/test/manual/async_edge.js @@ -0,0 +1,47 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function main() { + + console.log('Starting Manual Test Async Edge Node JS execution. Creating Node...') + const listener = new amlip_swig_js.InferenceSolutionListenerJS() + + const async_edge_node = new amlip_swig_js.AsyncEdgeNodeJS('async_edge_node_test', listener) + console.log('Node created. Creating inference...') + + class InferenceDataType extends amlip_swig_js.GenericDataType {} + data_str = '' + const inference_data = new InferenceDataType(data_str) + console.log('Inference data is: ' + inference_data.to_string()) + + console.log('Sending request...') + const task_id = async_edge_node.request_inference(inference_data) + console.log('Request sent with task id: ' + task_id + ' . Waiting for inference...') + + while (amlip_swig_js.block_edge_) { + console.log('Waiting for inference...') + await sleep(1000) + } + + console.log('Finishing Manual Test Async Edge Node JS execution.') +} + +main(); diff --git a/amlip_swig_js/test/manual/async_inference.js b/amlip_swig_js/test/manual/async_inference.js new file mode 100644 index 00000000..e17ae625 --- /dev/null +++ b/amlip_swig_js/test/manual/async_inference.js @@ -0,0 +1,39 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const express = require('express'); +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +const app = express(); + +const server = app.listen(() => { + // Do nothing +}); + +console.log('Starting Manual Test Async Inference Node JS execution. Creating Node...') +const replier = new amlip_swig_js.InferenceReplierJS() +const async_inference_node = new amlip_swig_js.AsyncInferenceNodeJS('async_inference_node_test', replier); +console.log('Node created.') + +console.log('Already processing inferences. Waiting SIGINT (C^)...') +async_inference_node.run() + +process.once('SIGINT', () => { + console.log('Received SIGINT. '); + async_inference_node.stop() + server.close(() => { + console.log('Finishing Manual Test Async Inference Node JS execution.'); + process.exit(0); + }); +}); diff --git a/amlip_swig_js/test/manual/async_main.js b/amlip_swig_js/test/manual/async_main.js new file mode 100644 index 00000000..ec3482dd --- /dev/null +++ b/amlip_swig_js/test/manual/async_main.js @@ -0,0 +1,47 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function main() { + + console.log('Starting Manual Test Async Main Node JS execution. Creating Node...') + const listener = new amlip_swig_js.SolutionListenerJS() + + const async_main_node = new amlip_swig_js.AsyncMainNodeJS('async_main_node_test', listener) + console.log('Node created. Creating job...') + + class JobDataType extends amlip_swig_js.GenericDataType {} + data_str = '' + const job_data = new JobDataType(data_str) + console.log('Job data is: ' + job_data.to_string()) + + console.log('Sending request...') + const task_id = async_main_node.request_job_solution(job_data) + console.log('Request sent with task id: ' + task_id + ' . Waiting for solution...') + + while (amlip_swig_js.block_main_) { + console.log('Waiting for solution...') + await sleep(1000) + } + + console.log('Finishing Manual Test Async Main Node JS execution.') +} + +main(); diff --git a/amlip_swig_js/test/manual/computing.js b/amlip_swig_js/test/manual/computing.js new file mode 100644 index 00000000..52a28f0c --- /dev/null +++ b/amlip_swig_js/test/manual/computing.js @@ -0,0 +1,30 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +console.log('Starting Manual Test Computing Node JS execution. Creating Node...') + +const computing_node = new amlip_swig_js.ComputingNode('computing_node_test'); +console.log('Node created.') + +var job_listener = new amlip_swig_js.JobListenerJS() +console.log('JobListenerJS created.') + +console.log('Processing job...') +computing_node.process_job(job_listener) + +console.log('Solution sent to client.') + +console.log('Finishing Manual Test Computing Node JS execution.') diff --git a/amlip_swig_js/test/manual/edge.js b/amlip_swig_js/test/manual/edge.js new file mode 100644 index 00000000..623ee9c9 --- /dev/null +++ b/amlip_swig_js/test/manual/edge.js @@ -0,0 +1,32 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +console.log('Starting Manual Test Edge Node JS execution. Creating Node...') +const edge_node = new amlip_swig_js.EdgeNode('edge_node_test'); +console.log('Node created. Creating inference...') + +class InferenceDataType extends amlip_swig_js.GenericDataType {} +inference_data = new InferenceDataType('HELLO WORLD') +console.log('Inference data is: ' + inference_data.to_string()) + +console.log('Sending request...') +const solution = edge_node.request_inference(inference_data) + +console.log('Solution receiced from server. Deserializing to string...') +console.log('Solution deserialized is: ' + solution.to_string()) + +console.log('Finishing Manual Test Edge Node JS execution.') diff --git a/amlip_swig_js/test/manual/inference.js b/amlip_swig_js/test/manual/inference.js new file mode 100644 index 00000000..3e5f93c2 --- /dev/null +++ b/amlip_swig_js/test/manual/inference.js @@ -0,0 +1,30 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +console.log('Starting Manual Test Inference Node JS execution. Creating Node...') + +const inference_node = new amlip_swig_js.InferenceNode('inference_node_test'); +console.log('Node created.') + +var inference_listener = new amlip_swig_js.InferenceListenerJS() +console.log('InferenceListenerJS created.') + +console.log('Processing inference...') +const client_id = inference_node.process_inference(inference_listener) + +console.log('Solution sent to client ' + client_id + '.') + +console.log('Finishing Manual Test Inference Node JS execution.') diff --git a/amlip_swig_js/test/manual/main.js b/amlip_swig_js/test/manual/main.js new file mode 100644 index 00000000..30d91cf7 --- /dev/null +++ b/amlip_swig_js/test/manual/main.js @@ -0,0 +1,32 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +console.log('Starting Manual Test Main Node JS execution. Creating Node...') +const main_node = new amlip_swig_js.MainNode('main_node_test'); +console.log('Node created.') + +class JobDataType extends amlip_swig_js.GenericDataType {} +job_data = new JobDataType('HELLO WORLD') +console.log('Job data is: ' + job_data.to_string()) + +console.log('Sending request...') +const solution = main_node.request_job_solution(job_data) + +console.log('Solution receiced from server. Deserializing to string...') +console.log('Solution deserialized is: ' + solution.to_string()) + +console.log('Finishing Manual Test Main Node JS execution.') diff --git a/amlip_swig_js/test/manual/model_manager_receiver.js b/amlip_swig_js/test/manual/model_manager_receiver.js new file mode 100644 index 00000000..367b8257 --- /dev/null +++ b/amlip_swig_js/test/manual/model_manager_receiver.js @@ -0,0 +1,46 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function main() { + + console.log('Starting Manual Test ModelManagerReceiver Node JS execution. Creating Node...') + const id = new amlip_swig_js.AmlipIdDataType('modelmanagerreceiver_node_test') + class ModelRequestDataType extends amlip_swig_js.GenericDataType {} + const data = new ModelRequestDataType('modelRequestDataType_test'); + const model_manager_receiver = new amlip_swig_js.ModelManagerReceiverNodeJS(id, data, 166); + console.log('Node created. Already processing models...') + + const listener = new amlip_swig_js.ModelListenerJS() + + model_manager_receiver.start(listener) + + while (amlip_swig_js.block_modelmanagerreceiver_) { + console.log('Waiting...') + await sleep(1000) + } + + model_manager_receiver.stop() + + console.log('Finishing Manual Test ModelManagerReceiver Node JS execution.') + +} + +main(); diff --git a/amlip_swig_js/test/manual/model_manager_sender.js b/amlip_swig_js/test/manual/model_manager_sender.js new file mode 100644 index 00000000..d17ca229 --- /dev/null +++ b/amlip_swig_js/test/manual/model_manager_sender.js @@ -0,0 +1,50 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function main() { + + console.log('Starting Manual Test ModelManagerSender Node JS execution. Creating Node...') + const id = new amlip_swig_js.AmlipIdDataType('modelmanagersender_node_test') + const model_sender_node = new amlip_swig_js.ModelManagerSenderNodeJS(id, 166); console.log('Node created. Already processing models...') + + model_sender_node.publish_statistics( + 'ModelManagerSenderStatistics', + 'hello world!' + ) + + console.log('Statistics published.') + + const listener = new amlip_swig_js.ModelReplierJS() + + model_sender_node.start(listener) + + while (amlip_swig_js.block_modelmanagersender_) { + console.log('Waiting for request...') + await sleep(1000) + } + + model_sender_node.stop() + + console.log('Finishing Manual Test ModelManagerSender Node JS execution.') + +} + +main(); diff --git a/amlip_swig_js/test/manual/status.js b/amlip_swig_js/test/manual/status.js new file mode 100644 index 00000000..e81a0fc6 --- /dev/null +++ b/amlip_swig_js/test/manual/status.js @@ -0,0 +1,41 @@ +// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const express = require('express'); +const amlip_swig_js = require('/home/irenebm/eprosima/annapurna/AML-IP-ws/src/amlip/amlip_swig_js/build/Release/amlip_swig_js.node'); + +const app = express(); + +const server = app.listen(() => { + // Do nothing +}); + +console.log('Starting Manual Test Status Node JS execution. Creating Node...') +const status_node = new amlip_swig_js.StatusNode('status_node_test'); +console.log('Node created.') + +const listener = new amlip_swig_js.StatusListenerJS() + +console.log('Listener created. Processing data asynchronously...') +status_node.process_status_async(listener) + +console.log('Already processing status data. Waiting SIGINT (C^)...') + +process.once('SIGINT', () => { + console.log('Received SIGINT. '); + server.close(() => { + console.log('Finishing Manual Test Status Node JS execution.'); + process.exit(0); + }); +}); diff --git a/thirdparty/node/node.h b/thirdparty/node/node.h new file mode 100644 index 00000000..31b7eb6d --- /dev/null +++ b/thirdparty/node/node.h @@ -0,0 +1,834 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +#ifndef SRC_NODE_H_ +#define SRC_NODE_H_ + +#ifdef _WIN32 +# ifndef BUILDING_NODE_EXTENSION +# define NODE_EXTERN __declspec(dllexport) +# else +# define NODE_EXTERN __declspec(dllimport) +# endif +#else +# define NODE_EXTERN __attribute__((visibility("default"))) +#endif + +#ifdef BUILDING_NODE_EXTENSION +# undef BUILDING_V8_SHARED +# undef BUILDING_UV_SHARED +# define USING_V8_SHARED 1 +# define USING_UV_SHARED 1 +#endif + +// This should be defined in make system. +// See issue https://github.com/nodejs/node-v0.x-archive/issues/1236 +#if defined(__MINGW32__) || defined(_MSC_VER) +#ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0600 // Windows Server 2008 +#endif + +#ifndef NOMINMAX +# define NOMINMAX +#endif + +#endif + +#if defined(_MSC_VER) +#define PATH_MAX MAX_PATH +#endif + +#ifdef _WIN32 +# define SIGKILL 9 +#endif + +#include "v8.h" // NOLINT(build/include_order) +#include "v8-platform.h" // NOLINT(build/include_order) +#include "node_version.h" // NODE_MODULE_VERSION + +#include + +#define NODE_MAKE_VERSION(major, minor, patch) \ + ((major) * 0x1000 + (minor) * 0x100 + (patch)) + +#ifdef __clang__ +# define NODE_CLANG_AT_LEAST(major, minor, patch) \ + (NODE_MAKE_VERSION(major, minor, patch) <= \ + NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__)) +#else +# define NODE_CLANG_AT_LEAST(major, minor, patch) (0) +#endif + +#ifdef __GNUC__ +# define NODE_GNUC_AT_LEAST(major, minor, patch) \ + (NODE_MAKE_VERSION(major, minor, patch) <= \ + NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)) +#else +# define NODE_GNUC_AT_LEAST(major, minor, patch) (0) +#endif + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +# define NODE_DEPRECATED(message, declarator) declarator +#else // NODE_WANT_INTERNALS +# if NODE_CLANG_AT_LEAST(2, 9, 0) || NODE_GNUC_AT_LEAST(4, 5, 0) +# define NODE_DEPRECATED(message, declarator) \ + __attribute__((deprecated(message))) declarator +# elif defined(_MSC_VER) +# define NODE_DEPRECATED(message, declarator) \ + __declspec(deprecated) declarator +# else +# define NODE_DEPRECATED(message, declarator) declarator +# endif +#endif + +// Forward-declare libuv loop +struct uv_loop_s; + +// Forward-declare these functions now to stop MSVS from becoming +// terminally confused when it's done in node_internals.h +namespace node { + +namespace tracing { + +class TracingController; + +} + +NODE_EXTERN v8::Local ErrnoException(v8::Isolate* isolate, + int errorno, + const char* syscall = nullptr, + const char* message = nullptr, + const char* path = nullptr); +NODE_EXTERN v8::Local UVException(v8::Isolate* isolate, + int errorno, + const char* syscall = nullptr, + const char* message = nullptr, + const char* path = nullptr, + const char* dest = nullptr); + +NODE_DEPRECATED("Use ErrnoException(isolate, ...)", + inline v8::Local ErrnoException( + int errorno, + const char* syscall = nullptr, + const char* message = nullptr, + const char* path = nullptr) { + return ErrnoException(v8::Isolate::GetCurrent(), + errorno, + syscall, + message, + path); +}) + +NODE_DEPRECATED("Use UVException(isolate, ...)", + inline v8::Local UVException(int errorno, + const char* syscall = nullptr, + const char* message = nullptr, + const char* path = nullptr) { + return UVException(v8::Isolate::GetCurrent(), + errorno, + syscall, + message, + path); +}) + +/* + * These methods need to be called in a HandleScope. + * + * It is preferred that you use the `MakeCallback` overloads taking + * `async_context` arguments. + */ + +NODE_DEPRECATED("Use MakeCallback(..., async_context)", + NODE_EXTERN v8::Local MakeCallback( + v8::Isolate* isolate, + v8::Local recv, + const char* method, + int argc, + v8::Local* argv)); +NODE_DEPRECATED("Use MakeCallback(..., async_context)", + NODE_EXTERN v8::Local MakeCallback( + v8::Isolate* isolate, + v8::Local recv, + v8::Local symbol, + int argc, + v8::Local* argv)); +NODE_DEPRECATED("Use MakeCallback(..., async_context)", + NODE_EXTERN v8::Local MakeCallback( + v8::Isolate* isolate, + v8::Local recv, + v8::Local callback, + int argc, + v8::Local* argv)); + +} // namespace node + +#include +#include + +#ifndef NODE_STRINGIFY +#define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) +#define NODE_STRINGIFY_HELPER(n) #n +#endif + +#ifdef _WIN32 +#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED) +typedef intptr_t ssize_t; +# define _SSIZE_T_ +# define _SSIZE_T_DEFINED +#endif +#else // !_WIN32 +# include // size_t, ssize_t +#endif // _WIN32 + + +namespace node { + +class IsolateData; +class Environment; + +// TODO(addaleax): Officially deprecate this and replace it with something +// better suited for a public embedder API. +NODE_EXTERN int Start(int argc, char* argv[]); + +// Tear down Node.js while it is running (there are active handles +// in the loop and / or actively executing JavaScript code). +NODE_EXTERN int Stop(Environment* env); + +// TODO(addaleax): Officially deprecate this and replace it with something +// better suited for a public embedder API. +NODE_EXTERN void Init(int* argc, + const char** argv, + int* exec_argc, + const char*** exec_argv); + +class NodeArrayBufferAllocator; + +// An ArrayBuffer::Allocator class with some Node.js-specific tweaks. If you do +// not have to use another allocator, using this class is recommended: +// - It supports Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() with +// uninitialized memory. +// - It supports transferring, rather than copying, ArrayBuffers when using +// MessagePorts. +class NODE_EXTERN ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { + public: + // If `always_debug` is true, create an ArrayBuffer::Allocator instance + // that performs additional integrity checks (e.g. make sure that only memory + // that was allocated by the it is also freed by it). + // This can also be set using the --debug-arraybuffer-allocations flag. + static std::unique_ptr Create( + bool always_debug = false); + + private: + virtual NodeArrayBufferAllocator* GetImpl() = 0; + + friend class IsolateData; +}; + +// Legacy equivalents for ArrayBufferAllocator::Create(). +NODE_EXTERN ArrayBufferAllocator* CreateArrayBufferAllocator(); +NODE_EXTERN void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator); + +class NODE_EXTERN MultiIsolatePlatform : public v8::Platform { + public: + ~MultiIsolatePlatform() override { } + // Returns true if work was dispatched or executed. New tasks that are + // posted during flushing of the queue are postponed until the next + // flushing. + virtual bool FlushForegroundTasks(v8::Isolate* isolate) = 0; + virtual void DrainTasks(v8::Isolate* isolate) = 0; + virtual void CancelPendingDelayedTasks(v8::Isolate* isolate) = 0; + + // These will be called by the `IsolateData` creation/destruction functions. + virtual void RegisterIsolate(v8::Isolate* isolate, + struct uv_loop_s* loop) = 0; + virtual void UnregisterIsolate(v8::Isolate* isolate) = 0; +}; + +// Set up some Node.js-specific defaults for `params`, in particular +// the ArrayBuffer::Allocator if it is provided, memory limits, and +// possibly a code event handler. +NODE_EXTERN void SetIsolateCreateParams(v8::Isolate::CreateParams* params, + ArrayBufferAllocator* allocator + = nullptr); +// Set a number of callbacks for the `isolate`, in particular the Node.js +// uncaught exception listener. +NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate); +// Creates a new isolate with Node.js-specific settings. +// This is a convenience method equivalent to using SetIsolateCreateParams(), +// Isolate::Allocate(), MultiIsolatePlatform::RegisterIsolate(), +// Isolate::Initialize(), and SetIsolateUpForNode(). +NODE_EXTERN v8::Isolate* NewIsolate(ArrayBufferAllocator* allocator, + struct uv_loop_s* event_loop); +NODE_EXTERN v8::Isolate* NewIsolate(ArrayBufferAllocator* allocator, + struct uv_loop_s* event_loop, + MultiIsolatePlatform* platform); + +// Creates a new context with Node.js-specific tweaks. +NODE_EXTERN v8::Local NewContext( + v8::Isolate* isolate, + v8::Local object_template = + v8::Local()); + +// If `platform` is passed, it will be used to register new Worker instances. +// It can be `nullptr`, in which case creating new Workers inside of +// Environments that use this `IsolateData` will not work. +NODE_EXTERN IsolateData* CreateIsolateData( + v8::Isolate* isolate, + struct uv_loop_s* loop, + MultiIsolatePlatform* platform = nullptr, + ArrayBufferAllocator* allocator = nullptr); +NODE_EXTERN void FreeIsolateData(IsolateData* isolate_data); + +// TODO(addaleax): Add an official variant using STL containers, and move +// per-Environment options parsing here. +// Returns nullptr when the Environment cannot be created e.g. there are +// pending JavaScript exceptions. +NODE_EXTERN Environment* CreateEnvironment(IsolateData* isolate_data, + v8::Local context, + int argc, + const char* const* argv, + int exec_argc, + const char* const* exec_argv); + +NODE_EXTERN void LoadEnvironment(Environment* env); +NODE_EXTERN void FreeEnvironment(Environment* env); + +// This may return nullptr if context is not associated with a Node instance. +NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local context); + +// This returns the MultiIsolatePlatform used in the main thread of Node.js. +// If NODE_USE_V8_PLATFORM haven't been defined when Node.js was built, +// it returns nullptr. +NODE_EXTERN MultiIsolatePlatform* GetMainThreadMultiIsolatePlatform(); + +NODE_EXTERN MultiIsolatePlatform* CreatePlatform( + int thread_pool_size, + node::tracing::TracingController* tracing_controller); +MultiIsolatePlatform* InitializeV8Platform(int thread_pool_size); +NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform); + +NODE_EXTERN void EmitBeforeExit(Environment* env); +NODE_EXTERN int EmitExit(Environment* env); +NODE_EXTERN void RunAtExit(Environment* env); + +// This may return nullptr if the current v8::Context is not associated +// with a Node instance. +NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate); + +/* Converts a unixtime to V8 Date */ +NODE_DEPRECATED("Use v8::Date::New() directly", + inline v8::Local NODE_UNIXTIME_V8(double time) { + return v8::Date::New( + v8::Isolate::GetCurrent()->GetCurrentContext(), + 1000 * time) + .ToLocalChecked(); + }) +#define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8 +NODE_DEPRECATED("Use v8::Date::ValueOf() directly", + inline double NODE_V8_UNIXTIME(v8::Local date) { + return date->ValueOf() / 1000; +}) +#define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME + +#define NODE_DEFINE_CONSTANT(target, constant) \ + do { \ + v8::Isolate* isolate = target->GetIsolate(); \ + v8::Local context = isolate->GetCurrentContext(); \ + v8::Local constant_name = \ + v8::String::NewFromUtf8(isolate, #constant, \ + v8::NewStringType::kInternalized).ToLocalChecked(); \ + v8::Local constant_value = \ + v8::Number::New(isolate, static_cast(constant)); \ + v8::PropertyAttribute constant_attributes = \ + static_cast(v8::ReadOnly | v8::DontDelete); \ + (target)->DefineOwnProperty(context, \ + constant_name, \ + constant_value, \ + constant_attributes).FromJust(); \ + } \ + while (0) + +#define NODE_DEFINE_HIDDEN_CONSTANT(target, constant) \ + do { \ + v8::Isolate* isolate = target->GetIsolate(); \ + v8::Local context = isolate->GetCurrentContext(); \ + v8::Local constant_name = \ + v8::String::NewFromUtf8(isolate, #constant, \ + v8::NewStringType::kInternalized) \ + .ToLocalChecked(); \ + v8::Local constant_value = \ + v8::Number::New(isolate, static_cast(constant)); \ + v8::PropertyAttribute constant_attributes = \ + static_cast(v8::ReadOnly | \ + v8::DontDelete | \ + v8::DontEnum); \ + (target)->DefineOwnProperty(context, \ + constant_name, \ + constant_value, \ + constant_attributes).FromJust(); \ + } \ + while (0) + +// Used to be a macro, hence the uppercase name. +inline void NODE_SET_METHOD(v8::Local recv, + const char* name, + v8::FunctionCallback callback) { + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::HandleScope handle_scope(isolate); + v8::Local t = v8::FunctionTemplate::New(isolate, + callback); + v8::Local fn_name = v8::String::NewFromUtf8(isolate, name, + v8::NewStringType::kInternalized).ToLocalChecked(); + t->SetClassName(fn_name); + recv->Set(fn_name, t); +} + +// Used to be a macro, hence the uppercase name. +inline void NODE_SET_METHOD(v8::Local recv, + const char* name, + v8::FunctionCallback callback) { + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::HandleScope handle_scope(isolate); + v8::Local context = isolate->GetCurrentContext(); + v8::Local t = v8::FunctionTemplate::New(isolate, + callback); + v8::Local fn = t->GetFunction(context).ToLocalChecked(); + v8::Local fn_name = v8::String::NewFromUtf8(isolate, name, + v8::NewStringType::kInternalized).ToLocalChecked(); + fn->SetName(fn_name); + recv->Set(context, fn_name, fn).FromJust(); +} +#define NODE_SET_METHOD node::NODE_SET_METHOD + +// Used to be a macro, hence the uppercase name. +// Not a template because it only makes sense for FunctionTemplates. +inline void NODE_SET_PROTOTYPE_METHOD(v8::Local recv, + const char* name, + v8::FunctionCallback callback) { + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::HandleScope handle_scope(isolate); + v8::Local s = v8::Signature::New(isolate, recv); + v8::Local t = + v8::FunctionTemplate::New(isolate, callback, v8::Local(), s); + v8::Local fn_name = v8::String::NewFromUtf8(isolate, name, + v8::NewStringType::kInternalized).ToLocalChecked(); + t->SetClassName(fn_name); + recv->PrototypeTemplate()->Set(fn_name, t); +} +#define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD + +// BINARY is a deprecated alias of LATIN1. +enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER, LATIN1 = BINARY}; + +NODE_EXTERN enum encoding ParseEncoding( + v8::Isolate* isolate, + v8::Local encoding_v, + enum encoding default_encoding = LATIN1); + +NODE_EXTERN void FatalException(v8::Isolate* isolate, + const v8::TryCatch& try_catch); + +NODE_EXTERN v8::Local Encode(v8::Isolate* isolate, + const char* buf, + size_t len, + enum encoding encoding = LATIN1); + +// Warning: This reverses endianness on Big Endian platforms, even though the +// signature using uint16_t implies that it should not. +NODE_EXTERN v8::Local Encode(v8::Isolate* isolate, + const uint16_t* buf, + size_t len); + +// Returns -1 if the handle was not valid for decoding +NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate, + v8::Local, + enum encoding encoding = LATIN1); +// returns bytes written. +NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate, + char* buf, + size_t buflen, + v8::Local, + enum encoding encoding = LATIN1); +#ifdef _WIN32 +NODE_EXTERN v8::Local WinapiErrnoException( + v8::Isolate* isolate, + int errorno, + const char* syscall = nullptr, + const char* msg = "", + const char* path = nullptr); +#endif + +const char* signo_string(int errorno); + + +typedef void (*addon_register_func)( + v8::Local exports, + v8::Local module, + void* priv); + +typedef void (*addon_context_register_func)( + v8::Local exports, + v8::Local module, + v8::Local context, + void* priv); + +enum ModuleFlags { + kLinked = 0x02 +}; + +struct node_module { + int nm_version; + unsigned int nm_flags; + void* nm_dso_handle; + const char* nm_filename; + node::addon_register_func nm_register_func; + node::addon_context_register_func nm_context_register_func; + const char* nm_modname; + void* nm_priv; + struct node_module* nm_link; +}; + +extern "C" NODE_EXTERN void node_module_register(void* mod); + +#ifdef _WIN32 +# define NODE_MODULE_EXPORT __declspec(dllexport) +#else +# define NODE_MODULE_EXPORT __attribute__((visibility("default"))) +#endif + +#ifdef NODE_SHARED_MODE +# define NODE_CTOR_PREFIX +#else +# define NODE_CTOR_PREFIX static +#endif + +#if defined(_MSC_VER) +#pragma section(".CRT$XCU", read) +#define NODE_C_CTOR(fn) \ + NODE_CTOR_PREFIX void __cdecl fn(void); \ + __declspec(dllexport, allocate(".CRT$XCU")) \ + void (__cdecl*fn ## _)(void) = fn; \ + NODE_CTOR_PREFIX void __cdecl fn(void) +#else +#define NODE_C_CTOR(fn) \ + NODE_CTOR_PREFIX void fn(void) __attribute__((constructor)); \ + NODE_CTOR_PREFIX void fn(void) +#endif + +#define NODE_MODULE_X(modname, regfunc, priv, flags) \ + extern "C" { \ + static node::node_module _module = \ + { \ + NODE_MODULE_VERSION, \ + flags, \ + NULL, /* NOLINT (readability/null_usage) */ \ + __FILE__, \ + (node::addon_register_func) (regfunc), \ + NULL, /* NOLINT (readability/null_usage) */ \ + NODE_STRINGIFY(modname), \ + priv, \ + NULL /* NOLINT (readability/null_usage) */ \ + }; \ + NODE_C_CTOR(_register_ ## modname) { \ + node_module_register(&_module); \ + } \ + } + +#define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags) \ + extern "C" { \ + static node::node_module _module = \ + { \ + NODE_MODULE_VERSION, \ + flags, \ + NULL, /* NOLINT (readability/null_usage) */ \ + __FILE__, \ + NULL, /* NOLINT (readability/null_usage) */ \ + (node::addon_context_register_func) (regfunc), \ + NODE_STRINGIFY(modname), \ + priv, \ + NULL /* NOLINT (readability/null_usage) */ \ + }; \ + NODE_C_CTOR(_register_ ## modname) { \ + node_module_register(&_module); \ + } \ + } + +// Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)` +// If no NODE_MODULE is declared, Node.js looks for the well-known +// symbol `node_register_module_v${NODE_MODULE_VERSION}`. +#define NODE_MODULE(modname, regfunc) \ + NODE_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage) + +#define NODE_MODULE_CONTEXT_AWARE(modname, regfunc) \ + /* NOLINTNEXTLINE (readability/null_usage) */ \ + NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0) + +// Embedders can use this type of binding for statically linked native bindings. +// It is used the same way addon bindings are used, except that linked bindings +// can be accessed through `process._linkedBinding(modname)`. +#define NODE_MODULE_LINKED(modname, regfunc) \ + /* NOLINTNEXTLINE (readability/null_usage) */ \ + NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, \ + node::ModuleFlags::kLinked) + +/* + * For backward compatibility in add-on modules. + */ +#define NODE_MODULE_DECL /* nothing */ + +#define NODE_MODULE_INITIALIZER_BASE node_register_module_v + +#define NODE_MODULE_INITIALIZER_X(base, version) \ + NODE_MODULE_INITIALIZER_X_HELPER(base, version) + +#define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version + +#define NODE_MODULE_INITIALIZER \ + NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE, \ + NODE_MODULE_VERSION) + +#define NODE_MODULE_INIT() \ + extern "C" NODE_MODULE_EXPORT void \ + NODE_MODULE_INITIALIZER(v8::Local exports, \ + v8::Local module, \ + v8::Local context); \ + NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, \ + NODE_MODULE_INITIALIZER) \ + void NODE_MODULE_INITIALIZER(v8::Local exports, \ + v8::Local module, \ + v8::Local context) + +/* Called after the event loop exits but before the VM is disposed. + * Callbacks are run in reverse order of registration, i.e. newest first. + */ +NODE_EXTERN void AtExit(void (*cb)(void* arg), void* arg = nullptr); + +/* Registers a callback with the passed-in Environment instance. The callback + * is called after the event loop exits, but before the VM is disposed. + * Callbacks are run in reverse order of registration, i.e. newest first. + */ +NODE_EXTERN void AtExit(Environment* env, + void (*cb)(void* arg), + void* arg = nullptr); + +typedef void (*promise_hook_func) (v8::PromiseHookType type, + v8::Local promise, + v8::Local parent, + void* arg); + +typedef double async_id; +struct async_context { + ::node::async_id async_id; + ::node::async_id trigger_async_id; +}; + +/* Registers an additional v8::PromiseHook wrapper. This API exists because V8 + * itself supports only a single PromiseHook. */ +NODE_DEPRECATED("Use async_hooks directly instead", + NODE_EXTERN void AddPromiseHook(v8::Isolate* isolate, + promise_hook_func fn, + void* arg)); + +/* This is a lot like node::AtExit, except that the hooks added via this + * function are run before the AtExit ones and will always be registered + * for the current Environment instance. + * These functions are safe to use in an addon supporting multiple + * threads/isolates. */ +NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate, + void (*fun)(void* arg), + void* arg); + +NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate, + void (*fun)(void* arg), + void* arg); + +/* Returns the id of the current execution context. If the return value is + * zero then no execution has been set. This will happen if the user handles + * I/O from native code. */ +NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate); + +/* Return same value as async_hooks.triggerAsyncId(); */ +NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate); + +/* If the native API doesn't inherit from the helper class then the callbacks + * must be triggered manually. This triggers the init() callback. The return + * value is the async id assigned to the resource. + * + * The `trigger_async_id` parameter should correspond to the resource which is + * creating the new resource, which will usually be the return value of + * `AsyncHooksGetTriggerAsyncId()`. */ +NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, + v8::Local resource, + const char* name, + async_id trigger_async_id = -1); + +NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, + v8::Local resource, + v8::Local name, + async_id trigger_async_id = -1); + +/* Emit the destroy() callback. */ +NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate, + async_context asyncContext); + +class InternalCallbackScope; + +/* This class works like `MakeCallback()` in that it sets up a specific + * asyncContext as the current one and informs the async_hooks and domains + * modules that this context is currently active. + * + * `MakeCallback()` is a wrapper around this class as well as + * `Function::Call()`. Either one of these mechanisms needs to be used for + * top-level calls into JavaScript (i.e. without any existing JS stack). + * + * This object should be stack-allocated to ensure that it is contained in a + * valid HandleScope. + * + * Exceptions happening within this scope will be treated like uncaught + * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope + * needs to be created inside of this scope. + */ +class NODE_EXTERN CallbackScope { + public: + CallbackScope(v8::Isolate* isolate, + v8::Local resource, + async_context asyncContext); + ~CallbackScope(); + + void operator=(const CallbackScope&) = delete; + void operator=(CallbackScope&&) = delete; + CallbackScope(const CallbackScope&) = delete; + CallbackScope(CallbackScope&&) = delete; + + private: + InternalCallbackScope* private_; + v8::TryCatch try_catch_; +}; + +/* An API specific to emit before/after callbacks is unnecessary because + * MakeCallback will automatically call them for you. + * + * These methods may create handles on their own, so run them inside a + * HandleScope. + * + * `asyncId` and `triggerAsyncId` should correspond to the values returned by + * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the + * invoking resource was created. If these values are unknown, 0 can be passed. + * */ +NODE_EXTERN +v8::MaybeLocal MakeCallback(v8::Isolate* isolate, + v8::Local recv, + v8::Local callback, + int argc, + v8::Local* argv, + async_context asyncContext); +NODE_EXTERN +v8::MaybeLocal MakeCallback(v8::Isolate* isolate, + v8::Local recv, + const char* method, + int argc, + v8::Local* argv, + async_context asyncContext); +NODE_EXTERN +v8::MaybeLocal MakeCallback(v8::Isolate* isolate, + v8::Local recv, + v8::Local symbol, + int argc, + v8::Local* argv, + async_context asyncContext); + +/* Helper class users can optionally inherit from. If + * `AsyncResource::MakeCallback()` is used, then all four callbacks will be + * called automatically. */ +class AsyncResource { + public: + AsyncResource(v8::Isolate* isolate, + v8::Local resource, + const char* name, + async_id trigger_async_id = -1) + : isolate_(isolate), + resource_(isolate, resource) { + async_context_ = EmitAsyncInit(isolate, resource, name, + trigger_async_id); + } + + virtual ~AsyncResource() { + EmitAsyncDestroy(isolate_, async_context_); + resource_.Reset(); + } + + v8::MaybeLocal MakeCallback( + v8::Local callback, + int argc, + v8::Local* argv) { + return node::MakeCallback(isolate_, get_resource(), + callback, argc, argv, + async_context_); + } + + v8::MaybeLocal MakeCallback( + const char* method, + int argc, + v8::Local* argv) { + return node::MakeCallback(isolate_, get_resource(), + method, argc, argv, + async_context_); + } + + v8::MaybeLocal MakeCallback( + v8::Local symbol, + int argc, + v8::Local* argv) { + return node::MakeCallback(isolate_, get_resource(), + symbol, argc, argv, + async_context_); + } + + v8::Local get_resource() { + return resource_.Get(isolate_); + } + + async_id get_async_id() const { + return async_context_.async_id; + } + + async_id get_trigger_async_id() const { + return async_context_.trigger_async_id; + } + + protected: + class CallbackScope : public node::CallbackScope { + public: + explicit CallbackScope(AsyncResource* res) + : node::CallbackScope(res->isolate_, + res->resource_.Get(res->isolate_), + res->async_context_) {} + }; + + private: + v8::Isolate* isolate_; + v8::Persistent resource_; + async_context async_context_; +}; + +} // namespace node + +#endif // SRC_NODE_H_ diff --git a/thirdparty/node/node_version.h b/thirdparty/node/node_version.h new file mode 100644 index 00000000..95e75c16 --- /dev/null +++ b/thirdparty/node/node_version.h @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +#ifndef SRC_NODE_VERSION_H_ +#define SRC_NODE_VERSION_H_ + +#define NODE_MAJOR_VERSION 11 +#define NODE_MINOR_VERSION 15 +#define NODE_PATCH_VERSION 0 + +#define NODE_VERSION_IS_LTS 0 +#define NODE_VERSION_LTS_CODENAME "" + +#define NODE_VERSION_IS_RELEASE 1 + +#ifndef NODE_STRINGIFY +#define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) +#define NODE_STRINGIFY_HELPER(n) #n +#endif + +#ifndef NODE_RELEASE +#define NODE_RELEASE "node" +#endif + +#ifndef NODE_TAG +# if NODE_VERSION_IS_RELEASE +# define NODE_TAG "" +# else +# define NODE_TAG "-pre" +# endif +#else +// NODE_TAG is passed without quotes when rc.exe is run from msbuild +# define NODE_EXE_VERSION NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \ + NODE_STRINGIFY(NODE_MINOR_VERSION) "." \ + NODE_STRINGIFY(NODE_PATCH_VERSION) \ + NODE_STRINGIFY(NODE_TAG) +#endif + +# define NODE_VERSION_STRING NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \ + NODE_STRINGIFY(NODE_MINOR_VERSION) "." \ + NODE_STRINGIFY(NODE_PATCH_VERSION) \ + NODE_TAG +#ifndef NODE_EXE_VERSION +# define NODE_EXE_VERSION NODE_VERSION_STRING +#endif + +#define NODE_VERSION "v" NODE_VERSION_STRING + + +#define NODE_VERSION_AT_LEAST(major, minor, patch) \ + (( (major) < NODE_MAJOR_VERSION) \ + || ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) \ + || ((major) == NODE_MAJOR_VERSION && \ + (minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION)) + +/** + * Node.js will refuse to load modules that weren't compiled against its own + * module ABI number, exposed as the process.versions.modules property. + * + * When this version number is changed, node.js will refuse + * to load older modules. This should be done whenever + * an API is broken in the C++ side, including in v8 or + * other dependencies. + * + * Node.js will not change the module version during a Major release line + * We will at times update the version of V8 shipped in the release line + * if it can be made ABI compatible with the previous version. + * + * Module version by Node.js version: + * Node.js v0.10.x: 11 + * Node.js v0.12.x: 14 + * Node.js v4.x: 46 + * Node.js v5.x: 47 + * Node.js v6.x: 48 + * Node.js v7.x: 51 + * Node.js v8.x: 57 + * + * Module version by V8 ABI version: + * V8 5.4: 51 + * V8 5.5: 52 + * V8 5.6: 53 + * V8 5.7: 54 + * V8 5.8: 55 + * V8 5.9: 56 + * V8 6.0: 57 + * V8 6.1: 58 + * V8 6.2: 59 + * V8 6.3: 60 + * V8 6.4: 61 + * V8 6.5: 62 + * V8 6.6: 63 + * V8 6.7: 64 + * V8 6.8: 65 + * V8 6.9: 66 + * V8 7.0: 67 + * + * More information can be found at https://nodejs.org/en/download/releases/ + */ +#define NODE_MODULE_VERSION 67 + +// the NAPI_VERSION provided by this version of the runtime +#define NAPI_VERSION 4 + +#endif // SRC_NODE_VERSION_H_ diff --git a/thirdparty/node/v8-platform.h b/thirdparty/node/v8-platform.h new file mode 100644 index 00000000..cfeb13b6 --- /dev/null +++ b/thirdparty/node/v8-platform.h @@ -0,0 +1,395 @@ +// Copyright 2013 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef V8_V8_PLATFORM_H_ +#define V8_V8_PLATFORM_H_ + +#include +#include +#include // For abort. +#include +#include + +#include "v8config.h" // NOLINT(build/include) + +namespace v8 { + +class Isolate; + +/** + * A Task represents a unit of work. + */ +class Task { + public: + virtual ~Task() = default; + + virtual void Run() = 0; +}; + +/** + * An IdleTask represents a unit of work to be performed in idle time. + * The Run method is invoked with an argument that specifies the deadline in + * seconds returned by MonotonicallyIncreasingTime(). + * The idle task is expected to complete by this deadline. + */ +class IdleTask { + public: + virtual ~IdleTask() = default; + virtual void Run(double deadline_in_seconds) = 0; +}; + +/** + * A TaskRunner allows scheduling of tasks. The TaskRunner may still be used to + * post tasks after the isolate gets destructed, but these tasks may not get + * executed anymore. All tasks posted to a given TaskRunner will be invoked in + * sequence. Tasks can be posted from any thread. + */ +class TaskRunner { + public: + /** + * Schedules a task to be invoked by this TaskRunner. The TaskRunner + * implementation takes ownership of |task|. + */ + virtual void PostTask(std::unique_ptr task) = 0; + + /** + * Schedules a task to be invoked by this TaskRunner. The task is scheduled + * after the given number of seconds |delay_in_seconds|. The TaskRunner + * implementation takes ownership of |task|. + */ + virtual void PostDelayedTask(std::unique_ptr task, + double delay_in_seconds) = 0; + + /** + * Schedules an idle task to be invoked by this TaskRunner. The task is + * scheduled when the embedder is idle. Requires that + * TaskRunner::SupportsIdleTasks(isolate) is true. Idle tasks may be reordered + * relative to other task types and may be starved for an arbitrarily long + * time if no idle time is available. The TaskRunner implementation takes + * ownership of |task|. + */ + virtual void PostIdleTask(std::unique_ptr task) = 0; + + /** + * Returns true if idle tasks are enabled for this TaskRunner. + */ + virtual bool IdleTasksEnabled() = 0; + + TaskRunner() = default; + virtual ~TaskRunner() = default; + + private: + TaskRunner(const TaskRunner&) = delete; + TaskRunner& operator=(const TaskRunner&) = delete; +}; + +/** + * The interface represents complex arguments to trace events. + */ +class ConvertableToTraceFormat { + public: + virtual ~ConvertableToTraceFormat() = default; + + /** + * Append the class info to the provided |out| string. The appended + * data must be a valid JSON object. Strings must be properly quoted, and + * escaped. There is no processing applied to the content after it is + * appended. + */ + virtual void AppendAsTraceFormat(std::string* out) const = 0; +}; + +/** + * V8 Tracing controller. + * + * Can be implemented by an embedder to record trace events from V8. + */ +class TracingController { + public: + virtual ~TracingController() = default; + + /** + * Called by TRACE_EVENT* macros, don't call this directly. + * The name parameter is a category group for example: + * TRACE_EVENT0("v8,parse", "V8.Parse") + * The pointer returned points to a value with zero or more of the bits + * defined in CategoryGroupEnabledFlags. + **/ + virtual const uint8_t* GetCategoryGroupEnabled(const char* name) { + static uint8_t no = 0; + return &no; + } + + /** + * Adds a trace event to the platform tracing system. These function calls are + * usually the result of a TRACE_* macro from trace_event_common.h when + * tracing and the category of the particular trace are enabled. It is not + * advisable to call these functions on their own; they are really only meant + * to be used by the trace macros. The returned handle can be used by + * UpdateTraceEventDuration to update the duration of COMPLETE events. + */ + virtual uint64_t AddTraceEvent( + char phase, const uint8_t* category_enabled_flag, const char* name, + const char* scope, uint64_t id, uint64_t bind_id, int32_t num_args, + const char** arg_names, const uint8_t* arg_types, + const uint64_t* arg_values, + std::unique_ptr* arg_convertables, + unsigned int flags) { + return 0; + } + virtual uint64_t AddTraceEventWithTimestamp( + char phase, const uint8_t* category_enabled_flag, const char* name, + const char* scope, uint64_t id, uint64_t bind_id, int32_t num_args, + const char** arg_names, const uint8_t* arg_types, + const uint64_t* arg_values, + std::unique_ptr* arg_convertables, + unsigned int flags, int64_t timestamp) { + return 0; + } + + /** + * Sets the duration field of a COMPLETE trace event. It must be called with + * the handle returned from AddTraceEvent(). + **/ + virtual void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, + const char* name, uint64_t handle) {} + + class TraceStateObserver { + public: + virtual ~TraceStateObserver() = default; + virtual void OnTraceEnabled() = 0; + virtual void OnTraceDisabled() = 0; + }; + + /** Adds tracing state change observer. */ + virtual void AddTraceStateObserver(TraceStateObserver*) {} + + /** Removes tracing state change observer. */ + virtual void RemoveTraceStateObserver(TraceStateObserver*) {} +}; + +/** + * A V8 memory page allocator. + * + * Can be implemented by an embedder to manage large host OS allocations. + */ +class PageAllocator { + public: + virtual ~PageAllocator() = default; + + /** + * Gets the page granularity for AllocatePages and FreePages. Addresses and + * lengths for those calls should be multiples of AllocatePageSize(). + */ + virtual size_t AllocatePageSize() = 0; + + /** + * Gets the page granularity for SetPermissions and ReleasePages. Addresses + * and lengths for those calls should be multiples of CommitPageSize(). + */ + virtual size_t CommitPageSize() = 0; + + /** + * Sets the random seed so that GetRandomMmapAddr() will generate repeatable + * sequences of random mmap addresses. + */ + virtual void SetRandomMmapSeed(int64_t seed) = 0; + + /** + * Returns a randomized address, suitable for memory allocation under ASLR. + * The address will be aligned to AllocatePageSize. + */ + virtual void* GetRandomMmapAddr() = 0; + + /** + * Memory permissions. + */ + enum Permission { + kNoAccess, + kRead, + kReadWrite, + // TODO(hpayer): Remove this flag. Memory should never be rwx. + kReadWriteExecute, + kReadExecute + }; + + /** + * Allocates memory in range with the given alignment and permission. + */ + virtual void* AllocatePages(void* address, size_t length, size_t alignment, + Permission permissions) = 0; + + /** + * Frees memory in a range that was allocated by a call to AllocatePages. + */ + virtual bool FreePages(void* address, size_t length) = 0; + + /** + * Releases memory in a range that was allocated by a call to AllocatePages. + */ + virtual bool ReleasePages(void* address, size_t length, + size_t new_length) = 0; + + /** + * Sets permissions on pages in an allocated range. + */ + virtual bool SetPermissions(void* address, size_t length, + Permission permissions) = 0; +}; + +/** + * V8 Platform abstraction layer. + * + * The embedder has to provide an implementation of this interface before + * initializing the rest of V8. + */ +class Platform { + public: + virtual ~Platform() = default; + + /** + * Allows the embedder to manage memory page allocations. + */ + virtual PageAllocator* GetPageAllocator() { + // TODO(bbudge) Make this abstract after all embedders implement this. + return nullptr; + } + + /** + * Enables the embedder to respond in cases where V8 can't allocate large + * blocks of memory. V8 retries the failed allocation once after calling this + * method. On success, execution continues; otherwise V8 exits with a fatal + * error. + * Embedder overrides of this function must NOT call back into V8. + */ + virtual void OnCriticalMemoryPressure() { + // TODO(bbudge) Remove this when embedders override the following method. + // See crbug.com/634547. + } + + /** + * Enables the embedder to respond in cases where V8 can't allocate large + * memory regions. The |length| parameter is the amount of memory needed. + * Returns true if memory is now available. Returns false if no memory could + * be made available. V8 will retry allocations until this method returns + * false. + * + * Embedder overrides of this function must NOT call back into V8. + */ + virtual bool OnCriticalMemoryPressure(size_t length) { return false; } + + /** + * Gets the number of worker threads used by + * Call(BlockingTask)OnWorkerThread(). This can be used to estimate the number + * of tasks a work package should be split into. A return value of 0 means + * that there are no worker threads available. Note that a value of 0 won't + * prohibit V8 from posting tasks using |CallOnWorkerThread|. + */ + virtual int NumberOfWorkerThreads() = 0; + + /** + * Returns a TaskRunner which can be used to post a task on the foreground. + * This function should only be called from a foreground thread. + */ + virtual std::shared_ptr GetForegroundTaskRunner( + Isolate* isolate) = 0; + + /** + * Schedules a task to be invoked on a worker thread. + */ + virtual void CallOnWorkerThread(std::unique_ptr task) = 0; + + /** + * Schedules a task that blocks the main thread to be invoked with + * high-priority on a worker thread. + */ + virtual void CallBlockingTaskOnWorkerThread(std::unique_ptr task) { + // Embedders may optionally override this to process these tasks in a high + // priority pool. + CallOnWorkerThread(std::move(task)); + } + + /** + * Schedules a task to be invoked on a worker thread after |delay_in_seconds| + * expires. + */ + virtual void CallDelayedOnWorkerThread(std::unique_ptr task, + double delay_in_seconds) = 0; + + /** + * Schedules a task to be invoked on a foreground thread wrt a specific + * |isolate|. Tasks posted for the same isolate should be execute in order of + * scheduling. The definition of "foreground" is opaque to V8. + */ + virtual void CallOnForegroundThread(Isolate* isolate, Task* task) = 0; + + /** + * Schedules a task to be invoked on a foreground thread wrt a specific + * |isolate| after the given number of seconds |delay_in_seconds|. + * Tasks posted for the same isolate should be execute in order of + * scheduling. The definition of "foreground" is opaque to V8. + */ + virtual void CallDelayedOnForegroundThread(Isolate* isolate, Task* task, + double delay_in_seconds) = 0; + + /** + * Schedules a task to be invoked on a foreground thread wrt a specific + * |isolate| when the embedder is idle. + * Requires that SupportsIdleTasks(isolate) is true. + * Idle tasks may be reordered relative to other task types and may be + * starved for an arbitrarily long time if no idle time is available. + * The definition of "foreground" is opaque to V8. + */ + virtual void CallIdleOnForegroundThread(Isolate* isolate, IdleTask* task) { + // This must be overriden if |IdleTasksEnabled()|. + abort(); + } + + /** + * Returns true if idle tasks are enabled for the given |isolate|. + */ + virtual bool IdleTasksEnabled(Isolate* isolate) { + return false; + } + + /** + * Monotonically increasing time in seconds from an arbitrary fixed point in + * the past. This function is expected to return at least + * millisecond-precision values. For this reason, + * it is recommended that the fixed point be no further in the past than + * the epoch. + **/ + virtual double MonotonicallyIncreasingTime() = 0; + + /** + * Current wall-clock time in milliseconds since epoch. + * This function is expected to return at least millisecond-precision values. + */ + virtual double CurrentClockTimeMillis() = 0; + + typedef void (*StackTracePrinter)(); + + /** + * Returns a function pointer that print a stack trace of the current stack + * on invocation. Disables printing of the stack trace if nullptr. + */ + virtual StackTracePrinter GetStackTracePrinter() { return nullptr; } + + /** + * Returns an instance of a v8::TracingController. This must be non-nullptr. + */ + virtual TracingController* GetTracingController() = 0; + + protected: + /** + * Default implementation of current wall-clock time in milliseconds + * since epoch. Useful for implementing |CurrentClockTimeMillis| if + * nothing special needed. + */ + static double SystemClockTimeMillis(); +}; + +} // namespace v8 + +#endif // V8_V8_PLATFORM_H_ diff --git a/thirdparty/node/v8-version.h b/thirdparty/node/v8-version.h new file mode 100644 index 00000000..63dc5e7a --- /dev/null +++ b/thirdparty/node/v8-version.h @@ -0,0 +1,20 @@ +// Copyright 2015 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef V8_INCLUDE_VERSION_H_ // V8_VERSION_H_ conflicts with src/version.h +#define V8_INCLUDE_VERSION_H_ + +// These macros define the version number for the current version. +// NOTE these macros are used by some of the tool scripts and the build +// system so their names cannot be changed without changing the scripts. +#define V8_MAJOR_VERSION 7 +#define V8_MINOR_VERSION 0 +#define V8_BUILD_NUMBER 276 +#define V8_PATCH_LEVEL 38 + +// Use 1 for candidates and 0 otherwise. +// (Boolean macro values are not supported by all preprocessors.) +#define V8_IS_CANDIDATE_VERSION 0 + +#endif // V8_INCLUDE_VERSION_H_ diff --git a/thirdparty/node/v8.h b/thirdparty/node/v8.h new file mode 100644 index 00000000..325d3b09 --- /dev/null +++ b/thirdparty/node/v8.h @@ -0,0 +1,10788 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** \mainpage V8 API Reference Guide + * + * V8 is Google's open source JavaScript engine. + * + * This set of documents provides reference material generated from the + * V8 header file, include/v8.h. + * + * For other documentation see http://code.google.com/apis/v8/ + */ + +#ifndef INCLUDE_V8_H_ +#define INCLUDE_V8_H_ + +#include +#include +#include +#include +#include +#include + +#include "v8-version.h" // NOLINT(build/include) +#include "v8config.h" // NOLINT(build/include) + +// We reserve the V8_* prefix for macros defined in V8 public API and +// assume there are no name conflicts with the embedder's code. + +#ifdef V8_OS_WIN + +// Setup for Windows DLL export/import. When building the V8 DLL the +// BUILDING_V8_SHARED needs to be defined. When building a program which uses +// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8 +// static library or building a program which uses the V8 static library neither +// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined. +#ifdef BUILDING_V8_SHARED +# define V8_EXPORT __declspec(dllexport) +#elif USING_V8_SHARED +# define V8_EXPORT __declspec(dllimport) +#else +# define V8_EXPORT +#endif // BUILDING_V8_SHARED + +#else // V8_OS_WIN + +// Setup for Linux shared library export. +#if V8_HAS_ATTRIBUTE_VISIBILITY +# ifdef BUILDING_V8_SHARED +# define V8_EXPORT __attribute__ ((visibility("default"))) +# else +# define V8_EXPORT +# endif +#else +# define V8_EXPORT +#endif + +#endif // V8_OS_WIN + +/** + * The v8 JavaScript engine. + */ +namespace v8 { + +class AccessorSignature; +class Array; +class ArrayBuffer; +class BigInt; +class BigIntObject; +class Boolean; +class BooleanObject; +class Context; +class Data; +class Date; +class External; +class Function; +class FunctionTemplate; +class HeapProfiler; +class ImplementationUtilities; +class Int32; +class Integer; +class Isolate; +template +class Maybe; +class Name; +class Number; +class NumberObject; +class Object; +class ObjectOperationDescriptor; +class ObjectTemplate; +class Platform; +class Primitive; +class Promise; +class PropertyDescriptor; +class Proxy; +class RawOperationDescriptor; +class Script; +class SharedArrayBuffer; +class Signature; +class StartupData; +class StackFrame; +class StackTrace; +class String; +class StringObject; +class Symbol; +class SymbolObject; +class PrimitiveArray; +class Private; +class Uint32; +class Utils; +class Value; +class WasmCompiledModule; +template class Local; +template +class MaybeLocal; +template class Eternal; +template class NonCopyablePersistentTraits; +template class PersistentBase; +template > +class Persistent; +template +class Global; +template class PersistentValueMap; +template +class PersistentValueMapBase; +template +class GlobalValueMap; +template class PersistentValueVector; +template class WeakCallbackObject; +class FunctionTemplate; +class ObjectTemplate; +template class FunctionCallbackInfo; +template class PropertyCallbackInfo; +class StackTrace; +class StackFrame; +class Isolate; +class CallHandlerHelper; +class EscapableHandleScope; +template class ReturnValue; + +namespace internal { +class Arguments; +class DeferredHandles; +class Heap; +class HeapObject; +class Isolate; +class LocalEmbedderHeapTracer; +class NeverReadOnlySpaceObject; +class Object; +struct ScriptStreamingData; +template class CustomArguments; +class PropertyCallbackArguments; +class FunctionCallbackArguments; +class GlobalHandles; + +namespace wasm { +class NativeModule; +class StreamingDecoder; +} // namespace wasm + +/** + * Configuration of tagging scheme. + */ +const int kApiPointerSize = sizeof(void*); // NOLINT +const int kApiDoubleSize = sizeof(double); // NOLINT +const int kApiIntSize = sizeof(int); // NOLINT +const int kApiInt64Size = sizeof(int64_t); // NOLINT + +// Tag information for HeapObject. +const int kHeapObjectTag = 1; +const int kWeakHeapObjectTag = 3; +const int kHeapObjectTagSize = 2; +const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1; + +// Tag information for Smi. +const int kSmiTag = 0; +const int kSmiTagSize = 1; +const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1; + +template +struct SmiTagging; + +template +V8_INLINE internal::Object* IntToSmi(int value) { + int smi_shift_bits = kSmiTagSize + kSmiShiftSize; + intptr_t tagged_value = + (static_cast(value) << smi_shift_bits) | kSmiTag; + return reinterpret_cast(tagged_value); +} + +// Smi constants for systems where tagged pointer is a 32-bit value. +template <> +struct SmiTagging<4> { + enum { kSmiShiftSize = 0, kSmiValueSize = 31 }; + static int SmiShiftSize() { return kSmiShiftSize; } + static int SmiValueSize() { return kSmiValueSize; } + V8_INLINE static int SmiToInt(const internal::Object* value) { + int shift_bits = kSmiTagSize + kSmiShiftSize; + // Throw away top 32 bits and shift down (requires >> to be sign extending). + return static_cast(reinterpret_cast(value)) >> shift_bits; + } + V8_INLINE static internal::Object* IntToSmi(int value) { + return internal::IntToSmi(value); + } + V8_INLINE static constexpr bool IsValidSmi(intptr_t value) { + // To be representable as an tagged small integer, the two + // most-significant bits of 'value' must be either 00 or 11 due to + // sign-extension. To check this we add 01 to the two + // most-significant bits, and check if the most-significant bit is 0 + // + // CAUTION: The original code below: + // bool result = ((value + 0x40000000) & 0x80000000) == 0; + // may lead to incorrect results according to the C language spec, and + // in fact doesn't work correctly with gcc4.1.1 in some cases: The + // compiler may produce undefined results in case of signed integer + // overflow. The computation must be done w/ unsigned ints. + return static_cast(value) + 0x40000000U < 0x80000000U; + } +}; + +// Smi constants for systems where tagged pointer is a 64-bit value. +template <> +struct SmiTagging<8> { + enum { kSmiShiftSize = 31, kSmiValueSize = 32 }; + static int SmiShiftSize() { return kSmiShiftSize; } + static int SmiValueSize() { return kSmiValueSize; } + V8_INLINE static int SmiToInt(const internal::Object* value) { + int shift_bits = kSmiTagSize + kSmiShiftSize; + // Shift down and throw away top 32 bits. + return static_cast(reinterpret_cast(value) >> shift_bits); + } + V8_INLINE static internal::Object* IntToSmi(int value) { + return internal::IntToSmi(value); + } + V8_INLINE static constexpr bool IsValidSmi(intptr_t value) { + // To be representable as a long smi, the value must be a 32-bit integer. + return (value == static_cast(value)); + } +}; + +#if V8_COMPRESS_POINTERS +static_assert( + kApiPointerSize == kApiInt64Size, + "Pointer compression can be enabled only for 64-bit architectures"); +typedef SmiTagging<4> PlatformSmiTagging; +#else +typedef SmiTagging PlatformSmiTagging; +#endif + +const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize; +const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize; +const int kSmiMinValue = (static_cast(-1)) << (kSmiValueSize - 1); +const int kSmiMaxValue = -(kSmiMinValue + 1); +constexpr bool SmiValuesAre31Bits() { return kSmiValueSize == 31; } +constexpr bool SmiValuesAre32Bits() { return kSmiValueSize == 32; } + +} // namespace internal + +namespace debug { +class ConsoleCallArguments; +} // namespace debug + +// --- Handles --- + +#define TYPE_CHECK(T, S) \ + while (false) { \ + *(static_cast(0)) = static_cast(0); \ + } + +/** + * An object reference managed by the v8 garbage collector. + * + * All objects returned from v8 have to be tracked by the garbage + * collector so that it knows that the objects are still alive. Also, + * because the garbage collector may move objects, it is unsafe to + * point directly to an object. Instead, all objects are stored in + * handles which are known by the garbage collector and updated + * whenever an object moves. Handles should always be passed by value + * (except in cases like out-parameters) and they should never be + * allocated on the heap. + * + * There are two types of handles: local and persistent handles. + * + * Local handles are light-weight and transient and typically used in + * local operations. They are managed by HandleScopes. That means that a + * HandleScope must exist on the stack when they are created and that they are + * only valid inside of the HandleScope active during their creation. + * For passing a local handle to an outer HandleScope, an EscapableHandleScope + * and its Escape() method must be used. + * + * Persistent handles can be used when storing objects across several + * independent operations and have to be explicitly deallocated when they're no + * longer used. + * + * It is safe to extract the object stored in the handle by + * dereferencing the handle (for instance, to extract the Object* from + * a Local); the value will still be governed by a handle + * behind the scenes and the same rules apply to these values as to + * their handles. + */ +template +class Local { + public: + V8_INLINE Local() : val_(0) {} + template + V8_INLINE Local(Local that) + : val_(reinterpret_cast(*that)) { + /** + * This check fails when trying to convert between incompatible + * handles. For example, converting from a Local to a + * Local. + */ + TYPE_CHECK(T, S); + } + + /** + * Returns true if the handle is empty. + */ + V8_INLINE bool IsEmpty() const { return val_ == 0; } + + /** + * Sets the handle to be empty. IsEmpty() will then return true. + */ + V8_INLINE void Clear() { val_ = 0; } + + V8_INLINE T* operator->() const { return val_; } + + V8_INLINE T* operator*() const { return val_; } + + /** + * Checks whether two handles are the same. + * Returns true if both are empty, or if the objects + * to which they refer are identical. + * The handles' references are not checked. + */ + template + V8_INLINE bool operator==(const Local& that) const { + internal::Object** a = reinterpret_cast(this->val_); + internal::Object** b = reinterpret_cast(that.val_); + if (a == 0) return b == 0; + if (b == 0) return false; + return *a == *b; + } + + template V8_INLINE bool operator==( + const PersistentBase& that) const { + internal::Object** a = reinterpret_cast(this->val_); + internal::Object** b = reinterpret_cast(that.val_); + if (a == 0) return b == 0; + if (b == 0) return false; + return *a == *b; + } + + /** + * Checks whether two handles are different. + * Returns true if only one of the handles is empty, or if + * the objects to which they refer are different. + * The handles' references are not checked. + */ + template + V8_INLINE bool operator!=(const Local& that) const { + return !operator==(that); + } + + template V8_INLINE bool operator!=( + const Persistent& that) const { + return !operator==(that); + } + + /** + * Cast a handle to a subclass, e.g. Local to Local. + * This is only valid if the handle actually refers to a value of the + * target type. + */ + template V8_INLINE static Local Cast(Local that) { +#ifdef V8_ENABLE_CHECKS + // If we're going to perform the type check then we have to check + // that the handle isn't empty before doing the checked cast. + if (that.IsEmpty()) return Local(); +#endif + return Local(T::Cast(*that)); + } + + /** + * Calling this is equivalent to Local::Cast(). + * In particular, this is only valid if the handle actually refers to a value + * of the target type. + */ + template + V8_INLINE Local As() const { + return Local::Cast(*this); + } + + /** + * Create a local handle for the content of another handle. + * The referee is kept alive by the local handle even when + * the original handle is destroyed/disposed. + */ + V8_INLINE static Local New(Isolate* isolate, Local that); + V8_INLINE static Local New(Isolate* isolate, + const PersistentBase& that); + + private: + friend class Utils; + template friend class Eternal; + template friend class PersistentBase; + template friend class Persistent; + template friend class Local; + template + friend class MaybeLocal; + template friend class FunctionCallbackInfo; + template friend class PropertyCallbackInfo; + friend class String; + friend class Object; + friend class Context; + friend class Isolate; + friend class Private; + template friend class internal::CustomArguments; + friend Local Undefined(Isolate* isolate); + friend Local Null(Isolate* isolate); + friend Local True(Isolate* isolate); + friend Local False(Isolate* isolate); + friend class HandleScope; + friend class EscapableHandleScope; + template + friend class PersistentValueMapBase; + template friend class PersistentValueVector; + template + friend class ReturnValue; + + explicit V8_INLINE Local(T* that) : val_(that) {} + V8_INLINE static Local New(Isolate* isolate, T* that); + T* val_; +}; + + +#if !defined(V8_IMMINENT_DEPRECATION_WARNINGS) +// Handle is an alias for Local for historical reasons. +template +using Handle = Local; +#endif + + +/** + * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether + * the Local<> is empty before it can be used. + * + * If an API method returns a MaybeLocal<>, the API method can potentially fail + * either because an exception is thrown, or because an exception is pending, + * e.g. because a previous API call threw an exception that hasn't been caught + * yet, or because a TerminateExecution exception was thrown. In that case, an + * empty MaybeLocal is returned. + */ +template +class MaybeLocal { + public: + V8_INLINE MaybeLocal() : val_(nullptr) {} + template + V8_INLINE MaybeLocal(Local that) + : val_(reinterpret_cast(*that)) { + TYPE_CHECK(T, S); + } + + V8_INLINE bool IsEmpty() const { return val_ == nullptr; } + + /** + * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty, + * |false| is returned and |out| is left untouched. + */ + template + V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local* out) const { + out->val_ = IsEmpty() ? nullptr : this->val_; + return !IsEmpty(); + } + + /** + * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty, + * V8 will crash the process. + */ + V8_INLINE Local ToLocalChecked(); + + /** + * Converts this MaybeLocal<> to a Local<>, using a default value if this + * MaybeLocal<> is empty. + */ + template + V8_INLINE Local FromMaybe(Local default_value) const { + return IsEmpty() ? default_value : Local(val_); + } + + private: + T* val_; +}; + +/** + * Eternal handles are set-once handles that live for the lifetime of the + * isolate. + */ +template class Eternal { + public: + V8_INLINE Eternal() : val_(nullptr) {} + template + V8_INLINE Eternal(Isolate* isolate, Local handle) : val_(nullptr) { + Set(isolate, handle); + } + // Can only be safely called if already set. + V8_INLINE Local Get(Isolate* isolate) const; + V8_INLINE bool IsEmpty() const { return val_ == nullptr; } + template V8_INLINE void Set(Isolate* isolate, Local handle); + + private: + T* val_; +}; + + +static const int kInternalFieldsInWeakCallback = 2; +static const int kEmbedderFieldsInWeakCallback = 2; + +template +class WeakCallbackInfo { + public: + typedef void (*Callback)(const WeakCallbackInfo& data); + + WeakCallbackInfo(Isolate* isolate, T* parameter, + void* embedder_fields[kEmbedderFieldsInWeakCallback], + Callback* callback) + : isolate_(isolate), parameter_(parameter), callback_(callback) { + for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) { + embedder_fields_[i] = embedder_fields[i]; + } + } + + V8_INLINE Isolate* GetIsolate() const { return isolate_; } + V8_INLINE T* GetParameter() const { return parameter_; } + V8_INLINE void* GetInternalField(int index) const; + + // When first called, the embedder MUST Reset() the Global which triggered the + // callback. The Global itself is unusable for anything else. No v8 other api + // calls may be called in the first callback. Should additional work be + // required, the embedder must set a second pass callback, which will be + // called after all the initial callbacks are processed. + // Calling SetSecondPassCallback on the second pass will immediately crash. + void SetSecondPassCallback(Callback callback) const { *callback_ = callback; } + + private: + Isolate* isolate_; + T* parameter_; + Callback* callback_; + void* embedder_fields_[kEmbedderFieldsInWeakCallback]; +}; + + +// kParameter will pass a void* parameter back to the callback, kInternalFields +// will pass the first two internal fields back to the callback, kFinalizer +// will pass a void* parameter back, but is invoked before the object is +// actually collected, so it can be resurrected. In the last case, it is not +// possible to request a second pass callback. +enum class WeakCallbackType { kParameter, kInternalFields, kFinalizer }; + +/** + * An object reference that is independent of any handle scope. Where + * a Local handle only lives as long as the HandleScope in which it was + * allocated, a PersistentBase handle remains valid until it is explicitly + * disposed using Reset(). + * + * A persistent handle contains a reference to a storage cell within + * the V8 engine which holds an object value and which is updated by + * the garbage collector whenever the object is moved. A new storage + * cell can be created using the constructor or PersistentBase::Reset and + * existing handles can be disposed using PersistentBase::Reset. + * + */ +template class PersistentBase { + public: + /** + * If non-empty, destroy the underlying storage cell + * IsEmpty() will return true after this call. + */ + V8_INLINE void Reset(); + /** + * If non-empty, destroy the underlying storage cell + * and create a new one with the contents of other if other is non empty + */ + template + V8_INLINE void Reset(Isolate* isolate, const Local& other); + + /** + * If non-empty, destroy the underlying storage cell + * and create a new one with the contents of other if other is non empty + */ + template + V8_INLINE void Reset(Isolate* isolate, const PersistentBase& other); + + V8_INLINE bool IsEmpty() const { return val_ == NULL; } + V8_INLINE void Empty() { val_ = 0; } + + V8_INLINE Local Get(Isolate* isolate) const { + return Local::New(isolate, *this); + } + + template + V8_INLINE bool operator==(const PersistentBase& that) const { + internal::Object** a = reinterpret_cast(this->val_); + internal::Object** b = reinterpret_cast(that.val_); + if (a == NULL) return b == NULL; + if (b == NULL) return false; + return *a == *b; + } + + template + V8_INLINE bool operator==(const Local& that) const { + internal::Object** a = reinterpret_cast(this->val_); + internal::Object** b = reinterpret_cast(that.val_); + if (a == NULL) return b == NULL; + if (b == NULL) return false; + return *a == *b; + } + + template + V8_INLINE bool operator!=(const PersistentBase& that) const { + return !operator==(that); + } + + template + V8_INLINE bool operator!=(const Local& that) const { + return !operator==(that); + } + + /** + * Install a finalization callback on this object. + * NOTE: There is no guarantee as to *when* or even *if* the callback is + * invoked. The invocation is performed solely on a best effort basis. + * As always, GC-based finalization should *not* be relied upon for any + * critical form of resource management! + */ + template + V8_INLINE void SetWeak(P* parameter, + typename WeakCallbackInfo

::Callback callback, + WeakCallbackType type); + + /** + * Turns this handle into a weak phantom handle without finalization callback. + * The handle will be reset automatically when the garbage collector detects + * that the object is no longer reachable. + * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall + * returns how many phantom handles were reset by the garbage collector. + */ + V8_INLINE void SetWeak(); + + template + V8_INLINE P* ClearWeak(); + + // TODO(dcarney): remove this. + V8_INLINE void ClearWeak() { ClearWeak(); } + + /** + * Annotates the strong handle with the given label, which is then used by the + * heap snapshot generator as a name of the edge from the root to the handle. + * The function does not take ownership of the label and assumes that the + * label is valid as long as the handle is valid. + */ + V8_INLINE void AnnotateStrongRetainer(const char* label); + + /** + * Allows the embedder to tell the v8 garbage collector that a certain object + * is alive. Only allowed when the embedder is asked to trace its heap by + * EmbedderHeapTracer. + */ + V8_INLINE void RegisterExternalReference(Isolate* isolate) const; + + /** + * Marks the reference to this object independent. Garbage collector is free + * to ignore any object groups containing this object. Weak callback for an + * independent handle should not assume that it will be preceded by a global + * GC prologue callback or followed by a global GC epilogue callback. + */ + V8_DEPRECATE_SOON( + "Objects are always considered independent. " + "Use MarkActive to avoid collecting otherwise dead weak handles.", + V8_INLINE void MarkIndependent()); + + /** + * Marks the reference to this object as active. The scavenge garbage + * collection should not reclaim the objects marked as active, even if the + * object held by the handle is otherwise unreachable. + * + * This bit is cleared after the each garbage collection pass. + */ + V8_INLINE void MarkActive(); + + V8_DEPRECATE_SOON("See MarkIndependent.", + V8_INLINE bool IsIndependent() const); + + /** Checks if the handle holds the only reference to an object. */ + V8_INLINE bool IsNearDeath() const; + + /** Returns true if the handle's reference is weak. */ + V8_INLINE bool IsWeak() const; + + /** + * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface + * description in v8-profiler.h for details. + */ + V8_INLINE void SetWrapperClassId(uint16_t class_id); + + /** + * Returns the class ID previously assigned to this handle or 0 if no class ID + * was previously assigned. + */ + V8_INLINE uint16_t WrapperClassId() const; + + PersistentBase(const PersistentBase& other) = delete; // NOLINT + void operator=(const PersistentBase&) = delete; + + private: + friend class Isolate; + friend class Utils; + template friend class Local; + template friend class Persistent; + template + friend class Global; + template friend class PersistentBase; + template friend class ReturnValue; + template + friend class PersistentValueMapBase; + template friend class PersistentValueVector; + friend class Object; + + explicit V8_INLINE PersistentBase(T* val) : val_(val) {} + V8_INLINE static T* New(Isolate* isolate, T* that); + + T* val_; +}; + + +/** + * Default traits for Persistent. This class does not allow + * use of the copy constructor or assignment operator. + * At present kResetInDestructor is not set, but that will change in a future + * version. + */ +template +class NonCopyablePersistentTraits { + public: + typedef Persistent > NonCopyablePersistent; + static const bool kResetInDestructor = false; + template + V8_INLINE static void Copy(const Persistent& source, + NonCopyablePersistent* dest) { + Uncompilable(); + } + // TODO(dcarney): come up with a good compile error here. + template V8_INLINE static void Uncompilable() { + TYPE_CHECK(O, Primitive); + } +}; + + +/** + * Helper class traits to allow copying and assignment of Persistent. + * This will clone the contents of storage cell, but not any of the flags, etc. + */ +template +struct CopyablePersistentTraits { + typedef Persistent > CopyablePersistent; + static const bool kResetInDestructor = true; + template + static V8_INLINE void Copy(const Persistent& source, + CopyablePersistent* dest) { + // do nothing, just allow copy + } +}; + + +/** + * A PersistentBase which allows copy and assignment. + * + * Copy, assignment and destructor behavior is controlled by the traits + * class M. + * + * Note: Persistent class hierarchy is subject to future changes. + */ +template class Persistent : public PersistentBase { + public: + /** + * A Persistent with no storage cell. + */ + V8_INLINE Persistent() : PersistentBase(0) { } + /** + * Construct a Persistent from a Local. + * When the Local is non-empty, a new storage cell is created + * pointing to the same object, and no flags are set. + */ + template + V8_INLINE Persistent(Isolate* isolate, Local that) + : PersistentBase(PersistentBase::New(isolate, *that)) { + TYPE_CHECK(T, S); + } + /** + * Construct a Persistent from a Persistent. + * When the Persistent is non-empty, a new storage cell is created + * pointing to the same object, and no flags are set. + */ + template + V8_INLINE Persistent(Isolate* isolate, const Persistent& that) + : PersistentBase(PersistentBase::New(isolate, *that)) { + TYPE_CHECK(T, S); + } + /** + * The copy constructors and assignment operator create a Persistent + * exactly as the Persistent constructor, but the Copy function from the + * traits class is called, allowing the setting of flags based on the + * copied Persistent. + */ + V8_INLINE Persistent(const Persistent& that) : PersistentBase(0) { + Copy(that); + } + template + V8_INLINE Persistent(const Persistent& that) : PersistentBase(0) { + Copy(that); + } + V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT + Copy(that); + return *this; + } + template + V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT + Copy(that); + return *this; + } + /** + * The destructor will dispose the Persistent based on the + * kResetInDestructor flags in the traits class. Since not calling dispose + * can result in a memory leak, it is recommended to always set this flag. + */ + V8_INLINE ~Persistent() { + if (M::kResetInDestructor) this->Reset(); + } + + // TODO(dcarney): this is pretty useless, fix or remove + template + V8_INLINE static Persistent& Cast(const Persistent& that) { // NOLINT +#ifdef V8_ENABLE_CHECKS + // If we're going to perform the type check then we have to check + // that the handle isn't empty before doing the checked cast. + if (!that.IsEmpty()) T::Cast(*that); +#endif + return reinterpret_cast&>(const_cast&>(that)); + } + + // TODO(dcarney): this is pretty useless, fix or remove + template + V8_INLINE Persistent& As() const { // NOLINT + return Persistent::Cast(*this); + } + + private: + friend class Isolate; + friend class Utils; + template friend class Local; + template friend class Persistent; + template friend class ReturnValue; + + explicit V8_INLINE Persistent(T* that) : PersistentBase(that) {} + V8_INLINE T* operator*() const { return this->val_; } + template + V8_INLINE void Copy(const Persistent& that); +}; + + +/** + * A PersistentBase which has move semantics. + * + * Note: Persistent class hierarchy is subject to future changes. + */ +template +class Global : public PersistentBase { + public: + /** + * A Global with no storage cell. + */ + V8_INLINE Global() : PersistentBase(nullptr) {} + /** + * Construct a Global from a Local. + * When the Local is non-empty, a new storage cell is created + * pointing to the same object, and no flags are set. + */ + template + V8_INLINE Global(Isolate* isolate, Local that) + : PersistentBase(PersistentBase::New(isolate, *that)) { + TYPE_CHECK(T, S); + } + /** + * Construct a Global from a PersistentBase. + * When the Persistent is non-empty, a new storage cell is created + * pointing to the same object, and no flags are set. + */ + template + V8_INLINE Global(Isolate* isolate, const PersistentBase& that) + : PersistentBase(PersistentBase::New(isolate, that.val_)) { + TYPE_CHECK(T, S); + } + /** + * Move constructor. + */ + V8_INLINE Global(Global&& other) : PersistentBase(other.val_) { // NOLINT + other.val_ = nullptr; + } + V8_INLINE ~Global() { this->Reset(); } + /** + * Move via assignment. + */ + template + V8_INLINE Global& operator=(Global&& rhs) { // NOLINT + TYPE_CHECK(T, S); + if (this != &rhs) { + this->Reset(); + this->val_ = rhs.val_; + rhs.val_ = nullptr; + } + return *this; + } + /** + * Pass allows returning uniques from functions, etc. + */ + Global Pass() { return static_cast(*this); } // NOLINT + + /* + * For compatibility with Chromium's base::Bind (base::Passed). + */ + typedef void MoveOnlyTypeForCPP03; + + Global(const Global&) = delete; + void operator=(const Global&) = delete; + + private: + template + friend class ReturnValue; + V8_INLINE T* operator*() const { return this->val_; } +}; + + +// UniquePersistent is an alias for Global for historical reason. +template +using UniquePersistent = Global; + + + /** + * A stack-allocated class that governs a number of local handles. + * After a handle scope has been created, all local handles will be + * allocated within that handle scope until either the handle scope is + * deleted or another handle scope is created. If there is already a + * handle scope and a new one is created, all allocations will take + * place in the new handle scope until it is deleted. After that, + * new handles will again be allocated in the original handle scope. + * + * After the handle scope of a local handle has been deleted the + * garbage collector will no longer track the object stored in the + * handle and may deallocate it. The behavior of accessing a handle + * for which the handle scope has been deleted is undefined. + */ +class V8_EXPORT HandleScope { + public: + explicit HandleScope(Isolate* isolate); + + ~HandleScope(); + + /** + * Counts the number of allocated handles. + */ + static int NumberOfHandles(Isolate* isolate); + + V8_INLINE Isolate* GetIsolate() const { + return reinterpret_cast(isolate_); + } + + HandleScope(const HandleScope&) = delete; + void operator=(const HandleScope&) = delete; + + protected: + V8_INLINE HandleScope() {} + + void Initialize(Isolate* isolate); + + static internal::Object** CreateHandle(internal::Isolate* isolate, + internal::Object* value); + + private: + // Declaring operator new and delete as deleted is not spec compliant. + // Therefore declare them private instead to disable dynamic alloc + void* operator new(size_t size); + void* operator new[](size_t size); + void operator delete(void*, size_t); + void operator delete[](void*, size_t); + + // Uses heap_object to obtain the current Isolate. + static internal::Object** CreateHandle( + internal::NeverReadOnlySpaceObject* heap_object, internal::Object* value); + + internal::Isolate* isolate_; + internal::Object** prev_next_; + internal::Object** prev_limit_; + + // Local::New uses CreateHandle with an Isolate* parameter. + template friend class Local; + + // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with + // a HeapObject* in their shortcuts. + friend class Object; + friend class Context; +}; + + +/** + * A HandleScope which first allocates a handle in the current scope + * which will be later filled with the escape value. + */ +class V8_EXPORT EscapableHandleScope : public HandleScope { + public: + explicit EscapableHandleScope(Isolate* isolate); + V8_INLINE ~EscapableHandleScope() {} + + /** + * Pushes the value into the previous scope and returns a handle to it. + * Cannot be called twice. + */ + template + V8_INLINE Local Escape(Local value) { + internal::Object** slot = + Escape(reinterpret_cast(*value)); + return Local(reinterpret_cast(slot)); + } + + template + V8_INLINE MaybeLocal EscapeMaybe(MaybeLocal value) { + return Escape(value.FromMaybe(Local())); + } + + EscapableHandleScope(const EscapableHandleScope&) = delete; + void operator=(const EscapableHandleScope&) = delete; + + private: + // Declaring operator new and delete as deleted is not spec compliant. + // Therefore declare them private instead to disable dynamic alloc + void* operator new(size_t size); + void* operator new[](size_t size); + void operator delete(void*, size_t); + void operator delete[](void*, size_t); + + internal::Object** Escape(internal::Object** escape_value); + internal::Object** escape_slot_; +}; + +/** + * A SealHandleScope acts like a handle scope in which no handle allocations + * are allowed. It can be useful for debugging handle leaks. + * Handles can be allocated within inner normal HandleScopes. + */ +class V8_EXPORT SealHandleScope { + public: + explicit SealHandleScope(Isolate* isolate); + ~SealHandleScope(); + + SealHandleScope(const SealHandleScope&) = delete; + void operator=(const SealHandleScope&) = delete; + + private: + // Declaring operator new and delete as deleted is not spec compliant. + // Therefore declare them private instead to disable dynamic alloc + void* operator new(size_t size); + void* operator new[](size_t size); + void operator delete(void*, size_t); + void operator delete[](void*, size_t); + + internal::Isolate* const isolate_; + internal::Object** prev_limit_; + int prev_sealed_level_; +}; + + +// --- Special objects --- + + +/** + * The superclass of values and API object templates. + */ +class V8_EXPORT Data { + private: + Data(); +}; + +/** + * A container type that holds relevant metadata for module loading. + * + * This is passed back to the embedder as part of + * HostImportModuleDynamicallyCallback for module loading. + */ +class V8_EXPORT ScriptOrModule { + public: + /** + * The name that was passed by the embedder as ResourceName to the + * ScriptOrigin. This can be either a v8::String or v8::Undefined. + */ + Local GetResourceName(); + + /** + * The options that were passed by the embedder as HostDefinedOptions to + * the ScriptOrigin. + */ + Local GetHostDefinedOptions(); +}; + +/** + * An array to hold Primitive values. This is used by the embedder to + * pass host defined options to the ScriptOptions during compilation. + * + * This is passed back to the embedder as part of + * HostImportModuleDynamicallyCallback for module loading. + * + */ +class V8_EXPORT PrimitiveArray { + public: + static Local New(Isolate* isolate, int length); + int Length() const; + V8_DEPRECATED("Use Isolate* version", + void Set(int index, Local item)); + V8_DEPRECATED("Use Isolate* version", + Local Get(int index)); + void Set(Isolate* isolate, int index, Local item); + Local Get(Isolate* isolate, int index); +}; + +/** + * The optional attributes of ScriptOrigin. + */ +class ScriptOriginOptions { + public: + V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false, + bool is_opaque = false, bool is_wasm = false, + bool is_module = false) + : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) | + (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) | + (is_module ? kIsModule : 0)) {} + V8_INLINE ScriptOriginOptions(int flags) + : flags_(flags & + (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {} + + bool IsSharedCrossOrigin() const { + return (flags_ & kIsSharedCrossOrigin) != 0; + } + bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; } + bool IsWasm() const { return (flags_ & kIsWasm) != 0; } + bool IsModule() const { return (flags_ & kIsModule) != 0; } + + int Flags() const { return flags_; } + + private: + enum { + kIsSharedCrossOrigin = 1, + kIsOpaque = 1 << 1, + kIsWasm = 1 << 2, + kIsModule = 1 << 3 + }; + const int flags_; +}; + +/** + * The origin, within a file, of a script. + */ +class ScriptOrigin { + public: + V8_INLINE ScriptOrigin( + Local resource_name, + Local resource_line_offset = Local(), + Local resource_column_offset = Local(), + Local resource_is_shared_cross_origin = Local(), + Local script_id = Local(), + Local source_map_url = Local(), + Local resource_is_opaque = Local(), + Local is_wasm = Local(), + Local is_module = Local(), + Local host_defined_options = Local()); + + V8_INLINE Local ResourceName() const; + V8_INLINE Local ResourceLineOffset() const; + V8_INLINE Local ResourceColumnOffset() const; + V8_INLINE Local ScriptID() const; + V8_INLINE Local SourceMapUrl() const; + V8_INLINE Local HostDefinedOptions() const; + V8_INLINE ScriptOriginOptions Options() const { return options_; } + + private: + Local resource_name_; + Local resource_line_offset_; + Local resource_column_offset_; + ScriptOriginOptions options_; + Local script_id_; + Local source_map_url_; + Local host_defined_options_; +}; + +/** + * A compiled JavaScript script, not yet tied to a Context. + */ +class V8_EXPORT UnboundScript { + public: + /** + * Binds the script to the currently entered context. + */ + Local