diff --git a/.clang-format b/.clang-format index bba10e571..7a1fc2ca3 100644 --- a/.clang-format +++ b/.clang-format @@ -15,14 +15,19 @@ AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlines: DontAlign AlignOperands: true + AlignTrailingComments: false +# > clang-format-13, looks weird +# Kind: Leave +# OverEmptyLines: 2 + AllowAllArgumentsOnNextLine: true AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: Empty -AllowShortLambdasOnASingleLine: Empty +AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None @@ -95,13 +100,14 @@ IncludeIsMainSourceRegex: '' #IndentCaseBlocks: true IndentCaseLabels: false IndentGotoLabels: false -IndentPPDirectives: AfterHash +IndentPPDirectives: None IndentWidth: 4 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false -#LambdaBodyIntdentation: Signature +#>clang-format-13 +LambdaBodyIndentation: OuterScope MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 2 diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..ef65bb043 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,5 @@ +root = true + +[*.{cpp,ipp,hpp,h,c}] +indent_style = space +indent_size = 4 diff --git a/.github/actions/build-cmake-preset/action.yml b/.github/actions/build-cmake-preset/action.yml index 814763bd8..ed9128ff4 100644 --- a/.github/actions/build-cmake-preset/action.yml +++ b/.github/actions/build-cmake-preset/action.yml @@ -21,6 +21,11 @@ inputs: description: "Run `cmake --target package` and upload artifact" required: false type: boolean + retention-days: + description: "How long we keep the artifacts" + required: false + type: number + default: 14 run-tests: description: "Run tests" required: false @@ -68,7 +73,7 @@ runs: - name: Setup host if: runner.os == 'Linux' - run: sudo apt install -y ninja-build doxygen clang-12 llvm-12 + run: sudo apt install -y ninja-build doxygen id: setup-host-linux shell: bash @@ -108,6 +113,7 @@ runs: with: name: "${{ inputs.preset-name }}-test-results" path: '_build/**/*gtestresults.xml' + retention-days: ${{ inputs.retention-days }} - name: create cmake package for ${{ inputs.preset-name }} if: ${{ inputs.do-package == 'true' }} @@ -128,6 +134,7 @@ runs: name: ${{ steps.cmake-package.outputs.package-name }} path: ${{ steps.cmake-package.outputs.package-path }} if-no-files-found: 'error' + retention-days: ${{ inputs.retention-days }} - name: upload symbols package ${{ inputs.preset-name }} if: ${{ inputs.do-package-symbols == 'true' }} @@ -136,3 +143,4 @@ runs: name: ${{ steps.cmake-package.outputs.symbols-package-name }} path: ${{ steps.cmake-package.outputs.symbols-package-path}} if-no-files-found: 'error' + retention-days: ${{ inputs.retention-days }} diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index a82a72e22..0513147f5 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -4,47 +4,32 @@ SPDX-FileCopyrightText: 2023 Vector Informatik GmbH SPDX-License-Identifier: MIT --> -## Developer checklist (address before review) - -- [ ] Changelog.md updated -- [ ] Prepared update for depending repositories -- [ ] Documentation updated (public API changes only) -- [ ] API docstrings updated (public API changes only) - ---- - ## Subject -What kind of changes does this pull request comprise? + -- [ ] Feature -- [ ] Bug fix -- [ ] Documentation update -- [ ] CI / build infrastructure -- [ ] other _(please specify below)_ ## Description -_Either give a technical description what changed in this PR or use the text below_ - -Please read the Jira entry and the commit messages for a description of the changes of this PR - -## Addressed Jira ticket(s) -_Which Jira tickets are addressed with this pull request (list all if multiple tickets are affected)_ - -## Review assignments - -- [X] review code _(please specify in [Code review instructions](#code-review-instructions))_ -- [ ] check new/modified tests (does it make sense? does it cover the functionality sufficiently?) -- [ ] run functional tests manually -- [ ] run specific setup (e.g., demos) _(please specify in [Testing instructions](#testing-instructions))_ -- [ ] other _(please specify below)_ - -#### Code review instructions -_Which parts should be reviewed in detail? For example: content of console output, correct semantics of changes_ + -#### Testing instructions (e.g., for specific setups) -_Test steps and test setup description. For example: which programs or configs to use_ +## Instructions for review / testing + -## Commit history check +## Developer checklist (address before review) - - [ ] Rebase → commit history clean - - [ ] Squash and merge → proper PR title \ No newline at end of file +- [ ] Changelog.md updated +- [ ] Prepared update for depending repositories +- [ ] Documentation updated (public API changes only) +- [ ] API docstrings updated (public API changes only) +- [ ] Rebase → commit history clean +- [ ] Squash and merge → proper PR title diff --git a/.github/workflows/build-linux-asan.yml b/.github/workflows/build-linux-asan.yml deleted file mode 100644 index d384f95ae..000000000 --- a/.github/workflows/build-linux-asan.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: 'Linux + address sanitizer' -on: - push: - branches: [ "main" ] -jobs: - clang12-asan-debug: - name: Address Sanitizer Tests - environment: public-github-runners - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v3 - with: - submodules: true - - uses: ./.github/actions/build-cmake-preset - with: - preset-name: clang12-asan-debug diff --git a/.github/workflows/build-linux-featurebranch.yml b/.github/workflows/build-linux-featurebranch.yml new file mode 100644 index 000000000..6fab73dcb --- /dev/null +++ b/.github/workflows/build-linux-featurebranch.yml @@ -0,0 +1,24 @@ +name: 'Linux Feature Branch Builds' +on: + workflow_dispatch: + inputs: + do_package: + required: true + type: boolean + default: true + do_package_symbols: + required: true + type: boolean + default: false + retention_days: + required: true + type: number + default: 14 + +jobs: + call_linux_build: + uses: ./.github/workflows/build-linux.yml + with: + do_package: ${{ inputs.do_package }} + retention_days: ${{ fromJSON(inputs.retention_days) }} + diff --git a/.github/workflows/build-linux-tsan.yml b/.github/workflows/build-linux-tsan.yml deleted file mode 100644 index 5b5359c03..000000000 --- a/.github/workflows/build-linux-tsan.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: 'Linux + thread sanitizer' -on: - push: - branches: [ "main" ] -jobs: - clang12-tsan-debug: - name: Thread Sanitizer Tests - environment: public-github-runners - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v3 - with: - submodules: true - - uses: ./.github/actions/build-cmake-preset - with: - preset-name: clang12-tsan-debug - - diff --git a/.github/workflows/build-linux-ubsan.yml b/.github/workflows/build-linux-ubsan.yml deleted file mode 100644 index 74b21c5c3..000000000 --- a/.github/workflows/build-linux-ubsan.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: 'Linux + UB sanitizer' -on: - push: - branches: [ "main" ] -jobs: - clang12-ubsan-debug: - name: Undefined Behavior Sanitizer Tests - environment: public-github-runners - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v3 - with: - submodules: true - - uses: ./.github/actions/build-cmake-preset - with: - preset-name: clang12-ubsan-debug - cmake-args: "-D SILKIT_BUILD_DASHBOARD=OFF" - - diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml new file mode 100644 index 000000000..0f1191170 --- /dev/null +++ b/.github/workflows/build-linux.yml @@ -0,0 +1,56 @@ +name: 'Linux Release Builds' +on: + workflow_call: + inputs: + do_package: + required: false + type: boolean + default: false + do_package_symbols: + required: false + type: boolean + default: false + retention_days: + required: false + type: number + default: 14 + run_build: + required: true + type: boolean + +jobs: + clang14-release: + name: Clang 14 release Builds for Ubuntu 22.04 + environment: public-github-runners + runs-on: ubuntu-22.04 + if: inputs.run_build == true + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - uses: ./.github/actions/build-cmake-preset + with: + preset-name: clang14-release + do-package: ${{ inputs.do_package }} + retention-days: ${{ inputs.retention_days }} + + gcc-release: + name: GCC release Builds for Ubuntu 22.04 + environment: public-github-runners + runs-on: ubuntu-latest + container: + image: ghcr.io/mariusbgm/sil-kit-ci-ubuntu-22.04:main + if: inputs.run_build == true + steps: + - name: git checkout + uses: actions/checkout@v1 + with: + submodules: true + - name: GCC release build + uses: ./.github/actions/build-cmake-preset + id: build + with: + preset-name: linux-release + do-package: ${{ inputs.do_package }} + retention-days: ${{ env.retention_days }} + diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index c85d2351e..c5b0d79d4 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -1,8 +1,20 @@ name: macOS build on: - push: - branches: [ "main" ] + workflow_call: + inputs: + do_package: + required: false + type: boolean + default: false + do_package_symbols: + required: false + type: boolean + default: false + retention_days: + required: false + type: number + default: 14 jobs: build-macos: @@ -17,4 +29,6 @@ jobs: - uses: ./.github/actions/build-cmake-preset with: preset-name: clang-release - + do_package: ${{ inputs.do_package }} + do_package_symbols: ${{ inputs.do_package_symbols }} + retention_days: ${{ inputs.retention_days }} diff --git a/.github/workflows/build-release-packages.yml b/.github/workflows/build-release-packages.yml index f5de9fc85..f0220282b 100644 --- a/.github/workflows/build-release-packages.yml +++ b/.github/workflows/build-release-packages.yml @@ -8,7 +8,7 @@ jobs: environment: public-github-runners runs-on: ubuntu-latest container: - image: vectorgrp/sil-kit:ci-ubuntu-18.04 + image: ghcr.io/mariusbgm/sil-kit-ci-ubuntu-18.04:main outputs: package-name: ${{ steps.build.outputs.package-name}} steps: @@ -30,7 +30,7 @@ jobs: environment: public-github-runners runs-on: ubuntu-latest container: - image: vectorgrp/sil-kit:ci-ubuntu-18.04 + image: ghcr.io/mariusbgm/sil-kit-ci-ubuntu-18.04:main outputs: package-name: ${{ steps.build.outputs.package-name}} steps: @@ -45,6 +45,7 @@ jobs: preset-name: gcc8-debug do-package: true run-tests: false + upload-testlog: false do-package-symbols: true gcc8-package: @@ -100,6 +101,7 @@ jobs: do-package: true do-package-symbols: true run-tests: false + upload-testlog: false toolset: 14.1 build-arch: x86 @@ -157,6 +159,7 @@ jobs: do-package: true do-package-symbols: true run-tests: false + upload-testlog: false toolset: 14.1 build-arch: x64 diff --git a/.github/workflows/build-win-featurebranch.yml b/.github/workflows/build-win-featurebranch.yml new file mode 100644 index 000000000..d518287c7 --- /dev/null +++ b/.github/workflows/build-win-featurebranch.yml @@ -0,0 +1,20 @@ +name: 'Windows Feature Branch Builds' +on: + workflow_dispatch: + inputs: + do_package: + required: true + type: boolean + default: true + retention_days: + required: true + type: number + default: 14 + +jobs: + call_win_build: + uses: ./.github/workflows/build-win.yml + with: + do_package: ${{ inputs.do_package }} + retention_days: ${{ fromJSON(inputs.retention_days) }} + diff --git a/.github/workflows/build-win.yml b/.github/workflows/build-win.yml index 19664167a..fb79d24fe 100644 --- a/.github/workflows/build-win.yml +++ b/.github/workflows/build-win.yml @@ -1,19 +1,60 @@ -name: Windows build +name: 'Windows builds' on: + workflow_call: + inputs: + do_package: + required: false + type: boolean + default: false + do_package_symbols: + required: false + type: boolean + default: false + retention_days: + required: false + type: number + default: 14 + run_build: + required: true + type: boolean + push: - branches: [ "main" ] + branches: [ 'main' ] + +concurrency: + group: ${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true jobs: build-win-x64: - runs-on: windows-latest + runs-on: windows-2019 environment: public-github-runners + if: inputs.run_build == true steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: true - uses: ./.github/actions/build-cmake-preset with: preset-name: vs141-x64-release + do-package: ${{ inputs.do_package }} + retention-days: ${{ inputs.retention_days }} + build-arch: x64 + build-win-x32: + runs-on: windows-2019 + environment: public-github-runners + if: inputs.run_build == true + steps: + - uses: actions/checkout@v4 + with: + submodules: true + + - uses: ./.github/actions/build-cmake-preset + with: + preset-name: vs141-x86-release + do-package: ${{ inputs.do_package }} + retention-days: ${{ inputs.retention_days }} + build-arch: x86 diff --git a/.github/workflows/linux-asan.yml b/.github/workflows/linux-asan.yml new file mode 100644 index 000000000..e9d893918 --- /dev/null +++ b/.github/workflows/linux-asan.yml @@ -0,0 +1,25 @@ +name: 'Linux + Address Sanitizer' +on: + workflow_call: + inputs: + run_build: + required: true + type: boolean + + push: + branches: [ 'main' ] + +jobs: + clang14-asan: + environment: public-github-runners + runs-on: ubuntu-22.04 + if: inputs.run_build == true + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - uses: ./.github/actions/build-cmake-preset + with: + preset-name: clang14-relwithdebinfo + cmake-args: "-D SILKIT_ENABLE_ASAN=ON -D SILKIT_BUILD_DASHBOARD=OFF" + do-package: false diff --git a/.github/workflows/linux-tsan.yml b/.github/workflows/linux-tsan.yml new file mode 100644 index 000000000..8ada41426 --- /dev/null +++ b/.github/workflows/linux-tsan.yml @@ -0,0 +1,26 @@ +name: 'Linux + Thread Sanitizer' +on: + workflow_call: + inputs: + run_build: + required: true + type: boolean + + push: + branches: [ 'main' ] + +jobs: + clang14-tsan: + name: Thread Sanitizer Tests + environment: public-github-runners + runs-on: ubuntu-22.04 + if: inputs.run_build == true + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - uses: ./.github/actions/build-cmake-preset + with: + preset-name: clang14-relwithdebinfo + cmake-args: "-D SILKIT_ENABLE_THREADSAN=ON -D SILKIT_BUILD_DASHBOARD=OFF" + do-package: false diff --git a/.github/workflows/linux-ubsan.yml b/.github/workflows/linux-ubsan.yml new file mode 100644 index 000000000..82ae3b060 --- /dev/null +++ b/.github/workflows/linux-ubsan.yml @@ -0,0 +1,26 @@ +name: 'Linux + UB Sanitizer' +on: + workflow_call: + inputs: + run_build: + required: true + type: boolean + + push: + branches: [ 'main' ] + +jobs: + clang14-ubsan: + name: Undefined Behavior Sanitizer Tests + environment: public-github-runners + runs-on: ubuntu-22.04 + if: inputs.run_build == true + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - uses: ./.github/actions/build-cmake-preset + with: + preset-name: clang14-relwithdebinfo + cmake-args: "-D SILKIT_ENABLE_UBSAN=ON -D SILKIT_BUILD_DASHBOARD=OFF" + do-package: false diff --git a/.github/workflows/repo-pull-public.yaml b/.github/workflows/repo-pull-public.yaml new file mode 100644 index 000000000..c023b5db9 --- /dev/null +++ b/.github/workflows/repo-pull-public.yaml @@ -0,0 +1,29 @@ +on: + workflow_dispatch: + schedule: + - cron: "0 * * * *" # every hour + +jobs: + sync_repo: + name: Pull main branch from public GitHub to local branch + runs-on: Linux + environment: repo-sync-action/public-github + permissions: + contents: write + actions: write + deployments: write + + steps: + - uses: actions/checkout@v3 + with: + clean: true + fetch-depth: 0 + + - uses: vector-actions/repo-sync-action@main + with: + app-key: ${{ secrets.VECTOR_APP_KEY }} + app-id: ${{ secrets.VECTOR_APP_ID }} + remote-repo-url: https://github.com/vectorgrp/sil-kit + local-branch: main-mirror + remote-branch: main + sync-option: pull-branch diff --git a/.github/workflows/sil-kit-ci.yml b/.github/workflows/sil-kit-ci.yml new file mode 100644 index 000000000..54a8f5ee1 --- /dev/null +++ b/.github/workflows/sil-kit-ci.yml @@ -0,0 +1,85 @@ +name: "CI for Pull Requests" + +on: + pull_request: + branches: [ 'main' ] + + push: + branches: [ 'main' ] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + check-licenses: + name: License checks for SIL Kit sources + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + with: + submodules: false + - name: Install Dependencies + id: dep-install + run: | + sudo apt install licensecheck + + - name: Check Licenses + id: license-check + run: | + sh ./SilKit/ci/check_licenses.sh + shell: bash + + check-run-builds: + runs-on: ubuntu-22.04 + outputs: + run_builds: ${{ steps.build_check.outputs.run_builds }} + steps: + - uses: actions/checkout@v4 + with: + submodules: false + - name: Check if build CI should run + id: build_check + run: | + if [[ ${{ github.event_name }} == 'push' ]];then \ + echo "run_builds=true" >> $GITHUB_OUTPUT; \ + else \ + python3 ./SilKit/ci/check_files_changed.py ${{ github.repository }} ${{ github.event.number }}; \ + fi + + clang14-tsan: + name: Thread Sanitizer Tests + needs: [check-licenses, check-run-builds] + uses: ./.github/workflows/linux-tsan.yml + with: + run_build: ${{ needs.check-run-builds.outputs.run_builds == 'true' }} + + clang14-ubsan: + name: Undefined Behavior Sanitizer Tests + needs: [check-licenses, check-run-builds] + uses: ./.github/workflows/linux-ubsan.yml + with: + run_build: ${{ needs.check-run-builds.outputs.run_builds == 'true' }} + + clang14-asan: + name: Address Sanitizer Tests + needs: [check-licenses, check-run-builds] + uses: ./.github/workflows/linux-asan.yml + with: + run_build: ${{ needs.check-run-builds.outputs.run_builds == 'true' }} + + ubuntu-release-builds: + uses: ./.github/workflows/build-linux.yml + needs: [check-licenses, check-run-builds] + with: + do_package: ${{ github.event_name == 'push' && true || false }} + retention_days: ${{ github.event_name == 'push' && 90 || 14 }} + run_build: ${{ needs.check-run-builds.outputs.run_builds == 'true' }} + + windows-release-builds: + uses: ./.github/workflows/build-win.yml + needs: [check-licenses, check-run-builds] + with: + do_package: ${{ github.event_name == 'push' && true || false }} + retention_days: ${{ github.event_name == 'push' && 90 || 14 }} + run_build: ${{ needs.check-run-builds.outputs.run_builds == 'true' }} diff --git a/.gitignore b/.gitignore index 7d591f477..0f7e424df 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ # compile commands for clangd support compile_commands.json # ignore cmake-generated path directories -build*/ +^build*/ _build*/ install*/ _install*/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 91de3c1a1..492bc2bd5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -61,6 +61,7 @@ if(SILKIT_BUILD_LINUX_PACKAGE) message(NOTICE " * SILKIT_BUILD_DASHBOARD OFF") set(SILKIT_BUILD_DASHBOARD OFF CACHE BOOL "Force SILKIT_BUILD_DASHBOARD OFF due to SILKIT_BUILD_REPRODUCIBLE" FORCE) + add_subdirectory(docs/man) endif() @@ -73,6 +74,9 @@ add_compile_definitions( ASIO_DISABLE_VISIBILITY=1 ) +if(MINGW AND (CMAKE_CXX_COMPILER_ID MATCHES GNU OR CMAKE_CXX_COMPILER_ID MATCHES Clang)) + add_compile_options("-Wa,-mbig-obj") +endif() list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake ${CMAKE_CURRENT_LIST_DIR}/SilKit/cmake) include(SilKitInstall) @@ -187,6 +191,7 @@ if(SILKIT_INSTALL_SOURCE) PATTERN *.cxx PATTERN *.c PATTERN *.rc + PATTERN *.map PATTERN *.h PATTERN *.hpp PATTERN *.hpp.in diff --git a/CMakePresets.json b/CMakePresets.json index 729fc8e6a..fdf10b20f 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -53,6 +53,15 @@ "SILKIT_CMAKE_PRESET_BUILD_TYPE": "Release" } }, + { + "name": "linux-relwithdebinfo", + "displayName": "Linux Release with Debug Info", + "description": "Target the Windows Subsystem for Linux (WSL) or a remote Linux system.", + "inherits": "linux-base", + "environment": { + "SILKIT_CMAKE_PRESET_BUILD_TYPE": "RelWithDebInfo" + } + }, { "name": "windows-base", "description": "Target Windows with the Visual Studio development environment.", @@ -88,12 +97,21 @@ { "name": "x64-release", "displayName": "x64 Release", - "description": "Target Windows (64-bit) with the Visual Studio development environment. (RelWithDebInfo)", + "description": "Target Windows (64-bit) with the Visual Studio development environment. (Release)", "inherits": "x64-debug", "environment": { "SILKIT_CMAKE_PRESET_BUILD_TYPE": "Release" } }, + { + "name": "x64-relwithdebinfo", + "displayName": "x64 Release with Debug Info", + "description": "Target Windows (64-bit) with the Visual Studio development environment. (RelWithDebInfo)", + "inherits": "x64-debug", + "environment": { + "SILKIT_CMAKE_PRESET_BUILD_TYPE": "RelWithDebInfo" + } + }, { "name": "x86-debug", "displayName": "x86 Debug", @@ -111,12 +129,21 @@ { "name": "x86-release", "displayName": "x86 Release", - "description": "Target Windows (32-bit) with the Visual Studio development environment. (RelWithDebInfo)", + "description": "Target Windows (32-bit) with the Visual Studio development environment. (Release)", "inherits": "x86-debug", "environment": { "SILKIT_CMAKE_PRESET_BUILD_TYPE": "Release" } }, + { + "name": "x86-relwithdebinfo", + "displayName": "x86 Release with Debug Info", + "description": "Target Windows (32-bit) with the Visual Studio development environment. (RelWithDebInfo)", + "inherits": "x86-debug", + "environment": { + "SILKIT_CMAKE_PRESET_BUILD_TYPE": "RelWithDebInfo" + } + }, @@ -378,6 +405,10 @@ "name": "vs140-x86-release", "inherits": [ "mixin-release", "vs140-x86-debug" ] }, + { + "name": "vs140-x86-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "vs140-x86-debug" ] + }, { "name": "vs140-x64-debug", "inherits": [ "mixin-arch-x64", "vs140-x86-debug" ] @@ -386,6 +417,10 @@ "name": "vs140-x64-release", "inherits": [ "mixin-release", "vs140-x64-debug" ] }, + { + "name": "vs140-x64-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "vs140-x64-debug" ] + }, { "name": "vs141-x86-debug", @@ -395,6 +430,10 @@ "name": "vs141-x86-release", "inherits": [ "mixin-release", "vs141-x86-debug" ] }, + { + "name": "vs141-x86-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "vs141-x86-debug" ] + }, { "name": "vs141-x64-debug", "inherits": [ "mixin-arch-x64", "vs141-x86-debug" ] @@ -403,6 +442,10 @@ "name": "vs141-x64-release", "inherits": [ "mixin-release", "vs141-x64-debug" ] }, + { + "name": "vs141-x64-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "vs141-x64-debug" ] + }, { "name": "gcc7-debug", @@ -424,6 +467,11 @@ "inherits": [ "mixin-release", "gcc8-debug", "mixin-build-docs" ] }, + { + "name": "gcc8-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "gcc8-debug", "mixin-build-docs" ] + }, + { "name": "gcc9-debug", "inherits": [ "mixin-posix", "mixin-dirs", "mixin-ninja", "mixin-debug", "mixin-gcc9" ] @@ -432,6 +480,10 @@ "name": "gcc9-release", "inherits": [ "mixin-release", "gcc9-debug", "mixin-build-docs" ] }, + { + "name": "gcc9-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "gcc9-debug", "mixin-build-docs" ] + }, { "name": "clang10-debug", "inherits": [ "mixin-clang10", "gcc9-debug" ] @@ -448,6 +500,10 @@ "name": "clang12-release", "inherits": [ "mixin-release", "clang12-debug" ] }, + { + "name": "clang12-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "clang12-debug" ] + }, { "name": "clang14-debug", "inherits": [ "mixin-clang14", "gcc9-debug" ] @@ -456,6 +512,10 @@ "name": "clang14-release", "inherits": [ "mixin-release", "clang14-debug" ] }, + { + "name": "clang14-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "clang14-debug" ] + }, { "name": "clang15-debug", @@ -465,6 +525,10 @@ "name": "clang15-release", "inherits": [ "mixin-release", "clang15-debug" ] }, + { + "name": "clang15-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "clang15-debug" ] + }, { "name": "clang-debug", @@ -474,6 +538,10 @@ "name": "clang-release", "inherits": [ "mixin-release", "clang-debug" ] }, + { + "name": "clang-relwithdebinfo", + "inherits": [ "mixin-relwithdebinfo", "clang-debug" ] + }, { "name": "clang12-asan-debug", @@ -571,6 +639,11 @@ "inherits": "linux-base", "configurePreset": "linux-release" }, + { + "name": "linux-relwithdebinfo", + "inherits": "linux-base", + "configurePreset": "linux-relwithdebinfo" + }, { "displayName": "1: x64-debug", "name": "x64-debug", @@ -629,6 +702,10 @@ "name": "gcc8-release", "configurePreset": "gcc8-release" }, + { + "name": "gcc8-relwithdebinfo", + "configurePreset": "gcc8-relwithdebinfo" + }, { "name": "gcc9-debug", "configurePreset": "gcc9-debug" @@ -637,6 +714,10 @@ "name": "gcc9-release", "configurePreset": "gcc9-release" }, + { + "name": "gcc9-relwithdebinfo", + "configurePreset": "gcc9-relwithdebinfo" + }, { "name": "clang10-debug", @@ -656,6 +737,10 @@ "name": "clang12-release", "configurePreset": "clang12-release" }, + { + "name": "clang12-relwithdebinfo", + "configurePreset": "clang12-relwithdebinfo" + }, { "name": "clang14-debug", @@ -665,6 +750,10 @@ "name": "clang14-release", "configurePreset": "clang14-release" }, + { + "name": "clang14-relwithdebinfo", + "configurePreset": "clang14-relwithdebinfo" + }, { "name": "clang15-debug", "configurePreset": "clang15-debug" @@ -673,6 +762,10 @@ "name": "clang15-release", "configurePreset": "clang15-release" }, + { + "name": "clang15-relwithdebinfo", + "configurePreset": "clang15-relwithdebinfo" + }, { "name": "clang-debug", "configurePreset": "clang-debug" @@ -681,6 +774,10 @@ "name": "clang-release", "configurePreset": "clang-release" }, + { + "name": "clang-relwithdebinfo", + "configurePreset": "clang-relwithdebinfo" + }, { "name": "clang12-asan-debug", "configurePreset": "clang12-asan-debug" @@ -757,6 +854,11 @@ "inherits": "linux-base", "configurePreset": "linux-release" }, + { + "name": "linux-relwithdebinfo", + "inherits": "linux-base", + "configurePreset": "linux-relwithdebinfo" + }, { "name": "x64-debug", "inherits": "windows-base", @@ -785,6 +887,10 @@ "name": "vs140-x86-release", "configurePreset": "vs140-x86-release" }, + { + "name": "vs140-x86-relwithdebinfo", + "configurePreset": "vs140-x86-relwithdebinfo" + }, { "name": "vs140-x64-debug", "configurePreset": "vs140-x64-debug" @@ -793,6 +899,10 @@ "name": "vs140-x64-release", "configurePreset": "vs140-x64-release" }, + { + "name": "vs140-x64-relwithdebinfo", + "configurePreset": "vs140-x64-relwithdebinfo" + }, { "name": "vs141-x86-debug", "configurePreset": "vs141-x86-debug" @@ -801,6 +911,10 @@ "name": "vs141-x86-release", "configurePreset": "vs141-x86-release" }, + { + "name": "vs141-x86-relwithdebinfo", + "configurePreset": "vs141-x86-relwithdebinfo" + }, { "name": "vs141-x64-debug", "configurePreset": "vs141-x64-debug" @@ -809,6 +923,10 @@ "name": "vs141-x64-release", "configurePreset": "vs141-x64-release" }, + { + "name": "vs141-x64-relwithdebinfo", + "configurePreset": "vs141-x64-relwithdebinfo" + }, { "name": "gcc7-debug", @@ -827,6 +945,10 @@ "name": "gcc8-release", "configurePreset": "gcc8-release" }, + { + "name": "gcc8-relwithdebinfo", + "configurePreset": "gcc8-relwithdebinfo" + }, { "name": "gcc9-debug", "configurePreset": "gcc9-debug" @@ -835,6 +957,10 @@ "name": "gcc9-release", "configurePreset": "gcc9-release" }, + { + "name": "gcc9-relwithdebinfo", + "configurePreset": "gcc9-relwithdebinfo" + }, { "name": "clang10-debug", @@ -854,6 +980,10 @@ "name": "clang12-release", "configurePreset": "clang12-release" }, + { + "name": "clang12-relwithdebinfo", + "configurePreset": "clang12-relwithdebinfo" + }, { "name": "clang14-debug", @@ -863,6 +993,10 @@ "name": "clang14-release", "configurePreset": "clang14-release" }, + { + "name": "clang14-relwithdebinfo", + "configurePreset": "clang14-relwithdebinfo" + }, { "name": "clang15-debug", @@ -872,6 +1006,10 @@ "name": "clang15-release", "configurePreset": "clang15-release" }, + { + "name": "clang15-relwithdebinfo", + "configurePreset": "clang15-relwithdebinfo" + }, { "name": "clang-debug", "configurePreset": "clang-debug" @@ -880,6 +1018,10 @@ "name": "clang-release", "configurePreset": "clang-release" }, + { + "name": "clang-relwithdebinfo", + "configurePreset": "clang-relwithdebinfo" + }, { "name": "clang12-asan-debug", "configurePreset": "clang12-asan-debug" diff --git a/Demos/Benchmark/BenchmarkDemo.cpp b/Demos/Benchmark/BenchmarkDemo.cpp index c9a4b230a..4b14f1b0f 100644 --- a/Demos/Benchmark/BenchmarkDemo.cpp +++ b/Demos/Benchmark/BenchmarkDemo.cpp @@ -79,7 +79,7 @@ void PrintUsage(const std::string& executableName) struct BenchmarkConfig { uint32_t numberOfSimulationRuns = 4; - std::chrono::seconds simulationDuration = 1s; + std::chrono::seconds simulationDuration = 1s; uint32_t numberOfParticipants = 2; uint32_t messageCount = 50; uint32_t messageSizeInBytes = 1000; @@ -94,12 +94,8 @@ bool Parse(int argc, char** argv, BenchmarkConfig& config) std::vector args; std::copy((argv + 1), (argv + argc), std::back_inserter(args)); - auto asNum = [](const auto& str) { - return static_cast(std::stoul(str)); - }; - auto asStr = [](auto& a) { - return std::string{a}; - }; + auto asNum = [](const auto& str) { return static_cast(std::stoul(str)); }; + auto asStr = [](auto& a) { return std::string{a}; }; // test and remove the flag from args, returns true if flag was present auto consumeFlag = [&args](const auto& namedOption) { @@ -204,7 +200,9 @@ bool Parse(int argc, char** argv, BenchmarkConfig& config) case 2: config.simulationDuration = std::chrono::seconds(asNum(args.at(1))); // [[fallthrough]] - case 1: config.numberOfSimulationRuns = asNum(args.at(0)); break; + case 1: + config.numberOfSimulationRuns = asNum(args.at(0)); + break; default: if (haveUserOptions) { @@ -263,7 +261,7 @@ uint32_t relateParticipant(uint32_t idx, uint32_t numberOfParticipants) } else { - return idx+1; + return idx + 1; } } @@ -293,7 +291,7 @@ void ParticipantsThread(std::shared_ptrCreateDataPublisher("PubCtrl1", dataSpec, 0); participant->CreateDataSubscriber("SubCtrl1", matchingDataSpec, [&messageCounter](auto*, auto&) { // this is handled in I/O thread, so no data races on counter. @@ -301,27 +299,25 @@ void ParticipantsThread(std::shared_ptrSetSimulationStepHandler( - [=, &publisher](std::chrono::nanoseconds now, const auto /*duration*/) { - if (now > benchmark.simulationDuration) - { - lifecycleService->Stop("Simulation done"); - } + timeSyncService->SetSimulationStepHandler([=, &publisher](std::chrono::nanoseconds now, const auto /*duration*/) { + if (now > benchmark.simulationDuration) + { + lifecycleService->Stop("Simulation done"); + } - if (isVerbose) - { - const auto simulationDurationInNs = - std::chrono::duration_cast(benchmark.simulationDuration); - const auto durationOfOneSimulationPercentile = simulationDurationInNs / 20; + if (isVerbose) + { + const auto simulationDurationInNs = + std::chrono::duration_cast(benchmark.simulationDuration); + const auto durationOfOneSimulationPercentile = simulationDurationInNs / 20; - if (now % durationOfOneSimulationPercentile < stepSize) - { - std::cout << "."; - } + if (now % durationOfOneSimulationPercentile < stepSize) + { + std::cout << "."; } - PublishMessages(publisher, benchmark.messageCount, benchmark.messageSizeInBytes); - }, - stepSize); + } + PublishMessages(publisher, benchmark.messageCount, benchmark.messageSizeInBytes); + }, stepSize); auto lifecycleFuture = lifecycleService->StartLifecycle(); lifecycleFuture.get(); @@ -408,7 +404,7 @@ int main(int argc, char** argv) registry->StartListening(benchmark.registryUri); std::vector messageCounts; - std::vector measuredRealDurations; + std::vector measuredRealDurations; for (uint32_t simulationRun = 1; simulationRun <= benchmark.numberOfSimulationRuns; simulationRun++) { @@ -451,15 +447,13 @@ int main(int argc, char** argv) auto endTimestamp = std::chrono::high_resolution_clock::now(); measuredRealDurations.emplace_back(endTimestamp - startTimestamp); auto totalCount = std::accumulate(counters.begin(), counters.end(), size_t{0}); - messageCounts.emplace_back(totalCount); + messageCounts.emplace_back(totalCount); std::cout << " " << measuredRealDurations.back() << std::endl; } std::vector measuredRealDurationsSeconds(measuredRealDurations.size()); std::transform(measuredRealDurations.begin(), measuredRealDurations.end(), measuredRealDurationsSeconds.begin(), - [](auto d) { - return static_cast(d.count() / 1e9); - }); + [](auto d) { return static_cast(d.count() / 1e9); }); const auto averageDuration = mean_and_error(measuredRealDurationsSeconds); diff --git a/Demos/Benchmark/LatencyDemo.cpp b/Demos/Benchmark/LatencyDemo.cpp index 9cfbcfdb8..3f74cd750 100644 --- a/Demos/Benchmark/LatencyDemo.cpp +++ b/Demos/Benchmark/LatencyDemo.cpp @@ -85,12 +85,8 @@ bool Parse(int argc, char** argv, BenchmarkConfig& config) std::vector args; std::copy((argv + 1), (argv + argc), std::back_inserter(args)); - auto asNum = [](const auto& str) { - return static_cast(std::stoul(str)); - }; - auto asStr = [](auto& a) { - return std::string{a}; - }; + auto asNum = [](const auto& str) { return static_cast(std::stoul(str)); }; + auto asStr = [](auto& a) { return std::string{a}; }; // test and remove the flag from args, returns true if flag was present auto consumeFlag = [&args](const auto& namedOption) { @@ -188,7 +184,9 @@ bool Parse(int argc, char** argv, BenchmarkConfig& config) case 2: config.messageSizeInBytes = asNum(args.at(1)); // [[fallthrough]] - case 1: config.messageCount = asNum(args.at(0)); break; + case 1: + config.messageCount = asNum(args.at(0)); + break; default: if (haveUserOptions) { @@ -245,7 +243,8 @@ void PrintParameters(BenchmarkConfig benchmark) << std::endl << "Running simulations with the following parameters:" << std::endl << std::endl - << std::left << std::setw(38) << "- Is Receiver: " << (benchmark.isReceiver ? "True" : "False") << std::endl + << std::left << std::setw(38) << "- Is Receiver: " << (benchmark.isReceiver ? "True" : "False") + << std::endl << std::left << std::setw(38) << "- Total message count: " << benchmark.messageCount << std::endl << std::left << std::setw(38) << "- Message size (bytes): " << benchmark.messageSizeInBytes << std::endl << std::left << std::setw(38) << "- Registry URI: " << benchmark.registryUri << std::endl @@ -315,38 +314,39 @@ int main(int argc, char** argv) std::string topicPub = benchmark.isReceiver ? "Pong" : "Ping"; std::string topicSub = benchmark.isReceiver ? "Ping" : "Pong"; auto publisher = participant->CreateDataPublisher("PubCtrl1", {topicPub, {}}, 1); - participant->CreateDataSubscriber( - "SubCtrl1", {topicSub, {}}, - [data, publisher, benchmark, &sendCount, &allSent, &allSentPromise, + participant->CreateDataSubscriber("SubCtrl1", {topicSub, {}}, + [data, publisher, benchmark, &sendCount, &allSent, &allSentPromise, - &measuredRoundtrips, &sendTime, &startTimestamp](auto*, auto&) { - if (!allSent) + &measuredRoundtrips, &sendTime, &startTimestamp](auto*, auto&) { + if (!allSent) + { + if (!benchmark.isReceiver) { - if (!benchmark.isReceiver) + if (sendCount == 0) { - if (sendCount == 0) - { - startTimestamp = std::chrono::high_resolution_clock::now(); // Initial receive: Start runtime measurement - } - else - { - measuredRoundtrips.push_back(std::chrono::high_resolution_clock::now() - sendTime); - } - sendTime = std::chrono::high_resolution_clock::now(); + startTimestamp = + std::chrono::high_resolution_clock::now(); // Initial receive: Start runtime measurement } - publisher->Publish(data); - sendCount++; - if (benchmark.isReceiver && (benchmark.messageCount <= 20 || sendCount % (benchmark.messageCount / 20) == 0)) + else { - std::cout << "."; - } - if (sendCount >= benchmark.messageCount+1) // Initial publish has no timing, use +1 - { - allSentPromise.set_value(); - allSent = true; + measuredRoundtrips.push_back(std::chrono::high_resolution_clock::now() - sendTime); } + sendTime = std::chrono::high_resolution_clock::now(); + } + publisher->Publish(data); + sendCount++; + if (benchmark.isReceiver + && (benchmark.messageCount <= 20 || sendCount % (benchmark.messageCount / 20) == 0)) + { + std::cout << "."; } - }); + if (sendCount >= benchmark.messageCount + 1) // Initial publish has no timing, use +1 + { + allSentPromise.set_value(); + allSent = true; + } + } + }); if (!benchmark.isReceiver) // Initial publish without timing { @@ -371,13 +371,13 @@ int main(int argc, char** argv) allDonePublisher->Publish(std::vector{0}); } participant->CreateDataSubscriber("SubCtrl2", {topicSubAllDone, {}}, - [&syncParticipants, benchmark, allDonePublisher](auto*, auto&) { - if (!benchmark.isReceiver) - { - allDonePublisher->Publish(std::vector{0}); - } - syncParticipants.set_value(); - }); + [&syncParticipants, benchmark, allDonePublisher](auto*, auto&) { + if (!benchmark.isReceiver) + { + allDonePublisher->Publish(std::vector{0}); + } + syncParticipants.set_value(); + }); auto syncParticipantsFuture = syncParticipants.get_future(); syncParticipantsFuture.wait(); std::cout << "... done." << std::endl; @@ -394,8 +394,9 @@ int main(int argc, char** argv) std::vector measuredLatencySeconds(measuredRoundtrips.size()); std::transform(measuredRoundtrips.begin(), measuredRoundtrips.end(), measuredLatencySeconds.begin(), [](auto d) { - return static_cast(d.count() / 1.e3 * 0.5); // Convert to microseconds, factor 0.5 for latency from roundtrip - }); + return static_cast(d.count() / 1.e3 + * 0.5); // Convert to microseconds, factor 0.5 for latency from roundtrip + }); const auto averageLatency = mean_and_error(measuredLatencySeconds); std::ostringstream averageLatencyWithUnit; @@ -417,16 +418,20 @@ int main(int argc, char** argv) durationWithUnit.precision(3); durationWithUnit << durationSeconds << " s"; - std::cout << std::setw(38) << "- Realtime duration (runtime): " << std::setw(6) << durationWithUnit.str() << std::endl - << std::setw(38) << "- Throughput (data size/runtime): " << std::setw(6) << throughputWithUnit.str() << std::endl - << std::setw(38) << "- Latency: " << std::setw(6) << averageLatencyWithUnit.str() << " +/- " << averageLatency.second << std::endl + std::cout << std::setw(38) << "- Realtime duration (runtime): " << std::setw(6) << durationWithUnit.str() + << std::endl + << std::setw(38) << "- Throughput (data size/runtime): " << std::setw(6) << throughputWithUnit.str() + << std::endl + << std::setw(38) << "- Latency: " << std::setw(6) << averageLatencyWithUnit.str() << " +/- " + << averageLatency.second << std::endl << std::endl; if (benchmark.writeCsv != "") { std::stringstream csvHeader; csvHeader << "# SilKitBenchmarkDemo, SIL Kit Version " << SilKit::Version::String(); - const auto csvColumns = "messageSize; messageCount; runtime(s); throughput(MiB/s); latency(us); latency_err"; + const auto csvColumns = + "messageSize; messageCount; runtime(s); throughput(MiB/s); latency(us); latency_err"; std::fstream csvFile; csvFile.open(benchmark.writeCsv, std::ios_base::in | std::ios_base::out); // Try to open bool csvValid{true}; @@ -453,10 +458,9 @@ int main(int argc, char** argv) { // Append data csvFile.seekp(0, std::ios_base::end); - csvFile << benchmark.messageSizeInBytes << ";" << benchmark.messageCount << ";" - << durationSeconds << ";" - << throughput << ";" - << averageLatency.first << ";" << averageLatency.second << std::endl; + csvFile << benchmark.messageSizeInBytes << ";" << benchmark.messageCount << ";" << durationSeconds + << ";" << throughput << ";" << averageLatency.first << ";" << averageLatency.second + << std::endl; } csvFile.close(); } diff --git a/Demos/Benchmark/msg-size-scaling/Readme.md b/Demos/Benchmark/msg-size-scaling/Readme.md index f1f7e7250..876c2ea2b 100644 --- a/Demos/Benchmark/msg-size-scaling/Readme.md +++ b/Demos/Benchmark/msg-size-scaling/Readme.md @@ -1,23 +1,23 @@ - - -Message size scaling helper scripts -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Collect timings for different message sizes and generate a plot with the results. -Run in a MinGW console with ``./benchmark.sh ``. - -- ``run-bench-msg-size-scaling.sh``: - Usage: ``./run-bench-msg-size-scaling.sh []`` - Starts a given SilKitDemoBenchmark executable with messages sizes from 1B to 100kB and saves the timings in a - given csv file. Optionally accepts a SIL Kit configuration file - -- ``benchmark.sh``: - Needs the path to the SilKitDemoBenchmark as input argument. Uses ``run-bench-msg-size-scaling.sh`` to run batches - of SilKitDemoBenchmark w/wo DomainSockets and creates a result plot. - -- ``plot-msg-size-scaling.gp``: - This gnupot script plots the results for throughput, message rate, and speedup to ``result-msg-size-scaling.pdf``. + + +Message size scaling helper scripts +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Collect timings for different message sizes and generate a plot with the results. +Run in a MinGW console with ``./benchmark.sh ``. + +- ``run-bench-msg-size-scaling.sh``: + Usage: ``./run-bench-msg-size-scaling.sh []`` + Starts a given SilKitDemoBenchmark executable with messages sizes from 1B to 100kB and saves the timings in a + given csv file. Optionally accepts a SIL Kit configuration file + +- ``benchmark.sh``: + Needs the path to the SilKitDemoBenchmark as input argument. Uses ``run-bench-msg-size-scaling.sh`` to run batches + of SilKitDemoBenchmark w/wo DomainSockets and creates a result plot. + +- ``plot-msg-size-scaling.gp``: + This gnupot script plots the results for throughput, message rate, and speedup to ``result-msg-size-scaling.pdf``. diff --git a/Demos/Benchmark/msg-size-scaling/benchmark.sh b/Demos/Benchmark/msg-size-scaling/benchmark.sh index e722148ed..8ccd5aaef 100644 --- a/Demos/Benchmark/msg-size-scaling/benchmark.sh +++ b/Demos/Benchmark/msg-size-scaling/benchmark.sh @@ -1,21 +1,21 @@ -#!/bin/sh - -# SPDX-FileCopyrightText: 2023 Vector Informatik GmbH -# -# SPDX-License-Identifier: MIT - -echo 'Cleanup' -rm ./result-msg-size-scaling.csv -rm ./result-msg-size-scaling-tcp.csv -rm ./result-msg-size-scaling.pdf - -EXE=$1 - -echo 'Run benchmarks with domain sockets ...' -./run-bench-msg-size-scaling.sh $1 ./result-msg-size-scaling.csv - -echo 'Run benchmarks with TCP ...' -./run-bench-msg-size-scaling.sh $1 ./result-msg-size-scaling-tcp.csv ./SilKitConfig_DemoBenchmark_DomainSockets_Off.yaml - -echo 'Create plots...' -gnuplot plot-msg-size-scaling.gp +#!/bin/sh + +# SPDX-FileCopyrightText: 2023 Vector Informatik GmbH +# +# SPDX-License-Identifier: MIT + +echo 'Cleanup' +rm ./result-msg-size-scaling.csv +rm ./result-msg-size-scaling-tcp.csv +rm ./result-msg-size-scaling.pdf + +EXE=$1 + +echo 'Run benchmarks with domain sockets ...' +./run-bench-msg-size-scaling.sh $1 ./result-msg-size-scaling.csv + +echo 'Run benchmarks with TCP ...' +./run-bench-msg-size-scaling.sh $1 ./result-msg-size-scaling-tcp.csv ./SilKitConfig_DemoBenchmark_DomainSockets_Off.yaml + +echo 'Create plots...' +gnuplot plot-msg-size-scaling.gp diff --git a/Demos/Benchmark/msg-size-scaling/plot-msg-size-scaling.gp b/Demos/Benchmark/msg-size-scaling/plot-msg-size-scaling.gp index fadefd2a4..a2c48a2e4 100644 --- a/Demos/Benchmark/msg-size-scaling/plot-msg-size-scaling.gp +++ b/Demos/Benchmark/msg-size-scaling/plot-msg-size-scaling.gp @@ -1,49 +1,49 @@ -# Teminal and output -set terminal pdfcairo font ',11' size 4.5,9 - -fres = "result-msg-size-scaling" -fres_csv = "result-msg-size-scaling.csv" -fres_tcp_csv = "result-msg-size-scaling-tcp.csv" - -set output fres.".pdf" -set datafile separator ";" - -version=system("head -1 ".fres_csv." | cut -c3-") -numruns=system("sed '3q;d' ".fres_csv." | awk -F ';' '{print $1}'") -participants=system("sed '3q;d' ".fres_csv." | awk -F ';' '{print $2}'") -msgcount=system("sed '3q;d' ".fres_csv." | awk -F ';' '{print $4}'") -duration=system("sed '3q;d' ".fres_csv." | awk -F ';' '{print $5}'") - -# Common layout -set multiplot layout 3,1 title "\n\n\n\n\n\n\n\n\n" - -set label 1 "{/:Bold Message size scaling}\n\n ".version."\n--number-simulation-runs ".numruns."\n--simulation-duration ".duration."\n--number-participants ".participants."\n--message-count ".msgcount."\n--message-size "\ -at screen 0.13,0.97 left - -set auto -set xl 'Message size (kB)' offset 0,0.3 -set key t l - -# Data columns -# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -# numruns, participants, msgsize, msgcount, duration, numsent, runtime, runtime_err, throughput, throughput_err, speedup, speedup_err, msgrate, msgrate_err - -# Plot 1: Throughput -set yl 'Throughput (MiB/s)' -p fres_csv u ($3/1000):9 w l lc 1 not, '' u ($3/1000):9:10 w yerr pt 2 ps 0.8 lc 1 t 'Throughput (DomainSockets)',\ - fres_tcp_csv u ($3/1000):9 w l lc 2 not, '' u ($3/1000):9:10 w yerr pt 2 ps 0.8 lc 2 t 'Throughput (TCP)' - -unset label - -# Plot 2: Message rate -set yl 'Message rate (kilocount/s)' -p fres_csv u ($3/1000):($13/1000) w l lc 1 not, '' u ($3/1000):($13/1000):($14/1000) w yerr pt 2 ps 0.8 lc 1 t 'Message rate (DomainSockets)',\ - fres_tcp_csv u ($3/1000):($13/1000) w l lc 2 not, '' u ($3/1000):($13/1000):($14/1000) w yerr pt 2 ps 0.8 lc 2 t 'Message rate (TCP)' - -# Plot 3: Speedup -set yl 'Speedup (virtual time/runtime)' -set log y -set yr[0.1:] -p fres_csv u ($3/1000):11 w l lc 1 not, '' u ($3/1000):11:12 w yerr pt 2 ps 0.8 lc 1 t 'Speedup (DomainSockets)',\ - fres_tcp_csv u ($3/1000):11 w l lc 2 not, '' u ($3/1000):11:12 w yerr pt 2 ps 0.8 lc 2 t 'Speedup (TCP)', 1 w l lc 0 dt 2 t 'Realtime' - +# Teminal and output +set terminal pdfcairo font ',11' size 4.5,9 + +fres = "result-msg-size-scaling" +fres_csv = "result-msg-size-scaling.csv" +fres_tcp_csv = "result-msg-size-scaling-tcp.csv" + +set output fres.".pdf" +set datafile separator ";" + +version=system("head -1 ".fres_csv." | cut -c3-") +numruns=system("sed '3q;d' ".fres_csv." | awk -F ';' '{print $1}'") +participants=system("sed '3q;d' ".fres_csv." | awk -F ';' '{print $2}'") +msgcount=system("sed '3q;d' ".fres_csv." | awk -F ';' '{print $4}'") +duration=system("sed '3q;d' ".fres_csv." | awk -F ';' '{print $5}'") + +# Common layout +set multiplot layout 3,1 title "\n\n\n\n\n\n\n\n\n" + +set label 1 "{/:Bold Message size scaling}\n\n ".version."\n--number-simulation-runs ".numruns."\n--simulation-duration ".duration."\n--number-participants ".participants."\n--message-count ".msgcount."\n--message-size "\ +at screen 0.13,0.97 left + +set auto +set xl 'Message size (kB)' offset 0,0.3 +set key t l + +# Data columns +# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 +# numruns, participants, msgsize, msgcount, duration, numsent, runtime, runtime_err, throughput, throughput_err, speedup, speedup_err, msgrate, msgrate_err + +# Plot 1: Throughput +set yl 'Throughput (MiB/s)' +p fres_csv u ($3/1000):9 w l lc 1 not, '' u ($3/1000):9:10 w yerr pt 2 ps 0.8 lc 1 t 'Throughput (DomainSockets)',\ + fres_tcp_csv u ($3/1000):9 w l lc 2 not, '' u ($3/1000):9:10 w yerr pt 2 ps 0.8 lc 2 t 'Throughput (TCP)' + +unset label + +# Plot 2: Message rate +set yl 'Message rate (kilocount/s)' +p fres_csv u ($3/1000):($13/1000) w l lc 1 not, '' u ($3/1000):($13/1000):($14/1000) w yerr pt 2 ps 0.8 lc 1 t 'Message rate (DomainSockets)',\ + fres_tcp_csv u ($3/1000):($13/1000) w l lc 2 not, '' u ($3/1000):($13/1000):($14/1000) w yerr pt 2 ps 0.8 lc 2 t 'Message rate (TCP)' + +# Plot 3: Speedup +set yl 'Speedup (virtual time/runtime)' +set log y +set yr[0.1:] +p fres_csv u ($3/1000):11 w l lc 1 not, '' u ($3/1000):11:12 w yerr pt 2 ps 0.8 lc 1 t 'Speedup (DomainSockets)',\ + fres_tcp_csv u ($3/1000):11 w l lc 2 not, '' u ($3/1000):11:12 w yerr pt 2 ps 0.8 lc 2 t 'Speedup (TCP)', 1 w l lc 0 dt 2 t 'Realtime' + diff --git a/Demos/Benchmark/performance-diff/Readme.md b/Demos/Benchmark/performance-diff/Readme.md index 1edccb1b7..a416c7282 100644 --- a/Demos/Benchmark/performance-diff/Readme.md +++ b/Demos/Benchmark/performance-diff/Readme.md @@ -1,20 +1,20 @@ - - -Message size scaling helper scripts -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Compares timings for two different versions of the SilKitDemoBenchmark and calculates the performance difference. -Run in a MinGW console with -``./performance-diff.sh -The arguments are for naming the csv outputs of the SilKitDemoBenchmark1/2. - -- ``performance-diff.sh``: - Starts the given two SilKitDemoBenchmark executables and saves the timings in seperate csv files. - -- ``diff.py``: - Reads the csv results of SilKitDemoBenchmark1/2 and calculates the performance difference. - The result is printed and saved to . + + +Message size scaling helper scripts +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Compares timings for two different versions of the SilKitDemoBenchmark and calculates the performance difference. +Run in a MinGW console with +``./performance-diff.sh +The arguments are for naming the csv outputs of the SilKitDemoBenchmark1/2. + +- ``performance-diff.sh``: + Starts the given two SilKitDemoBenchmark executables and saves the timings in seperate csv files. + +- ``diff.py``: + Reads the csv results of SilKitDemoBenchmark1/2 and calculates the performance difference. + The result is printed and saved to . diff --git a/Demos/Benchmark/performance-diff/diff.py b/Demos/Benchmark/performance-diff/diff.py index b02bc32ee..38e1429c1 100644 --- a/Demos/Benchmark/performance-diff/diff.py +++ b/Demos/Benchmark/performance-diff/diff.py @@ -1,46 +1,46 @@ -# SPDX-FileCopyrightText: 2023 Vector Informatik GmbH -# -# SPDX-License-Identifier: MIT - -import pandas as pd -import sys -pd.set_option('display.max_rows', 500) -pd.set_option('display.max_columns', 500) -pd.set_option('display.width', 1000) - -print(len(sys.argv),sys.argv) - -if len(sys.argv) != 4: - print("Usage: diff.py ") - exit() - -f_old = sys.argv[1] -f_new = sys.argv[2] -f_diff = sys.argv[3] - -df_new = pd.read_csv(f_new, sep=';', index_col=False, comment='#') -df_old = pd.read_csv(f_old, sep=';', index_col=False, comment='#') - -df_new_m = df_new.iloc[:, 6::2] -df_old_m = df_old.iloc[:, 6::2] -df_avg = (df_new_m + df_old_m) / 2.0 -df_diff_percent = (df_new_m - df_old_m) / df_avg * 100.0 - -df_new_err_m = df_new.iloc[:, 7::2] -df_old_err_m = df_old.iloc[:, 7::2] -df_diff_err_percent = (df_new_err_m + df_old_err_m) / df_avg.values * 100.0 - -df_mean = df_diff_percent.mean(axis=0) - -df_mean_w_err = [] -for v,err in zip(df_mean.values, df_diff_err_percent.values[0]): - df_mean_w_err.append(v) - df_mean_w_err.append(err) - -with open(f_diff, 'a') as f: - f.write('# Average change between versions ' + f_old + ' and ' + f_new + '\n') - -df_res = pd.DataFrame([df_mean_w_err], columns=['runtime change(%)', 'err(%)', 'throughput change(%)', 'err(%)', 'speedup change(%)', 'err(%)', 'messageRate change(%)', 'err(%)']) -print(df_res) -df_res.to_csv(path_or_buf=f_diff, sep=';', index=False) - +# SPDX-FileCopyrightText: 2023 Vector Informatik GmbH +# +# SPDX-License-Identifier: MIT + +import pandas as pd +import sys +pd.set_option('display.max_rows', 500) +pd.set_option('display.max_columns', 500) +pd.set_option('display.width', 1000) + +print(len(sys.argv),sys.argv) + +if len(sys.argv) != 4: + print("Usage: diff.py ") + exit() + +f_old = sys.argv[1] +f_new = sys.argv[2] +f_diff = sys.argv[3] + +df_new = pd.read_csv(f_new, sep=';', index_col=False, comment='#') +df_old = pd.read_csv(f_old, sep=';', index_col=False, comment='#') + +df_new_m = df_new.iloc[:, 6::2] +df_old_m = df_old.iloc[:, 6::2] +df_avg = (df_new_m + df_old_m) / 2.0 +df_diff_percent = (df_new_m - df_old_m) / df_avg * 100.0 + +df_new_err_m = df_new.iloc[:, 7::2] +df_old_err_m = df_old.iloc[:, 7::2] +df_diff_err_percent = (df_new_err_m + df_old_err_m) / df_avg.values * 100.0 + +df_mean = df_diff_percent.mean(axis=0) + +df_mean_w_err = [] +for v,err in zip(df_mean.values, df_diff_err_percent.values[0]): + df_mean_w_err.append(v) + df_mean_w_err.append(err) + +with open(f_diff, 'a') as f: + f.write('# Average change between versions ' + f_old + ' and ' + f_new + '\n') + +df_res = pd.DataFrame([df_mean_w_err], columns=['runtime change(%)', 'err(%)', 'throughput change(%)', 'err(%)', 'speedup change(%)', 'err(%)', 'messageRate change(%)', 'err(%)']) +print(df_res) +df_res.to_csv(path_or_buf=f_diff, sep=';', index=False) + diff --git a/Demos/CMakeLists.txt b/Demos/CMakeLists.txt index 9078fdbd7..86f910101 100755 --- a/Demos/CMakeLists.txt +++ b/Demos/CMakeLists.txt @@ -124,6 +124,11 @@ macro(make_silkit_demo executableName demoSourceFile) SilKit::SilKit Threads::Threads ) + + if(MSVC) + target_compile_options(${executableName} PRIVATE /wd4996) + endif() + add_dependencies(Demos ${executableName}) set(demo_list "${demo_list} ${executableName}" PARENT_SCOPE) endmacro() @@ -139,6 +144,7 @@ add_subdirectory(Lin) add_subdirectory(PubSub) add_subdirectory(Rpc) add_subdirectory(Benchmark) +add_subdirectory(NetworkSimulator) message(STATUS "Demos available: ${demo_list}") ####################################################################################################################### diff --git a/Demos/Can/CanDemo.cpp b/Demos/Can/CanDemo.cpp index 4644e35a7..5cef427fd 100644 --- a/Demos/Can/CanDemo.cpp +++ b/Demos/Can/CanDemo.cpp @@ -57,8 +57,7 @@ std::ostream& operator<<(std::ostream& out, nanoseconds timestamp) void FrameTransmitHandler(const CanFrameTransmitEvent& ack, ILogger* logger) { std::stringstream buffer; - buffer << ">> " << ack.status - << " for CAN frame with timestamp=" << ack.timestamp + buffer << ">> " << ack.status << " for CAN frame with timestamp=" << ack.timestamp << " and userContext=" << ack.userContext; logger->Info(buffer.str()); } @@ -67,15 +66,14 @@ void FrameHandler(const CanFrameEvent& frameEvent, ILogger* logger) { std::string payload(frameEvent.frame.dataField.begin(), frameEvent.frame.dataField.end()); std::stringstream buffer; - buffer << ">> CAN frame: canId=" << frameEvent.frame.canId - << " timestamp=" << frameEvent.timestamp - << " \"" << payload << "\""; + buffer << ">> CAN frame: canId=" << frameEvent.frame.canId << " timestamp=" << frameEvent.timestamp << " \"" + << payload << "\""; logger->Info(buffer.str()); } void SendFrame(ICanController* controller, ILogger* logger) { - CanFrame canFrame {}; + CanFrame canFrame{}; canFrame.canId = 3; canFrame.flags |= static_cast(CanFrameFlag::Fdf) // FD Format Indicator | static_cast(CanFrameFlag::Brs); // Bit Rate Switch (for FD Format only) @@ -94,7 +92,7 @@ void SendFrame(ICanController* controller, ILogger* logger) canFrame.dataField = payloadBytes; canFrame.dlc = static_cast(canFrame.dataField.size()); - void* const userContext = reinterpret_cast(static_cast(currentMessageId)); + void* const userContext = reinterpret_cast(static_cast(currentMessageId)); controller->SendFrame(std::move(canFrame), userContext); std::stringstream buffer; @@ -155,7 +153,8 @@ int main(int argc, char** argv) } } - auto participantConfiguration = SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); + auto participantConfiguration = + SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); auto sleepTimePerTick = 1000ms; std::cout << "Creating participant '" << participantName << "' with registry " << registryUri << std::endl; @@ -165,29 +164,21 @@ int main(int argc, char** argv) auto* logger = participant->GetLogger(); auto* canController = participant->CreateCanController("CAN1", "CAN1"); - canController->AddFrameTransmitHandler( - [logger](ICanController* /*ctrl*/, const CanFrameTransmitEvent& ack) { - FrameTransmitHandler(ack, logger); - }); + canController->AddFrameTransmitHandler([logger](ICanController* /*ctrl*/, const CanFrameTransmitEvent& ack) { + FrameTransmitHandler(ack, logger); + }); canController->AddFrameHandler( - [logger](ICanController* /*ctrl*/, const CanFrameEvent& frameEvent) { - FrameHandler(frameEvent, logger); - }); + [logger](ICanController* /*ctrl*/, const CanFrameEvent& frameEvent) { FrameHandler(frameEvent, logger); }); auto operationMode = (runSync ? OperationMode::Coordinated : OperationMode::Autonomous); auto* lifecycleService = participant->CreateLifecycleService({operationMode}); // Observe state changes - lifecycleService->SetStopHandler([]() { - std::cout << "Stop handler called" << std::endl; - }); - lifecycleService->SetShutdownHandler([]() { - std::cout << "Shutdown handler called" << std::endl; - }); - lifecycleService->SetAbortHandler([](auto lastState) { - std::cout << "Abort handler called while in state " << lastState << std::endl; - }); + lifecycleService->SetStopHandler([]() { std::cout << "Stop handler called" << std::endl; }); + lifecycleService->SetShutdownHandler([]() { std::cout << "Shutdown handler called" << std::endl; }); + lifecycleService->SetAbortHandler( + [](auto lastState) { std::cout << "Abort handler called while in state " << lastState << std::endl; }); if (runSync) { @@ -204,18 +195,19 @@ int main(int argc, char** argv) timeSyncService->SetSimulationStepHandler( [canController, logger, sleepTimePerTick](std::chrono::nanoseconds now, std::chrono::nanoseconds duration) { - std::cout << "now=" << now << ", duration=" << duration << std::endl; - SendFrame(canController, logger); - std::this_thread::sleep_for(sleepTimePerTick); - }, 5ms); + std::cout << "now=" << now << ", duration=" << duration << std::endl; + SendFrame(canController, logger); + std::this_thread::sleep_for(sleepTimePerTick); + }, + 5ms); } else { timeSyncService->SetSimulationStepHandler( [sleepTimePerTick](std::chrono::nanoseconds now, std::chrono::nanoseconds duration) { - std::cout << "now=" << now << ", duration=" << duration << std::endl; - std::this_thread::sleep_for(sleepTimePerTick); - }, 5ms); + std::cout << "now=" << now << ", duration=" << duration << std::endl; + std::this_thread::sleep_for(sleepTimePerTick); + }, 5ms); } auto finalStateFuture = lifecycleService->StartLifecycle(); @@ -238,8 +230,8 @@ int main(int argc, char** argv) workerThread = std::thread{[&]() { futureObj.get(); - while (lifecycleService->State() == ParticipantState::ReadyToRun || - lifecycleService->State() == ParticipantState::Running) + while (lifecycleService->State() == ParticipantState::ReadyToRun + || lifecycleService->State() == ParticipantState::Running) { if (participantName == "CanWriter") { @@ -255,17 +247,15 @@ int main(int argc, char** argv) canController->Start(); }); - lifecycleService->SetStartingHandler([&]() { - promiseObj.set_value(); - }); + lifecycleService->SetStartingHandler([&]() { promiseObj.set_value(); }); lifecycleService->StartLifecycle(); std::cout << "Press enter to leave the simulation..." << std::endl; std::cin.ignore(); isStopRequested = true; - if (lifecycleService->State() == ParticipantState::Running || - lifecycleService->State() == ParticipantState::Paused) + if (lifecycleService->State() == ParticipantState::Running + || lifecycleService->State() == ParticipantState::Paused) { std::cout << "User requested to stop in state " << lifecycleService->State() << std::endl; lifecycleService->Stop("User requested to stop"); diff --git a/Demos/Ethernet/EthernetDemo.cpp b/Demos/Ethernet/EthernetDemo.cpp old mode 100755 new mode 100644 index 1db45ff80..0743dfa0f --- a/Demos/Ethernet/EthernetDemo.cpp +++ b/Demos/Ethernet/EthernetDemo.cpp @@ -28,12 +28,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #include -#ifdef SILKIT_HOURGLASS -#include "silkit/hourglass/SilKit.hpp" -#include "silkit/hourglass/config/IParticipantConfiguration.hpp" -#else #include "silkit/SilKit.hpp" -#endif #include "silkit/SilKitVersion.hpp" #include "silkit/services/all.hpp" @@ -60,14 +55,14 @@ std::ostream& operator<<(std::ostream& out, std::chrono::nanoseconds timestamp) std::vector CreateFrame(const EthernetMac& destinationAddress, const EthernetMac& sourceAddress, const std::vector& payload) { - const uint16_t etherType = 0x0000; // no protocol + const uint16_t etherType = 0x0000; // no protocol std::vector raw; std::copy(destinationAddress.begin(), destinationAddress.end(), std::back_inserter(raw)); std::copy(sourceAddress.begin(), sourceAddress.end(), std::back_inserter(raw)); auto etherTypeBytes = reinterpret_cast(ðerType); - raw.push_back(etherTypeBytes[1]); // We assume our platform to be little-endian + raw.push_back(etherTypeBytes[1]); // We assume our platform to be little-endian raw.push_back(etherTypeBytes[0]); std::copy(payload.begin(), payload.end(), std::back_inserter(raw)); @@ -119,23 +114,23 @@ void FrameHandler(IEthernetController* /*controller*/, const EthernetFrameEvent& { auto frame = frameEvent.frame; auto payload = GetPayloadStringFromFrame(frame); - std::cout << ">> Ethernet frame: \"" - << payload - << "\"" << std::endl; + std::cout << ">> Ethernet frame: \"" << payload << "\"" << std::endl; } void SendFrame(IEthernetController* controller, const EthernetMac& from, const EthernetMac& to) { static int frameId = 0; std::stringstream stream; - stream << "Hello from Ethernet writer! (frameId =" << frameId++ << ")" - "----------------------------------------------------"; // ensure that the payload is long enough to constitute a valid Ethernet frame + stream + << "Hello from Ethernet writer! (frameId =" << frameId++ + << ")" + "----------------------------------------------------"; // ensure that the payload is long enough to constitute a valid Ethernet frame auto payloadString = stream.str(); std::vector payload(payloadString.size() + 1); memcpy(payload.data(), payloadString.c_str(), payloadString.size() + 1); - const auto userContext = reinterpret_cast(static_cast(frameId)); + const auto userContext = reinterpret_cast(static_cast(frameId)); auto frame = CreateFrame(to, from, payload); controller->SendFrame(EthernetFrame{frame}, userContext); @@ -198,13 +193,8 @@ int main(int argc, char** argv) } } -#ifdef SILKIT_HOURGLASS - using SilKit::Hourglass::CreateParticipant; - using SilKit::Hourglass::Config::ParticipantConfigurationFromFile; -#else using SilKit::CreateParticipant; using SilKit::Config::ParticipantConfigurationFromFile; -#endif auto participantConfiguration = ParticipantConfigurationFromFile(participantConfigurationFilename); @@ -219,15 +209,10 @@ int main(int argc, char** argv) auto* lifecycleService = participant->CreateLifecycleService({operationMode}); // Observe state changes - lifecycleService->SetStopHandler([]() { - std::cout << "Stop handler called" << std::endl; - }); - lifecycleService->SetShutdownHandler([]() { - std::cout << "Shutdown handler called" << std::endl; - }); - lifecycleService->SetAbortHandler([](auto lastState) { - std::cout << "Abort handler called while in state " << lastState << std::endl; - }); + lifecycleService->SetStopHandler([]() { std::cout << "Stop handler called" << std::endl; }); + lifecycleService->SetShutdownHandler([]() { std::cout << "Shutdown handler called" << std::endl; }); + lifecycleService->SetAbortHandler( + [](auto lastState) { std::cout << "Abort handler called while in state " << lastState << std::endl; }); if (runSync) { @@ -244,20 +229,21 @@ int main(int argc, char** argv) timeSyncService->SetSimulationStepHandler( [ethernetController, WriterMacAddr, destinationAddress = BroadcastMacAddr]( std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - std::cout << "now=" << std::chrono::duration_cast(now).count() - << "ms" << std::endl; - SendFrame(ethernetController, WriterMacAddr, destinationAddress); - std::this_thread::sleep_for(300ms); - }, 1ms); + std::cout << "now=" << std::chrono::duration_cast(now).count() << "ms" + << std::endl; + SendFrame(ethernetController, WriterMacAddr, destinationAddress); + std::this_thread::sleep_for(300ms); + }, + 1ms); } else { timeSyncService->SetSimulationStepHandler( [](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - std::cout << "now=" << std::chrono::duration_cast(now).count() - << "ms" << std::endl; - std::this_thread::sleep_for(300ms); - }, 1ms); + std::cout << "now=" << std::chrono::duration_cast(now).count() << "ms" + << std::endl; + std::this_thread::sleep_for(300ms); + }, 1ms); } auto finalStateFuture = lifecycleService->StartLifecycle(); @@ -278,8 +264,8 @@ int main(int argc, char** argv) std::cout << "Communication ready handler called for " << participantName << std::endl; workerThread = std::thread{[&]() { startHandlerFuture.get(); - while (lifecycleService->State() == ParticipantState::ReadyToRun || - lifecycleService->State() == ParticipantState::Running) + while (lifecycleService->State() == ParticipantState::ReadyToRun + || lifecycleService->State() == ParticipantState::Running) { if (participantName == "EthernetWriter") { @@ -295,17 +281,15 @@ int main(int argc, char** argv) ethernetController->Activate(); }); - lifecycleService->SetStartingHandler([&]() { - startHandlerPromise.set_value(); - }); + lifecycleService->SetStartingHandler([&]() { startHandlerPromise.set_value(); }); lifecycleService->StartLifecycle(); std::cout << "Press enter to leave the simulation..." << std::endl; std::cin.ignore(); isStopRequested = true; - if (lifecycleService->State() == ParticipantState::Running || - lifecycleService->State() == ParticipantState::Paused) + if (lifecycleService->State() == ParticipantState::Running + || lifecycleService->State() == ParticipantState::Paused) { std::cout << "User requested to stop in state " << lifecycleService->State() << std::endl; lifecycleService->Stop("User requested to stop"); diff --git a/Demos/Flexray/FlexrayDemo.cpp b/Demos/Flexray/FlexrayDemo.cpp old mode 100755 new mode 100644 index a504de7fb..c34767661 --- a/Demos/Flexray/FlexrayDemo.cpp +++ b/Demos/Flexray/FlexrayDemo.cpp @@ -46,7 +46,7 @@ std::ostream& operator<<(std::ostream& out, std::chrono::nanoseconds timestamp) return out; } -template +template void ReceiveMessage(IFlexrayController* /*controller*/, const T& t) { std::cout << ">> " << t << "\n"; @@ -58,7 +58,7 @@ struct FlexrayNode : controller{controller} , controllerConfig{std::move(config)} { - oldPocStatus.state = FlexrayPocState::DefaultConfig; + oldPocStatus.state = FlexrayPocState::DefaultConfig; } void SetStartupDelay(std::chrono::nanoseconds delay) @@ -133,8 +133,7 @@ struct FlexrayNode // prepare a friendly message as payload std::stringstream payloadStream; - payloadStream << "FlexrayFrameEvent#" << std::setw(4) << msgNumber - << "; bufferId=" << bufferIdx; + payloadStream << "FlexrayFrameEvent#" << std::setw(4) << msgNumber << "; bufferId=" << bufferIdx; auto payloadString = payloadStream.str(); std::vector payloadBytes; @@ -175,15 +174,11 @@ struct FlexrayNode void PocStatusHandler(IFlexrayController* /*controller*/, const FlexrayPocStatusEvent& pocStatus) { - std::cout << ">> POC=" << pocStatus.state - << ", Freeze=" << pocStatus.freeze - << ", Wakeup=" << pocStatus.wakeupStatus - << ", Slot=" << pocStatus.slotMode - << " @t=" << pocStatus.timestamp - << std::endl; - - if (oldPocStatus.state == FlexrayPocState::Wakeup - && pocStatus.state == FlexrayPocState::Ready) + std::cout << ">> POC=" << pocStatus.state << ", Freeze=" << pocStatus.freeze + << ", Wakeup=" << pocStatus.wakeupStatus << ", Slot=" << pocStatus.slotMode + << " @t=" << pocStatus.timestamp << std::endl; + + if (oldPocStatus.state == FlexrayPocState::Wakeup && pocStatus.state == FlexrayPocState::Ready) { std::cout << " Wakeup finished..." << std::endl; busState = MasterState::WakeupDone; @@ -305,15 +300,15 @@ int main(int argc, char** argv) if (argc >= 4) { registryUri = argv[3]; - } + } - auto participantConfiguration = SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); + auto participantConfiguration = + SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); std::cout << "Creating participant '" << participantName << "' with registry " << registryUri << std::endl; auto participant = SilKit::CreateParticipant(participantConfiguration, participantName, registryUri); auto* controller = participant->CreateFlexrayController("FlexRay1", "PowerTrain1"); - auto* lifecycleService = - participant->CreateLifecycleService({OperationMode::Coordinated}); + auto* lifecycleService = participant->CreateLifecycleService({OperationMode::Coordinated}); auto* timeSyncService = lifecycleService->CreateTimeSyncService(); std::vector bufferConfigs; @@ -365,7 +360,7 @@ int main(int argc, char** argv) config.bufferConfigs = bufferConfigs; config.clusterParams = clusterParams; - + config.nodeParams = MakeNodeParams(participantName); FlexrayNode frNode(controller, std::move(config)); @@ -380,20 +375,19 @@ int main(int argc, char** argv) } else { - std::cout << "Wrong participant name provided. Use either \"Node0\" or \"Node1\"." - << std::endl; + std::cout << "Wrong participant name provided. Use either \"Node0\" or \"Node1\"." << std::endl; return 1; } - controller->AddPocStatusHandler([&frNode](IFlexrayController* linController, - const FlexrayPocStatusEvent& pocStatusEvent) { - frNode.PocStatusHandler(linController, pocStatusEvent); + controller->AddPocStatusHandler( + [&frNode](IFlexrayController* frController, const FlexrayPocStatusEvent& pocStatusEvent) { + frNode.PocStatusHandler(frController, pocStatusEvent); }); controller->AddFrameHandler(&ReceiveMessage); controller->AddFrameTransmitHandler(&ReceiveMessage); - controller->AddWakeupHandler([&frNode](IFlexrayController* linController, - const FlexrayWakeupEvent& wakeupEvent) { - frNode.WakeupHandler(linController, wakeupEvent); + controller->AddWakeupHandler( + [&frNode](IFlexrayController* frController, const FlexrayWakeupEvent& wakeupEvent) { + frNode.WakeupHandler(frController, wakeupEvent); }); controller->AddSymbolHandler(&ReceiveMessage); controller->AddSymbolTransmitHandler(&ReceiveMessage); @@ -401,12 +395,10 @@ int main(int argc, char** argv) timeSyncService->SetSimulationStepHandler( [&frNode](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - - auto nowMs = std::chrono::duration_cast(now); - std::cout << "now=" << nowMs.count() << "ms" << std::endl; - frNode.doAction(now); - std::this_thread::sleep_for(500ms); - + auto nowMs = std::chrono::duration_cast(now); + std::cout << "now=" << nowMs.count() << "ms" << std::endl; + frNode.doAction(now); + std::this_thread::sleep_for(500ms); }, 1ms); auto finalStateFuture = lifecycleService->StartLifecycle(); diff --git a/Demos/Lin/LinDemo.cpp b/Demos/Lin/LinDemo.cpp old mode 100755 new mode 100644 index ef70b70d3..87b345583 --- a/Demos/Lin/LinDemo.cpp +++ b/Demos/Lin/LinDemo.cpp @@ -82,7 +82,8 @@ class Schedule { public: Schedule() = default; - Schedule(std::initializer_list>> tasks) + Schedule( + std::initializer_list>> tasks) { for (auto&& task : tasks) { @@ -118,8 +119,13 @@ class Schedule _timer.Set(_now + currentTask->delay, currentTask->action); } - struct Task { - Task(std::chrono::nanoseconds delay, std::function action) : delay{delay}, action{action} {} + struct Task + { + Task(std::chrono::nanoseconds delay, std::function action) + : delay{delay} + , action{action} + { + } std::chrono::nanoseconds delay; std::function action; @@ -127,7 +133,7 @@ class Schedule Timer _timer; std::vector _schedule; - std::vector::iterator _nextTask; + std::vector::iterator _nextTask; std::chrono::nanoseconds _now = 0ns; }; @@ -137,14 +143,12 @@ class LinMaster LinMaster(ILinController* controller) : controller{controller} { - schedule = { - {10ms, [this](std::chrono::nanoseconds now) { SendFrame_16(now); }}, - {20ms, [this](std::chrono::nanoseconds now) { SendFrame_17(now); }}, - {10ms, [this](std::chrono::nanoseconds now) { SendFrame_18(now); }}, - {10ms, [this](std::chrono::nanoseconds now) { SendFrame_19(now); }}, - {10ms, [this](std::chrono::nanoseconds now) { SendFrame_34(now); }}, - {10ms, [this](std::chrono::nanoseconds /*now*/) { GoToSleep(); }} - }; + schedule = {{10ms, [this](std::chrono::nanoseconds now) { SendFrame_16(now); }}, + {20ms, [this](std::chrono::nanoseconds now) { SendFrame_17(now); }}, + {10ms, [this](std::chrono::nanoseconds now) { SendFrame_18(now); }}, + {10ms, [this](std::chrono::nanoseconds now) { SendFrame_19(now); }}, + {10ms, [this](std::chrono::nanoseconds now) { SendFrame_34(now); }}, + {10ms, [this](std::chrono::nanoseconds /*now*/) { GoToSleep(); }}}; } void DoAction(std::chrono::nanoseconds now) @@ -169,7 +173,7 @@ class LinMaster frame.id = 17; frame.checksumModel = LinChecksumModel::Classic; frame.dataLength = 6; - frame.data = std::array{1,7,1,7,1,7,1,7}; + frame.data = std::array{1, 7, 1, 7, 1, 7, 1, 7}; SendFrameIfOperational(frame, LinFrameResponseType::MasterResponse); } @@ -217,8 +221,10 @@ class LinMaster { switch (frameStatusEvent.status) { - case LinFrameStatus::LIN_RX_OK: break; // good case, no need to warn - case LinFrameStatus::LIN_TX_OK: break; // good case, no need to warn + case LinFrameStatus::LIN_RX_OK: + break; // good case, no need to warn + case LinFrameStatus::LIN_TX_OK: + break; // good case, no need to warn default: std::cout << "WARNING: LIN transmission failed!" << std::endl; } @@ -268,7 +274,6 @@ class LinMaster }; - class LinSlave { public: @@ -298,21 +303,18 @@ class LinSlave UpdateTxBuffer_LinId34(linController); } - std::cout << ">> " << frameStatusEvent.frame - << " status=" << frameStatusEvent.status - << " timestamp=" << frameStatusEvent.timestamp - << std::endl; + std::cout << ">> " << frameStatusEvent.frame << " status=" << frameStatusEvent.status + << " timestamp=" << frameStatusEvent.timestamp << std::endl; } void GoToSleepHandler(ILinController* linController, const LinGoToSleepEvent& /*goToSleepEvent*/) { std::cout << "LIN Slave received go-to-sleep command; entering sleep mode." << std::endl; // wakeup in 15 ms - timer.Set(now + 15ms, - [linController](std::chrono::nanoseconds tnow) { - std::cout << "<< Wakeup pulse @" << tnow << std::endl; - linController->Wakeup(); - }); + timer.Set(now + 15ms, [linController](std::chrono::nanoseconds tnow) { + std::cout << "<< Wakeup pulse @" << tnow << std::endl; + linController->Wakeup(); + }); linController->GoToSleepInternal(); } @@ -404,7 +406,8 @@ void InitLinSlave(ILinController* linController, std::string participantName) * Main Function **************************************************************************************************/ -int main(int argc, char** argv) try +int main(int argc, char** argv) +try { if (argc < 3) { @@ -447,15 +450,10 @@ int main(int argc, char** argv) try auto* linController = participant->CreateLinController("LIN1", "LIN1"); // Observe state changes - lifecycleService->SetStopHandler([]() { - std::cout << "Stop handler called" << std::endl; - }); - lifecycleService->SetShutdownHandler([]() { - std::cout << "Shutdown handler called" << std::endl; - }); - lifecycleService->SetAbortHandler([](auto lastState) { - std::cout << "Abort handler called while in state " << lastState << std::endl; - }); + lifecycleService->SetStopHandler([]() { std::cout << "Stop handler called" << std::endl; }); + lifecycleService->SetShutdownHandler([]() { std::cout << "Shutdown handler called" << std::endl; }); + lifecycleService->SetAbortHandler( + [](auto lastState) { std::cout << "Abort handler called while in state " << lastState << std::endl; }); LinMaster master{linController}; LinSlave slave; @@ -464,27 +462,25 @@ int main(int argc, char** argv) try { linController->AddFrameStatusHandler( [&master](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master.FrameStatusHandler(linController, frameStatusEvent); - }); + master.FrameStatusHandler(linController, frameStatusEvent); + }); linController->AddWakeupHandler([&master](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - master.WakeupHandler(linController, wakeupEvent); - }); + master.WakeupHandler(linController, wakeupEvent); + }); if (runSync) { - lifecycleService->SetCommunicationReadyHandler([&participantName, linController]() { - InitLinMaster(linController, participantName); - }); + lifecycleService->SetCommunicationReadyHandler( + [&participantName, linController]() { InitLinMaster(linController, participantName); }); timeSyncService->SetSimulationStepHandler( [&master](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - auto nowMs = std::chrono::duration_cast(now); - std::cout << "now=" << nowMs.count() << "ms" << std::endl; + auto nowMs = std::chrono::duration_cast(now); + std::cout << "now=" << nowMs.count() << "ms" << std::endl; - master.DoAction(now); + master.DoAction(now); - std::this_thread::sleep_for(100ms); - }, - 1ms); + std::this_thread::sleep_for(100ms); + }, 1ms); auto lifecycleFuture = lifecycleService->StartLifecycle(); auto finalState = lifecycleFuture.get(); @@ -505,8 +501,8 @@ int main(int argc, char** argv) try InitLinMaster(linController, participantName); workerThread = std::thread{[&]() { startHandlerFuture.get(); - while (lifecycleService->State() == ParticipantState::ReadyToRun || - lifecycleService->State() == ParticipantState::Running) + while (lifecycleService->State() == ParticipantState::ReadyToRun + || lifecycleService->State() == ParticipantState::Running) { master.DoAction(now); now += 1ms; @@ -519,17 +515,15 @@ int main(int argc, char** argv) try }}; }); - lifecycleService->SetStartingHandler([&]() { - startHandlerPromise.set_value(); - }); + lifecycleService->SetStartingHandler([&]() { startHandlerPromise.set_value(); }); lifecycleService->StartLifecycle(); std::cout << "Press enter to leave the simulation..." << std::endl; std::cin.ignore(); isStopRequested = true; - if (lifecycleService->State() == ParticipantState::Running || - lifecycleService->State() == ParticipantState::Paused) + if (lifecycleService->State() == ParticipantState::Running + || lifecycleService->State() == ParticipantState::Paused) { std::cout << "User requested to stop in state " << lifecycleService->State() << std::endl; lifecycleService->Stop("User requested to stop"); @@ -546,30 +540,28 @@ int main(int argc, char** argv) try { linController->AddFrameStatusHandler( [&slave](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - slave.FrameStatusHandler(linController, frameStatusEvent); - }); + slave.FrameStatusHandler(linController, frameStatusEvent); + }); linController->AddGoToSleepHandler( [&slave](ILinController* linController, const LinGoToSleepEvent& goToSleepEvent) { - slave.GoToSleepHandler(linController, goToSleepEvent); - }); + slave.GoToSleepHandler(linController, goToSleepEvent); + }); linController->AddWakeupHandler([&slave](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - slave.WakeupHandler(linController, wakeupEvent); - }); + slave.WakeupHandler(linController, wakeupEvent); + }); if (runSync) { - lifecycleService->SetCommunicationReadyHandler([&participantName, linController]() { - InitLinSlave(linController, participantName); - }); + lifecycleService->SetCommunicationReadyHandler( + [&participantName, linController]() { InitLinSlave(linController, participantName); }); timeSyncService->SetSimulationStepHandler( [&slave](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - std::cout << "now=" << std::chrono::duration_cast(now).count() << "ms" - << std::endl; - slave.DoAction(now); + std::cout << "now=" << std::chrono::duration_cast(now).count() << "ms" + << std::endl; + slave.DoAction(now); - std::this_thread::sleep_for(100ms); - }, - 1ms); + std::this_thread::sleep_for(100ms); + }, 1ms); auto finalStateFuture = lifecycleService->StartLifecycle(); auto finalState = finalStateFuture.get(); @@ -590,8 +582,8 @@ int main(int argc, char** argv) try InitLinSlave(linController, participantName); workerThread = std::thread{[&]() { startHandlerFuture.get(); - while (lifecycleService->State() == ParticipantState::ReadyToRun || - lifecycleService->State() == ParticipantState::Running) + while (lifecycleService->State() == ParticipantState::ReadyToRun + || lifecycleService->State() == ParticipantState::Running) { slave.DoAction(now); now += 1ms; @@ -604,18 +596,15 @@ int main(int argc, char** argv) try }}; }); - lifecycleService->StartLifecycle(); - lifecycleService->SetStartingHandler([&]() { - startHandlerPromise.set_value(); - }); + lifecycleService->SetStartingHandler([&]() { startHandlerPromise.set_value(); }); lifecycleService->StartLifecycle(); std::cout << "Press enter to leave the simulation..." << std::endl; std::cin.ignore(); isStopRequested = true; - if (lifecycleService->State() == ParticipantState::Running || - lifecycleService->State() == ParticipantState::Paused) + if (lifecycleService->State() == ParticipantState::Running + || lifecycleService->State() == ParticipantState::Paused) { std::cout << "User requested to stop in state " << lifecycleService->State() << std::endl; lifecycleService->Stop("User requested to stop"); @@ -630,8 +619,7 @@ int main(int argc, char** argv) try } else { - std::cout << "Wrong participant name provided. Use either \"LinMaster\" or \"LinSlave\"." - << std::endl; + std::cout << "Wrong participant name provided. Use either \"LinMaster\" or \"LinSlave\"." << std::endl; return 1; } diff --git a/Demos/Lin/LinDemoDynamic.cpp b/Demos/Lin/LinDemoDynamic.cpp index 0c2fe7a6a..9ba4f579c 100644 --- a/Demos/Lin/LinDemoDynamic.cpp +++ b/Demos/Lin/LinDemoDynamic.cpp @@ -79,7 +79,8 @@ class Schedule { public: Schedule() = default; - Schedule(std::initializer_list>> tasks) + Schedule( + std::initializer_list>> tasks) { for (auto&& task : tasks) { @@ -112,8 +113,13 @@ class Schedule } private: - struct Task { - Task(std::chrono::nanoseconds delay, std::function action) : delay{delay}, action{action} {} + struct Task + { + Task(std::chrono::nanoseconds delay, std::function action) + : delay{delay} + , action{action} + { + } std::chrono::nanoseconds delay; std::function action; @@ -151,7 +157,7 @@ class LinMaster f17.id = 17; f17.checksumModel = LinChecksumModel::Classic; f17.dataLength = 6; - f17.data = std::array{1,7,1,7,1,7,1,7}; + f17.data = std::array{1, 7, 1, 7, 1, 7, 1, 7}; _masterResponses[f17.id] = f17; LinFrame f18{}; @@ -180,7 +186,8 @@ class LinMaster void SendFrameHeader(std::chrono::nanoseconds now, LinId linId) { controller->SendFrameHeader(linId); - std::cout << "<< LIN Frame sent with ID=" << static_cast(linId) << " @" << now.count() << "ns" << std::endl; + std::cout << "<< LIN Frame sent with ID=" << static_cast(linId) << " @" << now.count() << "ns" + << std::endl; } void GoToSleep(std::chrono::nanoseconds now) @@ -193,8 +200,10 @@ class LinMaster { switch (frameStatusEvent.status) { - case LinFrameStatus::LIN_RX_OK: break; // good case, no need to warn - case LinFrameStatus::LIN_TX_OK: break; // good case, no need to warn + case LinFrameStatus::LIN_RX_OK: + break; // good case, no need to warn + case LinFrameStatus::LIN_TX_OK: + break; // good case, no need to warn default: std::cout << "WARNING: LIN transmission failed!" << std::endl; } @@ -216,7 +225,8 @@ class LinMaster schedule.ScheduleNextTask(); } - void OnFrameHeader(ILinController* linController, const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& header) + void OnFrameHeader(ILinController* linController, + const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& header) { std::cout << ">> Received Frame Header: id=" << (int)header.id << "@" << header.timestamp << std::endl; @@ -271,21 +281,18 @@ class LinSlave UpdateDynamicResponseTo34(); } - std::cout << ">> " << frameStatusEvent.frame - << " status=" << frameStatusEvent.status - << " timestamp=" << frameStatusEvent.timestamp - << std::endl; + std::cout << ">> " << frameStatusEvent.frame << " status=" << frameStatusEvent.status + << " timestamp=" << frameStatusEvent.timestamp << std::endl; } void GoToSleepHandler(ILinController* linController, const LinGoToSleepEvent& /*goToSleepEvent*/) { std::cout << "LIN Slave received go-to-sleep command; entering sleep mode." << std::endl; // wakeup in 10 ms - timer.Set(now + 10ms, - [linController](std::chrono::nanoseconds tnow) { - std::cout << "<< Wakeup pulse @" << tnow << std::endl; - linController->Wakeup(); - }); + timer.Set(now + 10ms, [linController](std::chrono::nanoseconds tnow) { + std::cout << "<< Wakeup pulse @" << tnow << std::endl; + linController->Wakeup(); + }); linController->GoToSleepInternal(); } @@ -301,7 +308,8 @@ class LinSlave } } - void OnFrameHeader(ILinController* linController, const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& header) + void OnFrameHeader(ILinController* linController, + const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& header) { std::cout << "<< Received Frame Header: id=" << (int)header.id << "@" << header.timestamp << std::endl; @@ -351,7 +359,8 @@ void InitLinSlave(ILinController* linController, std::string participantName) * Main Function **************************************************************************************************/ -int main(int argc, char** argv) try +int main(int argc, char** argv) +try { if (argc < 3) { @@ -387,52 +396,44 @@ int main(int argc, char** argv) try std::cout << "Creating participant '" << participantName << "' with registry " << registryUri << std::endl; auto participant = SilKit::CreateParticipant(participantConfiguration, participantName, registryUri); - auto* lifecycleService = - participant->CreateLifecycleService({OperationMode::Coordinated}); + auto* lifecycleService = participant->CreateLifecycleService({OperationMode::Coordinated}); auto* timeSyncService = lifecycleService->CreateTimeSyncService(); auto* linController = participant->CreateLinController("LIN1", "LIN1"); // Set a Stop and Shutdown Handler - lifecycleService->SetStopHandler([]() { - std::cout << "Stop handler called" << std::endl; - }); - lifecycleService->SetShutdownHandler([]() { - std::cout << "Shutdown handler called" << std::endl; - }); + lifecycleService->SetStopHandler([]() { std::cout << "Stop handler called" << std::endl; }); + lifecycleService->SetShutdownHandler([]() { std::cout << "Shutdown handler called" << std::endl; }); LinMaster master{linController}; LinSlave slave; if (participantName == "LinMaster") { - - lifecycleService->SetCommunicationReadyHandler([&participantName, linController]() { - InitLinMaster(linController, participantName); - }); + lifecycleService->SetCommunicationReadyHandler( + [&participantName, linController]() { InitLinMaster(linController, participantName); }); linController->AddFrameStatusHandler( [&master](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master.FrameStatusHandler(linController, frameStatusEvent); - }); + master.FrameStatusHandler(linController, frameStatusEvent); + }); linController->AddWakeupHandler([&master](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - master.WakeupHandler(linController, wakeupEvent); - }); + master.WakeupHandler(linController, wakeupEvent); + }); SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( linController, [&master](ILinController* linController, const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& event) { - master.OnFrameHeader(linController, event); - }); + master.OnFrameHeader(linController, event); + }); if (runSync) { timeSyncService->SetSimulationStepHandler( [&master](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - auto nowMs = std::chrono::duration_cast(now); - std::cout << "now=" << nowMs.count() << "ms" << std::endl; + auto nowMs = std::chrono::duration_cast(now); + std::cout << "now=" << nowMs.count() << "ms" << std::endl; - master.DoAction(now); - }, - 1ms); + master.DoAction(now); + }, 1ms); auto finalStateFuture = lifecycleService->StartLifecycle(); @@ -450,8 +451,8 @@ int main(int argc, char** argv) try auto now = 0ms; workerThread = std::thread{[&]() { - while (lifecycleService->State() == ParticipantState::ReadyToRun || - lifecycleService->State() == ParticipantState::Running) + while (lifecycleService->State() == ParticipantState::ReadyToRun + || lifecycleService->State() == ParticipantState::Running) { master.DoAction(now); now += 1ms; @@ -484,39 +485,37 @@ int main(int argc, char** argv) try } else if (participantName == "LinSlave") { - lifecycleService->SetCommunicationReadyHandler([&participantName, linController]() { - InitLinSlave(linController, participantName); - }); + lifecycleService->SetCommunicationReadyHandler( + [&participantName, linController]() { InitLinSlave(linController, participantName); }); linController->AddFrameStatusHandler( [&slave](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - slave.FrameStatusHandler(linController, frameStatusEvent); - }); + slave.FrameStatusHandler(linController, frameStatusEvent); + }); linController->AddGoToSleepHandler( [&slave](ILinController* linController, const LinGoToSleepEvent& goToSleepEvent) { - slave.GoToSleepHandler(linController, goToSleepEvent); - }); + slave.GoToSleepHandler(linController, goToSleepEvent); + }); linController->AddWakeupHandler([&slave](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - slave.WakeupHandler(linController, wakeupEvent); - }); + slave.WakeupHandler(linController, wakeupEvent); + }); SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( linController, [&slave](ILinController* linController, - const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& event) { - slave.OnFrameHeader(linController, event); - }); + const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& event) { + slave.OnFrameHeader(linController, event); + }); if (runSync) { timeSyncService->SetSimulationStepHandler( [&slave](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - std::cout << "now=" << std::chrono::duration_cast(now).count() << "ms" - << std::endl; - slave.DoAction(now); + std::cout << "now=" << std::chrono::duration_cast(now).count() << "ms" + << std::endl; + slave.DoAction(now); - std::this_thread::sleep_for(100ms); - }, - 1ms); + std::this_thread::sleep_for(100ms); + }, 1ms); auto finalStateFuture = lifecycleService->StartLifecycle(); auto finalState = finalStateFuture.get(); @@ -534,8 +533,8 @@ int main(int argc, char** argv) try auto now = 0ms; workerThread = std::thread{[&]() { - while (lifecycleService->State() == ParticipantState::ReadyToRun || - lifecycleService->State() == ParticipantState::Running) + while (lifecycleService->State() == ParticipantState::ReadyToRun + || lifecycleService->State() == ParticipantState::Running) { slave.DoAction(now); now += 1ms; @@ -568,8 +567,7 @@ int main(int argc, char** argv) try } else { - std::cout << "Wrong participant name provided. Use either \"LinMaster\" or \"LinSlave\"." - << std::endl; + std::cout << "Wrong participant name provided. Use either \"LinMaster\" or \"LinSlave\"." << std::endl; return 1; } diff --git a/Demos/NetworkSimulator/CMakeLists.txt b/Demos/NetworkSimulator/CMakeLists.txt new file mode 100644 index 000000000..1eb13c8ef --- /dev/null +++ b/Demos/NetworkSimulator/CMakeLists.txt @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +# +# SPDX-License-Identifier: MIT + +make_silkit_demo(SilKitDemoNetSim NetSimDemo.cpp) + +target_sources(SilKitDemoNetSim + PRIVATE src/MySimulatedNetwork.cpp + PRIVATE src/MySimulatedNetwork.hpp + PRIVATE src/Scheduler.cpp + PRIVATE src/Scheduler.hpp + PRIVATE src/Can/MySimulatedCanController.cpp + PRIVATE src/Can/MySimulatedCanController.hpp + PRIVATE DemoNetSim.silkit.yaml +) + +target_include_directories(SilKitDemoNetSim + PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src +) \ No newline at end of file diff --git a/Demos/NetworkSimulator/DemoNetSim.silkit.yaml b/Demos/NetworkSimulator/DemoNetSim.silkit.yaml new file mode 100644 index 000000000..621b051b3 --- /dev/null +++ b/Demos/NetworkSimulator/DemoNetSim.silkit.yaml @@ -0,0 +1,5 @@ +Description: Sample Configuration for the Network Simulator Demo +Logging: + Sinks: + - Level: Info + Type: Stdout diff --git a/Demos/NetworkSimulator/NetSimDemo.cpp b/Demos/NetworkSimulator/NetSimDemo.cpp new file mode 100644 index 000000000..345479dec --- /dev/null +++ b/Demos/NetworkSimulator/NetSimDemo.cpp @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include +#include +#include +#include + +#include "silkit/SilKit.hpp" +#include "silkit/services/all.hpp" +#include "silkit/services/orchestration/all.hpp" +#include "silkit/services/orchestration/string_utils.hpp" +#include "silkit/experimental/netsim/all.hpp" +#include "silkit/experimental/participant/ParticipantExtensions.hpp" + +#include "src/MySimulatedNetwork.hpp" + +using namespace std::chrono_literals; +using namespace SilKit::Services; +using namespace SilKit::Services::Can; +using namespace SilKit::Experimental::NetworkSimulation; + +int main(int argc, char** argv) +{ + if (argc < 3) + { + std::cerr << "Missing arguments! Start demo with: " << argv[0] + << " [RegistryUri]" << std::endl; + return -1; + } + + std::string participantConfigurationFilename(argv[1]); + std::string participantName(argv[2]); + std::string registryUri = "silkit://localhost:8500"; + if (argc == 4) + registryUri = argv[3]; + + try + { + auto participantConfiguration = + SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); + auto participant = SilKit::CreateParticipant(participantConfiguration, participantName, registryUri); + + auto operationMode = SilKit::Services::Orchestration::OperationMode::Coordinated; + auto* lifecycleService = participant->CreateLifecycleService({operationMode}); + auto* timeSyncService = lifecycleService->CreateTimeSyncService(); + + // --------------------- + // NETSIM API USAGE + // --------------------- + + auto scheduler = std::make_unique(); + auto networkSimulator = SilKit::Experimental::Participant::CreateNetworkSimulator(participant.get()); + std::string networkName = "CAN1"; + SimulatedNetworkType networkType = SimulatedNetworkType::CAN; + auto simulatedCanNetwork = + std::make_unique(participant.get(), scheduler.get(), networkType, networkName); + networkSimulator->SimulateNetwork(networkName, networkType, std::move(simulatedCanNetwork)); + + networkSimulator->Start(); + + // --------------------- + + timeSyncService->SetSimulationStepHandler( + [scheduler = scheduler.get()](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { + auto nowMs = std::chrono::duration_cast(now); + std::cout << "now=" << nowMs.count() << "ms" << std::endl; + scheduler->OnSimulationStep(now); + std::this_thread::sleep_for(1s); + }, 1ms); + + auto lifecycleFuture = lifecycleService->StartLifecycle(); + auto finalState = lifecycleFuture.get(); + + std::cout << "Simulation stopped. Final State: " << finalState << std::endl; + std::cout << "Press enter to stop the process..." << std::endl; + std::cin.ignore(); + } + catch (const SilKit::ConfigurationError& error) + { + std::cerr << "Invalid configuration: " << error.what() << std::endl; + std::cout << "Press enter to stop the process..." << std::endl; + std::cin.ignore(); + return -2; + } + catch (const std::exception& error) + { + std::cerr << "Something went wrong: " << error.what() << std::endl; + std::cout << "Press enter to stop the process..." << std::endl; + std::cin.ignore(); + return -3; + } + + return 0; +} diff --git a/Demos/NetworkSimulator/src/Can/MySimulatedCanController.cpp b/Demos/NetworkSimulator/src/Can/MySimulatedCanController.cpp new file mode 100644 index 000000000..02d37e442 --- /dev/null +++ b/Demos/NetworkSimulator/src/Can/MySimulatedCanController.cpp @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "MySimulatedCanController.hpp" +#include "silkit/services/can/CanDatatypes.hpp" + +using namespace SilKit; +using namespace SilKit::Experimental::NetworkSimulation; +using namespace SilKit::Experimental::NetworkSimulation::Can; +using namespace std::chrono_literals; + +MySimulatedCanController::MySimulatedCanController(MySimulatedNetwork* mySimulatedNetwork, + ControllerDescriptor controllerDescriptor) + : _mySimulatedNetwork{mySimulatedNetwork} + , _controllerDescriptor{controllerDescriptor} + , _baudRate{0} + , _controllerMode{} +{ + std::string controllerDescriptorStr = std::to_string(static_cast(controllerDescriptor)); + + _logger = _mySimulatedNetwork->GetLogger(); + std::stringstream logMsg; + logMsg << "Registered SimulatedCanController #" << controllerDescriptorStr << " on network '" + << _mySimulatedNetwork->GetNetworkName() << "' of type '" << _mySimulatedNetwork->GetNetworkType() << "'"; + _logger->Info(logMsg.str()); + + _scheduler = _mySimulatedNetwork->GetScheduler(); +} + +// ISimulatedCanController + +void MySimulatedCanController::OnSetControllerMode(const CanControllerMode& controllerMode) +{ + std::stringstream logMsg; + logMsg << "Received 'CanControllerMode' on network '" << _mySimulatedNetwork->GetNetworkName() << "' of type '" + << _mySimulatedNetwork->GetNetworkType() << "'"; + _logger->Info(logMsg.str()); + + _controllerMode = controllerMode.state; +} + +void MySimulatedCanController::OnSetBaudrate(const CanConfigureBaudrate& configureBaudrate) +{ + std::stringstream logMsg; + logMsg << "Received 'CanConfigureBaudrate' on network '" << _mySimulatedNetwork->GetNetworkName() << "' of type '" + << _mySimulatedNetwork->GetNetworkType() << "'"; + _logger->Info(logMsg.str()); + + _baudRate = configureBaudrate.baudRate; +} + +void MySimulatedCanController::OnFrameRequest(const CanFrameRequest& frameRequest) +{ + std::stringstream logMsg; + logMsg << "Received 'CanFrameRequest' on network '" << _mySimulatedNetwork->GetNetworkName() << "' of type '" + << _mySimulatedNetwork->GetNetworkType() << "'"; + _logger->Info(logMsg.str()); + + // Send acknowledge back to the sending CAN controller + Services::Can::CanFrameTransmitEvent ack; + ack.canId = frameRequest.frame.canId; + ack.status = Services::Can::CanTransmitStatus::Transmitted; + ack.timestamp = _scheduler->Now(); + ack.userContext = frameRequest.userContext; + + std::array receiverArray{_controllerDescriptor}; + auto receivers = SilKit::Util::MakeSpan(receiverArray); + _mySimulatedNetwork->GetCanEventProducer()->Produce(std::move(ack), receivers); + + // Distribute the frame to all controllers in the network with delay + Services::Can::CanFrameEvent frameEvent; + frameEvent.direction = Services::TransmitDirection::RX; + frameEvent.frame = frameRequest.frame; + frameEvent.userContext = frameRequest.userContext; + std::vector payloadBytes{frameRequest.frame.dataField.begin(), frameRequest.frame.dataField.end()}; + + _scheduler->ScheduleEvent(2ms, [this, frameEvent, payloadBytes = std::move(payloadBytes)]() mutable { + frameEvent.frame.dataField = SilKit::Util::ToSpan(payloadBytes); + frameEvent.timestamp = _scheduler->Now(); + _mySimulatedNetwork->GetCanEventProducer()->Produce(frameEvent, + _mySimulatedNetwork->GetAllControllerDescriptors()); + }); +} diff --git a/Demos/NetworkSimulator/src/Can/MySimulatedCanController.hpp b/Demos/NetworkSimulator/src/Can/MySimulatedCanController.hpp new file mode 100644 index 000000000..041e937bd --- /dev/null +++ b/Demos/NetworkSimulator/src/Can/MySimulatedCanController.hpp @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "silkit/experimental/netsim/all.hpp" +#include "MySimulatedNetwork.hpp" + +class MySimulatedCanController : public SilKit::Experimental::NetworkSimulation::Can::ISimulatedCanController +{ +public: + MySimulatedCanController(MySimulatedNetwork* mySimulatedNetwork, + SilKit::Experimental::NetworkSimulation::ControllerDescriptor controllerDescriptor); + + // ISimulatedCanController + + void OnSetBaudrate(const SilKit::Experimental::NetworkSimulation::Can::CanConfigureBaudrate& msg) override; + void OnFrameRequest(const SilKit::Experimental::NetworkSimulation::Can::CanFrameRequest& msg) override; + void OnSetControllerMode(const SilKit::Experimental::NetworkSimulation::Can::CanControllerMode& msg) override; + +private: + MySimulatedNetwork* _mySimulatedNetwork; + Scheduler* _scheduler; + + SilKit::Experimental::NetworkSimulation::ControllerDescriptor _controllerDescriptor; + + double _baudRate; + SilKit::Services::Can::CanControllerState _controllerMode; + + SilKit::Services::Logging::ILogger* _logger; +}; diff --git a/Demos/NetworkSimulator/src/MySimulatedNetwork.cpp b/Demos/NetworkSimulator/src/MySimulatedNetwork.cpp new file mode 100644 index 000000000..e6f00a139 --- /dev/null +++ b/Demos/NetworkSimulator/src/MySimulatedNetwork.cpp @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "MySimulatedNetwork.hpp" +#include "Can/MySimulatedCanController.hpp" + +using namespace SilKit::Experimental::NetworkSimulation; + +MySimulatedNetwork::MySimulatedNetwork(SilKit::IParticipant* participant, Scheduler* scheduler, + SimulatedNetworkType networkType, std::string networkName) + : _participant{participant} + , _logger{_participant->GetLogger()} + , _scheduler{scheduler} + , _networkType{networkType} + , _networkName{networkName} + , _mySimulatedControllers{} +{ + std::stringstream msg; + msg << "Registered SimulatedNetwork '" << networkName << "' of type '" << _networkType << "'"; + _logger->Info(msg.str()); +} + +// ISimulatedNetwork + +void MySimulatedNetwork::SetEventProducer(std::unique_ptr eventProducer) +{ + _eventProducer = std::move(eventProducer); +} + +auto MySimulatedNetwork::ProvideSimulatedController(ControllerDescriptor controllerDescriptor) -> ISimulatedController* +{ + _controllerDescriptors.push_back(controllerDescriptor); + + switch (_networkType) + { + case SimulatedNetworkType::CAN: + { + _mySimulatedControllers.emplace_back(std::make_unique(this, controllerDescriptor)); + return _mySimulatedControllers.back().get(); + } + default: + break; + } + + return {}; +} + +void MySimulatedNetwork::SimulatedControllerRemoved(ControllerDescriptor /*controllerDescriptor*/) {} diff --git a/Demos/NetworkSimulator/src/MySimulatedNetwork.hpp b/Demos/NetworkSimulator/src/MySimulatedNetwork.hpp new file mode 100644 index 000000000..98459fc1e --- /dev/null +++ b/Demos/NetworkSimulator/src/MySimulatedNetwork.hpp @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "silkit/SilKit.hpp" +#include "silkit/experimental/netsim/string_utils.hpp" +#include "silkit/experimental/netsim/all.hpp" + +#include "Scheduler.hpp" + +class MySimulatedNetwork : public SilKit::Experimental::NetworkSimulation::ISimulatedNetwork +{ +public: + MySimulatedNetwork(SilKit::IParticipant* participant, Scheduler* scheduler, + SilKit::Experimental::NetworkSimulation::SimulatedNetworkType networkType, + std::string networkName); + + // ISimulatedNetwork + auto ProvideSimulatedController(SilKit::Experimental::NetworkSimulation::ControllerDescriptor controllerDescriptor) + -> SilKit::Experimental::NetworkSimulation::ISimulatedController* override; + + void SetEventProducer( + std::unique_ptr eventProducer) override; + + void SimulatedControllerRemoved( + SilKit::Experimental::NetworkSimulation::ControllerDescriptor controllerDescriptor) override; + + // Getter for children + auto GetLogger() -> SilKit::Services::Logging::ILogger* + { + return _logger; + } + auto GetNetworkType() -> SilKit::Experimental::NetworkSimulation::SimulatedNetworkType + { + return _networkType; + } + auto GetNetworkName() -> std::string + { + return _networkName; + } + auto GetAllControllerDescriptors() + -> SilKit::Util::Span + { + return SilKit::Util::ToSpan(_controllerDescriptors); + } + auto GetScheduler() -> Scheduler* + { + return _scheduler; + } + auto GetCanEventProducer() -> SilKit::Experimental::NetworkSimulation::Can::ICanEventProducer* + { + return static_cast(_eventProducer.get()); + } + +private: + // On construction + SilKit::IParticipant* _participant; + SilKit::Services::Logging::ILogger* _logger; + Scheduler* _scheduler; + SilKit::Experimental::NetworkSimulation::SimulatedNetworkType _networkType; + std::string _networkName; + + // Aggregated + std::unique_ptr _eventProducer; + std::vector> _mySimulatedControllers; + std::vector _controllerDescriptors; +}; \ No newline at end of file diff --git a/Demos/NetworkSimulator/src/Scheduler.cpp b/Demos/NetworkSimulator/src/Scheduler.cpp new file mode 100644 index 000000000..9a039d556 --- /dev/null +++ b/Demos/NetworkSimulator/src/Scheduler.cpp @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "Scheduler.hpp" + +Scheduler::Scheduler() + : _now{0} +{ +} + +void Scheduler::ScheduleEvent(std::chrono::nanoseconds delta, const std::function& callback) +{ + events.push({_now + delta, callback}); +} + +void Scheduler::OnSimulationStep(std::chrono::nanoseconds now) +{ + _now = now; + + while (!events.empty() && events.top().timestamp <= now) + { + Event event = events.top(); + events.pop(); + if (event.callback) + { + event.callback(); + } + } +} diff --git a/Demos/NetworkSimulator/src/Scheduler.hpp b/Demos/NetworkSimulator/src/Scheduler.hpp new file mode 100644 index 000000000..c16c0b1d4 --- /dev/null +++ b/Demos/NetworkSimulator/src/Scheduler.hpp @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include + +class Scheduler +{ +public: + Scheduler(); + + // Register an event with a timestamp and a callback function + void ScheduleEvent(std::chrono::nanoseconds delta, const std::function& callback); + + // Run the scheduler loop to check for due events + void OnSimulationStep(std::chrono::nanoseconds now); + + std::chrono::nanoseconds Now() + { + return _now; + } + + struct Event + { + std::chrono::nanoseconds timestamp; + std::function callback; + }; + +private: + // Custom comparison function for the priority queue + struct CompareEvent + { + bool operator()(const Event& e1, const Event& e2) + { + return e1.timestamp > e2.timestamp; + } + }; + + std::priority_queue, CompareEvent> events; + std::chrono::nanoseconds _now{0}; +}; diff --git a/Demos/PubSub/PubSubDemo.cpp b/Demos/PubSub/PubSubDemo.cpp old mode 100755 new mode 100644 index 86a955c16..527426b49 --- a/Demos/PubSub/PubSubDemo.cpp +++ b/Demos/PubSub/PubSubDemo.cpp @@ -86,8 +86,7 @@ GpsData Deserialize(const std::vector& data) return gpsData; } -void PublishData(IDataPublisher* gpsPublisher, - IDataPublisher* temperaturePublisher) +void PublishData(IDataPublisher* gpsPublisher, IDataPublisher* temperaturePublisher) { // GPS GpsData gpsData; @@ -151,8 +150,7 @@ int main(int argc, char** argv) if (participantName != "Publisher" && participantName != "Subscriber") { - std::cout << "Wrong participant name provided. Use either \"Publisher\" or \"Subscriber\"." - << std::endl; + std::cout << "Wrong participant name provided. Use either \"Publisher\" or \"Subscriber\"." << std::endl; return 1; } @@ -183,7 +181,8 @@ int main(int argc, char** argv) } } - auto participantConfiguration = SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); + auto participantConfiguration = + SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); std::cout << "Creating participant '" << participantName << "' with registry " << registryUri << std::endl; auto participant = SilKit::CreateParticipant(participantConfiguration, participantName, registryUri); @@ -191,36 +190,25 @@ int main(int argc, char** argv) auto* lifecycleService = participant->CreateLifecycleService({operationMode}); // Observe state changes - lifecycleService->SetStopHandler([]() { - std::cout << "Stop handler called" << std::endl; - }); - lifecycleService->SetShutdownHandler([]() { - std::cout << "Shutdown handler called" << std::endl; - }); - lifecycleService->SetAbortHandler([](auto lastState) { - std::cout << "Abort handler called while in state " << lastState << std::endl; - }); + lifecycleService->SetStopHandler([]() { std::cout << "Stop handler called" << std::endl; }); + lifecycleService->SetShutdownHandler([]() { std::cout << "Shutdown handler called" << std::endl; }); + lifecycleService->SetAbortHandler( + [](auto lastState) { std::cout << "Abort handler called while in state " << lastState << std::endl; }); auto isPublisher = (participantName == "Publisher"); // Create a data publisher for GPS data - auto* gpsPublisher = (isPublisher - ? participant->CreateDataPublisher("GpsPublisher", dataSpecPubGps, 0) - : nullptr); + auto* gpsPublisher = + (isPublisher ? participant->CreateDataPublisher("GpsPublisher", dataSpecPubGps, 0) : nullptr); // Create a data publisher for temperature data - auto* temperaturePublisher = ( - isPublisher - ? participant->CreateDataPublisher("TemperaturePublisher", dataSpecPubTemperature, 0) - : nullptr); + auto* temperaturePublisher = + (isPublisher ? participant->CreateDataPublisher("TemperaturePublisher", dataSpecPubTemperature, 0) + : nullptr); if (!isPublisher) { - participant->CreateDataSubscriber( - "GpsSubscriber", dataSpecPubGps, - &ReceiveGpsData); - participant->CreateDataSubscriber( - "TemperatureSubscriber", dataSpecPubTemperature, - &ReceiveTemperatureData); + participant->CreateDataSubscriber("GpsSubscriber", dataSpecPubGps, &ReceiveGpsData); + participant->CreateDataSubscriber("TemperatureSubscriber", dataSpecPubTemperature, &ReceiveTemperatureData); } if (runSync) @@ -236,28 +224,25 @@ int main(int argc, char** argv) timeSyncService->SetSimulationStepHandler( [gpsPublisher, temperaturePublisher](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - auto nowMs = - std::chrono::duration_cast(now); - std::cout << "now=" << nowMs.count() << "ms" << std::endl; + auto nowMs = std::chrono::duration_cast(now); + std::cout << "now=" << nowMs.count() << "ms" << std::endl; - if (gpsPublisher && temperaturePublisher) - { - PublishData(gpsPublisher, temperaturePublisher); - } - std::this_thread::sleep_for(1s); - }, + if (gpsPublisher && temperaturePublisher) + { + PublishData(gpsPublisher, temperaturePublisher); + } + std::this_thread::sleep_for(1s); + }, 1s); } else { timeSyncService->SetSimulationStepHandler( [](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - auto nowMs = - std::chrono::duration_cast(now); - std::cout << "now=" << nowMs.count() << "ms" << std::endl; - std::this_thread::sleep_for(1s); - }, - 1s); + auto nowMs = std::chrono::duration_cast(now); + std::cout << "now=" << nowMs.count() << "ms" << std::endl; + std::this_thread::sleep_for(1s); + }, 1s); } auto finalStateFuture = lifecycleService->StartLifecycle(); @@ -277,8 +262,8 @@ int main(int argc, char** argv) std::cout << "Communication ready handler called for " << participantName << std::endl; workerThread = std::thread{[&]() { startHandlerFuture.get(); - while (lifecycleService->State() == ParticipantState::ReadyToRun || - lifecycleService->State() == ParticipantState::Running) + while (lifecycleService->State() == ParticipantState::ReadyToRun + || lifecycleService->State() == ParticipantState::Running) { if (gpsPublisher && temperaturePublisher) { @@ -293,17 +278,15 @@ int main(int argc, char** argv) }}; }); - lifecycleService->SetStartingHandler([&]() { - startHandlerPromise.set_value(); - }); + lifecycleService->SetStartingHandler([&]() { startHandlerPromise.set_value(); }); lifecycleService->StartLifecycle(); std::cout << "Press enter to leave the simulation..." << std::endl; std::cin.ignore(); isStopRequested = true; - if (lifecycleService->State() == ParticipantState::Running || - lifecycleService->State() == ParticipantState::Paused) + if (lifecycleService->State() == ParticipantState::Running + || lifecycleService->State() == ParticipantState::Paused) { std::cout << "User requested to stop in state " << lifecycleService->State() << std::endl; lifecycleService->Stop("User requested to stop"); diff --git a/Demos/Rpc/RpcDemo.cpp b/Demos/Rpc/RpcDemo.cpp index 6ba344e74..b14b61eac 100644 --- a/Demos/Rpc/RpcDemo.cpp +++ b/Demos/Rpc/RpcDemo.cpp @@ -57,12 +57,10 @@ static std::ostream& operator<<(std::ostream& os, const std::vector& v) void Call(IRpcClient* client) { - std::vector argumentData{ - static_cast(rand() % 10), - static_cast(rand() % 10), - static_cast(rand() % 10) }; + std::vector argumentData{static_cast(rand() % 10), static_cast(rand() % 10), + static_cast(rand() % 10)}; - // Add an incrementing callCounter as userContext, to reidentify the corresponding call on reception of a + // Add an incrementing callCounter as userContext, to reidentify the corresponding call on reception of a // call result. const auto userContext = reinterpret_cast(uintptr_t(callCounter++)); @@ -84,20 +82,22 @@ void CallReturn(IRpcClient* /*client*/, RpcCallResultEvent event) SilKit::Util::SerDes::Deserializer deserializer(resultDataVector); resultData = deserializer.Deserialize>(); } - + switch (event.callStatus) { case RpcCallStatus::Success: std::cout << ">> Call " << event.userContext << " returned with resultData=" << resultData << std::endl; break; case RpcCallStatus::ServerNotReachable: - std::cout << "Warning: Call " << event.userContext << " failed with RpcCallStatus::ServerNotReachable" << std::endl; + std::cout << "Warning: Call " << event.userContext << " failed with RpcCallStatus::ServerNotReachable" + << std::endl; break; case RpcCallStatus::UndefinedError: std::cout << "Warning: Call " << event.userContext << " failed with RpcCallStatus::UndefinedError" << std::endl; break; case RpcCallStatus::InternalServerError: - std::cout << "Warning: Call " << event.userContext << " failed with RpcCallStatus::InternalServerError" << std::endl; + std::cout << "Warning: Call " << event.userContext << " failed with RpcCallStatus::InternalServerError" + << std::endl; break; case RpcCallStatus::Timeout: std::cout << "Warning: Call " << event.userContext << " failed with RpcCallStatus::Timeout" << std::endl; @@ -146,8 +146,8 @@ void RemoteFunc_Sort(IRpcServer* server, RpcCallEvent event) // Perform calculation (sort argument values) std::sort(resultData.begin(), resultData.end()); - std::cout << ">> Received call with argumentData=" << argumentData - << ", returning resultData=" << resultData << std::endl; + std::cout << ">> Received call with argumentData=" << argumentData << ", returning resultData=" << resultData + << std::endl; // Serialize result data SilKit::Util::SerDes::Serializer serializer; @@ -200,7 +200,8 @@ int main(int argc, char** argv) } } - auto participantConfiguration = SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); + auto participantConfiguration = + SilKit::Config::ParticipantConfigurationFromFile(participantConfigurationFilename); std::cout << "Creating participant '" << participantName << "' with registry " << registryUri << std::endl; auto participant = SilKit::CreateParticipant(participantConfiguration, participantName, registryUri); @@ -209,15 +210,10 @@ int main(int argc, char** argv) auto* lifecycleService = participant->CreateLifecycleService({operationMode}); // Observe state changes - lifecycleService->SetStopHandler([]() { - std::cout << "Stop handler called" << std::endl; - }); - lifecycleService->SetShutdownHandler([]() { - std::cout << "Shutdown handler called" << std::endl; - }); - lifecycleService->SetAbortHandler([](auto lastState) { - std::cout << "Abort handler called while in state " << lastState << std::endl; - }); + lifecycleService->SetStopHandler([]() { std::cout << "Stop handler called" << std::endl; }); + lifecycleService->SetShutdownHandler([]() { std::cout << "Shutdown handler called" << std::endl; }); + lifecycleService->SetAbortHandler( + [](auto lastState) { std::cout << "Abort handler called while in state " << lastState << std::endl; }); auto isClient = participantName == "Client"; if (!isClient) @@ -230,11 +226,10 @@ int main(int argc, char** argv) } // Create RpcClient to call "Add100" - auto* clientAdd100 = (isClient ? participant->CreateRpcClient("ClientAdd100", rpcSpecAdd100, &CallReturn) - : nullptr); + auto* clientAdd100 = + (isClient ? participant->CreateRpcClient("ClientAdd100", rpcSpecAdd100, &CallReturn) : nullptr); // Create RpcClient to call "Sort" - auto* clientSort = (isClient ? participant->CreateRpcClient("ClientSort", rpcSpecSort, &CallReturn) - : nullptr); + auto* clientSort = (isClient ? participant->CreateRpcClient("ClientSort", rpcSpecSort, &CallReturn) : nullptr); if (runSync) { @@ -244,26 +239,24 @@ int main(int argc, char** argv) { timeSyncService->SetSimulationStepHandler( [clientAdd100, clientSort](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - auto nowMs = std::chrono::duration_cast(now); - std::cout << "now=" << nowMs.count() << "ms" << std::endl; - - // Call both remote procedures in each simulation step - if (clientAdd100) - Call(clientAdd100); - if (clientSort) - Call(clientSort); - }, - 1s); + auto nowMs = std::chrono::duration_cast(now); + std::cout << "now=" << nowMs.count() << "ms" << std::endl; + + // Call both remote procedures in each simulation step + if (clientAdd100) + Call(clientAdd100); + if (clientSort) + Call(clientSort); + }, 1s); } else { timeSyncService->SetSimulationStepHandler( [](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - auto nowMs = std::chrono::duration_cast(now); - std::cout << "now=" << nowMs.count() << "ms" << std::endl; - std::this_thread::sleep_for(1s); - }, - 1s); + auto nowMs = std::chrono::duration_cast(now); + std::cout << "now=" << nowMs.count() << "ms" << std::endl; + std::this_thread::sleep_for(1s); + }, 1s); } auto finalStateFuture = lifecycleService->StartLifecycle(); @@ -282,13 +275,13 @@ int main(int argc, char** argv) lifecycleService->SetCommunicationReadyHandler([&]() { workerThread = std::thread{[&]() { startHandlerFuture.get(); - while (lifecycleService->State() == ParticipantState::ReadyToRun || - lifecycleService->State() == ParticipantState::Running) + while (lifecycleService->State() == ParticipantState::ReadyToRun + || lifecycleService->State() == ParticipantState::Running) { if (clientAdd100) - Call(clientAdd100); + Call(clientAdd100); if (clientSort) - Call(clientSort); + Call(clientSort); std::this_thread::sleep_for(1s); } if (!isStopRequested) @@ -298,17 +291,15 @@ int main(int argc, char** argv) }}; }); - lifecycleService->SetStartingHandler([&]() { - startHandlerPromise.set_value(); - }); + lifecycleService->SetStartingHandler([&]() { startHandlerPromise.set_value(); }); lifecycleService->StartLifecycle(); std::cout << "Press enter to stop the simulation..." << std::endl; std::cin.ignore(); isStopRequested = true; - if (lifecycleService->State() == ParticipantState::Running || - lifecycleService->State() == ParticipantState::Paused) + if (lifecycleService->State() == ParticipantState::Running + || lifecycleService->State() == ParticipantState::Paused) { std::cout << "User requested to stop in state " << lifecycleService->State() << std::endl; lifecycleService->Stop("User requested to stop"); diff --git a/README.rst b/README.rst index 72f8ab763..f7120eeba 100644 --- a/README.rst +++ b/README.rst @@ -1,21 +1,23 @@ ================================ The Vector SIL Kit ================================ -.. image:: https://img.shields.io/github/v/release/vectorgrp/sil-kit.svg +.. |ReleaseBadge| image:: https://img.shields.io/github/v/release/vectorgrp/sil-kit.svg :target: https://github.com/vectorgrp/sil-kit/releases -.. image:: https://img.shields.io/badge/license-MIT-blue.svg +.. |LicenseBadge| image:: https://img.shields.io/badge/license-MIT-blue.svg :target: https://github.com/vectorgrp/sil-kit/blob/main/LICENSE -.. image:: https://img.shields.io/badge/documentation-html-blue.svg +.. |DocsBadge| image:: https://img.shields.io/badge/documentation-html-blue.svg :target: https://vectorgrp.github.io/sil-kit-docs -.. image:: https://github.com/vectorgrp/sil-kit/actions/workflows/build-linux-asan.yml/badge.svg - :target: https://github.com/vectorgrp/sil-kit/actions/workflows/build-linux-asan.yml -.. image:: https://github.com/vectorgrp/sil-kit/actions/workflows/build-linux-ubsan.yml/badge.svg - :target: https://github.com/vectorgrp/sil-kit/actions/workflows/build-linux-ubsan.yml -.. image:: https://github.com/vectorgrp/sil-kit/actions/workflows/build-linux-tsan.yml/badge.svg - :target: https://github.com/vectorgrp/sil-kit/actions/workflows/build-linux-tsan.yml -.. image:: https://github.com/vectorgrp/sil-kit/actions/workflows/build-win.yml/badge.svg +.. |AsanBadge| image:: https://github.com/vectorgrp/sil-kit/actions/workflows/linux-asan.yml/badge.svg + :target: https://github.com/vectorgrp/sil-kit/actions/workflows/linux-asan.yml +.. |UbsanBadge| image:: https://github.com/vectorgrp/sil-kit/actions/workflows/linux-ubsan.yml/badge.svg + :target: https://github.com/vectorgrp/sil-kit/actions/workflows/linux-ubsan.yml +.. |TsanBadge| image:: https://github.com/vectorgrp/sil-kit/actions/workflows/linux-tsan.yml/badge.svg + :target: https://github.com/vectorgrp/sil-kit/actions/workflows/linux-tsan.yml +.. |WinBadge| image:: https://github.com/vectorgrp/sil-kit/actions/workflows/build-win.yml/badge.svg :target: https://github.com/vectorgrp/sil-kit/actions/workflows/build-win.yml +| |ReleaseBadge| |LicenseBadge| |DocsBadge| +| |AsanBadge| |UbsanBadge| |TsanBadge| |WinBadge| The Vector SIL Kit is an open-source library for connecting Software-in-the-Loop Environments. This README is intended to provide you with quick start on how to build the Vector SIL Kit. @@ -48,6 +50,9 @@ The SIL Kit ecosystem comprises the following turn-key solutions: * The `SIL Kit FMU Importer `_ allows to import Functional Mockup Units (FMUs) as SIL Kit participants. +* The `Vector SIL Kit Adapter for Generic Linux IO `_ + allows to attach SIL Kit to a generic Linux IO device, such as character devices or GPIOs. + Related Applications -------------------- diff --git a/SilKit/IntegrationTests/CMakeLists.txt b/SilKit/IntegrationTests/CMakeLists.txt index e47ad3c28..d21d0e2b1 100644 --- a/SilKit/IntegrationTests/CMakeLists.txt +++ b/SilKit/IntegrationTests/CMakeLists.txt @@ -249,6 +249,47 @@ add_silkit_test_to_executable(SilKitIntegrationTests I_SilKit_Config_TestUtils ) +# ============================================================ +# Integration Tests for NetworkSimulaton +# ============================================================ + +add_silkit_test_to_executable(SilKitIntegrationTests + SOURCES + ITest_NetSimCan.cpp + ITest_NetSim.hpp + + LIBS + S_ITests_STH +) + +add_silkit_test_to_executable(SilKitIntegrationTests + SOURCES + ITest_NetSimEthernet.cpp + ITest_NetSim.hpp + + LIBS + S_ITests_STH +) + +add_silkit_test_to_executable(SilKitIntegrationTests + SOURCES + ITest_NetSimLin.cpp + ITest_NetSim.hpp + + LIBS + S_ITests_STH +) + +add_silkit_test_to_executable(SilKitIntegrationTests + SOURCES + ITest_NetSimFlexRay.cpp + ITest_NetSim.hpp + + LIBS + S_ITests_STH +) + + # ============================================================ # Integration Tests based on Demo Applications # ============================================================ @@ -291,7 +332,7 @@ add_silkit_test_to_executable(SilKitIntegrationTests S_ITests_STH ) -add_silkit_test_to_executable( SilKitIntegrationTests +add_silkit_test_to_executable(SilKitIntegrationTests SOURCES ITest_RequestRemoteParticipantConnect.cpp diff --git a/SilKit/IntegrationTests/EthernetHelpers.hpp b/SilKit/IntegrationTests/EthernetHelpers.hpp index 9d20997e5..02fb713bb 100644 --- a/SilKit/IntegrationTests/EthernetHelpers.hpp +++ b/SilKit/IntegrationTests/EthernetHelpers.hpp @@ -49,8 +49,8 @@ const size_t EthernetFrameHeaderSize = 2 * sizeof(EthernetMac) + sizeof(Ethernet //! \brief Build an Ethernet frame with specified destination and source MAC addresses, ether-type, and string payload. inline auto CreateEthernetFrameFromString(const EthernetMac& destinationMac, const EthernetMac& sourceMac, - const EthernetEtherType& etherType, const std::string& payload) - -> std::vector + const EthernetEtherType& etherType, + const std::string& payload) -> std::vector { std::vector raw; @@ -66,10 +66,9 @@ inline auto CreateEthernetFrameFromString(const EthernetMac& destinationMac, con } //! \brief Build an Ethernet frame with specified destination and source MAC addresses, VLAN tag, ether-type, and string payload. -inline auto CreateEthernetFrameWithVlanTagFromString(const EthernetMac& destinationMac, const EthernetMac& sourceMac, - const EthernetEtherType& etherType, const std::string& payload, - const EthernetVlanTagControlIdentifier& tci) - -> std::vector +inline auto CreateEthernetFrameWithVlanTagFromString( + const EthernetMac& destinationMac, const EthernetMac& sourceMac, const EthernetEtherType& etherType, + const std::string& payload, const EthernetVlanTagControlIdentifier& tci) -> std::vector { std::vector raw; diff --git a/SilKit/IntegrationTests/FTest_CanControllerThreadSafety.cpp b/SilKit/IntegrationTests/FTest_CanControllerThreadSafety.cpp index e23fa4747..ccb9e3be3 100644 --- a/SilKit/IntegrationTests/FTest_CanControllerThreadSafety.cpp +++ b/SilKit/IntegrationTests/FTest_CanControllerThreadSafety.cpp @@ -52,11 +52,8 @@ const int stopAfterReceptions = 100; class FTest_CanControllerThreadSafety : public testing::Test { - protected: - FTest_CanControllerThreadSafety() - { - } + FTest_CanControllerThreadSafety() {} struct TestParticipant { @@ -64,11 +61,11 @@ class FTest_CanControllerThreadSafety : public testing::Test { name = newName; } - std::string name; + std::string name; std::unique_ptr participant; ICanController* canController; uint64_t numReceptions = 0; - bool allReceived{ false }; + bool allReceived{false}; std::promise allReceivedPromise; void AwaitCommunication() @@ -98,7 +95,6 @@ class FTest_CanControllerThreadSafety : public testing::Test frame.canId = increasingCanId++; participant.canController->SendFrame(frame); } - } catch (const SilKit::ConfigurationError& error) { @@ -194,9 +190,8 @@ class FTest_CanControllerThreadSafety : public testing::Test try { - asyncParticipantThreads.emplace_back([this, &participant, registryUri] { - AsyncCanWriterThread(participant, registryUri); - }); + asyncParticipantThreads.emplace_back( + [this, &participant, registryUri] { AsyncCanWriterThread(participant, registryUri); }); } catch (const SilKit::ConfigurationError& error) { @@ -218,9 +213,8 @@ class FTest_CanControllerThreadSafety : public testing::Test try { - asyncParticipantThreads.emplace_back([this, &participant, registryUri] { - AsyncCanReaderThread(participant, registryUri); - }); + asyncParticipantThreads.emplace_back( + [this, &participant, registryUri] { AsyncCanReaderThread(participant, registryUri); }); } catch (const SilKit::ConfigurationError& error) { @@ -261,7 +255,7 @@ class FTest_CanControllerThreadSafety : public testing::Test protected: std::unique_ptr registry; std::vector asyncParticipantThreads; - bool runAsync{ true }; + bool runAsync{true}; }; @@ -270,8 +264,8 @@ TEST_F(FTest_CanControllerThreadSafety, DISABLED_add_remove_handler_during_recep numParticipants = 0; auto registryUri = MakeTestRegistryUri(); - TestParticipant canWriterParticipant{ "CanWriterParticipant" }; - TestParticipant canReaderParticipant{ "CanReaderParticipant" }; + TestParticipant canWriterParticipant{"CanWriterParticipant"}; + TestParticipant canReaderParticipant{"CanReaderParticipant"}; RunRegistry(registryUri); diff --git a/SilKit/IntegrationTests/FTest_CanWithoutSync.cpp b/SilKit/IntegrationTests/FTest_CanWithoutSync.cpp index e09aea809..7710ba2e0 100644 --- a/SilKit/IntegrationTests/FTest_CanWithoutSync.cpp +++ b/SilKit/IntegrationTests/FTest_CanWithoutSync.cpp @@ -40,18 +40,14 @@ using namespace std::chrono_literals; // basically the same as the normal == operator, but it doesn't compare timestamps bool Matches(const SilKit::Services::Can::CanFrameEvent& lhs, const SilKit::Services::Can::CanFrameEvent& rhs) { - return lhs.frame.canId == rhs.frame.canId - && lhs.frame.flags == rhs.frame.flags - && lhs.frame.dlc == rhs.frame.dlc - && SilKit::Util::ItemsAreEqual(lhs.frame.dataField, rhs.frame.dataField) - && lhs.userContext == rhs.userContext - && lhs.direction == rhs.direction; + return lhs.frame.canId == rhs.frame.canId && lhs.frame.flags == rhs.frame.flags && lhs.frame.dlc == rhs.frame.dlc + && SilKit::Util::ItemsAreEqual(lhs.frame.dataField, rhs.frame.dataField) + && lhs.userContext == rhs.userContext && lhs.direction == rhs.direction; } class FTest_CanWithoutSync : public testing::Test { protected: - FTest_CanWithoutSync() { _registryUri = MakeTestRegistryUri(); @@ -92,40 +88,40 @@ class FTest_CanWithoutSync : public testing::Test canack.canId = index; canack.timestamp = 1s; canack.status = SilKit::Services::Can::CanTransmitStatus::Transmitted; - canack.userContext = (void*)((size_t)index+1); + canack.userContext = (void*)((size_t)index + 1); } } void CanWriter() { - unsigned numSent{ 0 }, numAcks{ 0 }; + unsigned numSent{0}, numAcks{0}; std::promise canWriterAllAcksReceivedPromiseLocal; auto participant = SilKit::CreateParticipant(SilKit::Config::ParticipantConfigurationFromString(""), "CanWriter", _registryUri); auto* controller = participant->CreateCanController("CAN1", "CAN1"); - controller->AddFrameTransmitHandler( - [this, &canWriterAllAcksReceivedPromiseLocal, &numAcks](SilKit::Services::Can::ICanController* /*ctrl*/, const SilKit::Services::Can::CanFrameTransmitEvent& ack) { - _testMessages.at(numAcks++).receivedAck = ack; - auto tempUserContext = ack.userContext; - // double check that userContext is not nullified for frame transmit handler - EXPECT_TRUE(tempUserContext == (void*)((size_t)numAcks)); - if (numAcks >= _testMessages.size()) - { - std::cout << "All can acks received" << std::endl; - _canWriterAllAcksReceivedPromise.set_value(); // Promise for canReader - canWriterAllAcksReceivedPromiseLocal.set_value(); - } - }); - - + controller->AddFrameTransmitHandler([this, &canWriterAllAcksReceivedPromiseLocal, &numAcks]( + SilKit::Services::Can::ICanController* /*ctrl*/, + const SilKit::Services::Can::CanFrameTransmitEvent& ack) { + _testMessages.at(numAcks++).receivedAck = ack; + auto tempUserContext = ack.userContext; + // double check that userContext is not nullified for frame transmit handler + EXPECT_TRUE(tempUserContext == (void*)((size_t)numAcks)); + if (numAcks >= _testMessages.size()) + { + std::cout << "All can acks received" << std::endl; + _canWriterAllAcksReceivedPromise.set_value(); // Promise for canReader + canWriterAllAcksReceivedPromiseLocal.set_value(); + } + }); + + controller->AddFrameHandler( [](SilKit::Services::Can::ICanController*, const SilKit::Services::Can::CanFrameEvent& msg) { - // make sure that userContext fo TX is not nullified - EXPECT_TRUE(msg.userContext > (void*)((size_t)0)); - }, - static_cast(SilKit::Services::TransmitDirection::TX)); + // make sure that userContext fo TX is not nullified + EXPECT_TRUE(msg.userContext > (void*)((size_t)0)); + }, static_cast(SilKit::Services::TransmitDirection::TX)); controller->Start(); @@ -133,7 +129,8 @@ class FTest_CanWithoutSync : public testing::Test while (numSent < _testMessages.size()) { - controller->SendFrame(_testMessages.at(numSent).expectedMsg.frame, (void*)((size_t)numSent+1)); // Don't move the msg to test the altered transmitID + controller->SendFrame(_testMessages.at(numSent).expectedMsg.frame, + (void*)((size_t)numSent + 1)); // Don't move the msg to test the altered transmitID numSent++; } std::cout << "All can messages sent" << std::endl; @@ -145,30 +142,31 @@ class FTest_CanWithoutSync : public testing::Test void CanReader() { std::promise canReaderAllReceivedPromiseLocal; - unsigned numReceived{ 0 }; + unsigned numReceived{0}; auto participant = SilKit::CreateParticipant(SilKit::Config::ParticipantConfigurationFromString(""), "CanReader", _registryUri); auto* controller = participant->CreateCanController("CAN1", "CAN1"); controller->AddFrameHandler( - [this, &canReaderAllReceivedPromiseLocal, &numReceived](SilKit::Services::Can::ICanController*, const SilKit::Services::Can::CanFrameEvent& msg) { - unsigned msgIndex = numReceived++; + [this, &canReaderAllReceivedPromiseLocal, &numReceived](SilKit::Services::Can::ICanController*, + const SilKit::Services::Can::CanFrameEvent& msg) { + unsigned msgIndex = numReceived++; - auto& msgData = _testMessages.at(msgIndex).receivedMsgData; - auto& msgEvent = _testMessages.at(msgIndex).receivedMsg; + auto& msgData = _testMessages.at(msgIndex).receivedMsgData; + auto& msgEvent = _testMessages.at(msgIndex).receivedMsg; - msgEvent = msg; + msgEvent = msg; - msgData = ToStdVector(msg.frame.dataField); - msgEvent.frame.dataField = msgData; + msgData = ToStdVector(msg.frame.dataField); + msgEvent.frame.dataField = msgData; - if (numReceived >= _testMessages.size()) - { - std::cout << "All can messages received" << std::endl; - _canReaderAllReceivedPromise.set_value(); - canReaderAllReceivedPromiseLocal.set_value(); - } + if (numReceived >= _testMessages.size()) + { + std::cout << "All can messages received" << std::endl; + _canReaderAllReceivedPromise.set_value(); + canReaderAllReceivedPromiseLocal.set_value(); + } }); controller->Start(); @@ -182,8 +180,8 @@ class FTest_CanWithoutSync : public testing::Test void ExecuteTest() { - std::thread canReaderThread{ [this] { CanReader(); } }; - std::thread canWriterThread{ [this] { CanWriter(); } }; + std::thread canReaderThread{[this] { CanReader(); }}; + std::thread canWriterThread{[this] { CanWriter(); }}; canReaderThread.join(); canWriterThread.join(); for (auto&& message : _testMessages) @@ -214,7 +212,8 @@ class FTest_CanWithoutSync : public testing::Test TEST_F(FTest_CanWithoutSync, can_communication_no_simulation_flow_vasio) { - auto registry = SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); + auto registry = + SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); registry->StartListening(_registryUri); ExecuteTest(); } diff --git a/SilKit/IntegrationTests/FTest_EthWithoutSync.cpp b/SilKit/IntegrationTests/FTest_EthWithoutSync.cpp old mode 100755 new mode 100644 index c46e69e1a..8a81e7a77 --- a/SilKit/IntegrationTests/FTest_EthWithoutSync.cpp +++ b/SilKit/IntegrationTests/FTest_EthWithoutSync.cpp @@ -50,7 +50,6 @@ constexpr std::size_t MINIMUM_ETHERNET_FRAME_LENGTH = 60; class FTest_EthWithoutSync : public testing::Test { protected: - FTest_EthWithoutSync() { _registryUri = MakeTestRegistryUri(); @@ -71,27 +70,27 @@ class FTest_EthWithoutSync : public testing::Test auto& frameEvent = _testFrames[index].expectedFrameEvent; auto& frameData = _testFrames[index].expectedFrameData; - EthernetMac destinationMac{ 0x12, 0x23, 0x45, 0x67, 0x89, 0x9a }; - EthernetMac sourceMac{ 0x9a, 0x89, 0x67, 0x45, 0x23, 0x12 }; - EthernetEtherType etherType{ 0x0800 }; - EthernetVlanTagControlIdentifier tci{ 0x0000 }; + EthernetMac destinationMac{0x12, 0x23, 0x45, 0x67, 0x89, 0x9a}; + EthernetMac sourceMac{0x9a, 0x89, 0x67, 0x45, 0x23, 0x12}; + EthernetEtherType etherType{0x0800}; + EthernetVlanTagControlIdentifier tci{0x0000}; frameData = CreateEthernetFrameWithVlanTagFromString(destinationMac, sourceMac, etherType, messageString, tci); frameEvent.frame = SilKit::Services::Ethernet::EthernetFrame{frameData}; EXPECT_GE(frameEvent.frame.raw.size(), MINIMUM_ETHERNET_FRAME_LENGTH); - frameEvent.userContext = reinterpret_cast(static_cast(index + 1)); + frameEvent.userContext = reinterpret_cast(static_cast(index + 1)); auto& ethack = _testFrames[index].expectedAck; - ethack.userContext = reinterpret_cast(static_cast(index + 1)); + ethack.userContext = reinterpret_cast(static_cast(index + 1)); ethack.status = SilKit::Services::Ethernet::EthernetTransmitStatus::Transmitted; } } void EthWriter() { - unsigned numSent{ 0 }, numAcks{ 0 }; + unsigned numSent{0}, numAcks{0}; std::promise ethWriterAllAcksReceivedPromiseLocal; const auto participant = SilKit::CreateParticipant(SilKit::Config::ParticipantConfigurationFromString(""), @@ -100,16 +99,17 @@ class FTest_EthWithoutSync : public testing::Test controller->Activate(); - controller->AddFrameTransmitHandler( - [this, ðWriterAllAcksReceivedPromiseLocal, &numAcks](SilKit::Services::Ethernet::IEthernetController* /*ctrl*/, const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& ack) { - _testFrames.at(numAcks++).receivedAck = ack; - if (numAcks >= _testFrames.size()) - { - std::cout << "All eth acks received" << std::endl; - _ethWriterAllAcksReceivedPromise.set_value(); // Promise for ethReader - ethWriterAllAcksReceivedPromiseLocal.set_value(); // Promise for this thread - } - }); + controller->AddFrameTransmitHandler([this, ðWriterAllAcksReceivedPromiseLocal, &numAcks]( + SilKit::Services::Ethernet::IEthernetController* /*ctrl*/, + const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& ack) { + _testFrames.at(numAcks++).receivedAck = ack; + if (numAcks >= _testFrames.size()) + { + std::cout << "All eth acks received" << std::endl; + _ethWriterAllAcksReceivedPromise.set_value(); // Promise for ethReader + ethWriterAllAcksReceivedPromiseLocal.set_value(); // Promise for this thread + } + }); _ethReaderRegisteredPromise.get_future().wait_for(10s); @@ -127,7 +127,7 @@ class FTest_EthWithoutSync : public testing::Test void EthReader() { - unsigned numReceived{ 0 }; + unsigned numReceived{0}; std::promise ethReaderAllReceivedPromiseLocal; const auto participant = SilKit::CreateParticipant(SilKit::Config::ParticipantConfigurationFromString(""), "EthReader", _registryUri); @@ -135,24 +135,25 @@ class FTest_EthWithoutSync : public testing::Test controller->Activate(); - controller->AddFrameHandler( - [this, ðReaderAllReceivedPromiseLocal, &numReceived](SilKit::Services::Ethernet::IEthernetController*, const SilKit::Services::Ethernet::EthernetFrameEvent& msg) { - unsigned frameIndex = numReceived++; + controller->AddFrameHandler([this, ðReaderAllReceivedPromiseLocal, &numReceived]( + SilKit::Services::Ethernet::IEthernetController*, + const SilKit::Services::Ethernet::EthernetFrameEvent& msg) { + unsigned frameIndex = numReceived++; - auto& frameData = _testFrames.at(frameIndex).receivedFrameData; - auto& frameEvent = _testFrames.at(frameIndex).receivedFrameEvent; + auto& frameData = _testFrames.at(frameIndex).receivedFrameData; + auto& frameEvent = _testFrames.at(frameIndex).receivedFrameEvent; - frameEvent = msg; - frameData = ToStdVector(msg.frame.raw); - frameEvent.frame = SilKit::Services::Ethernet::EthernetFrame{frameData}; + frameEvent = msg; + frameData = ToStdVector(msg.frame.raw); + frameEvent.frame = SilKit::Services::Ethernet::EthernetFrame{frameData}; - if (numReceived >= _testFrames.size()) - { - std::cout << "All eth messages received" << std::endl; - _ethReaderAllReceivedPromise.set_value(); // Promise for ethWriter - ethReaderAllReceivedPromiseLocal.set_value(); // Promise for this thread - } - }); + if (numReceived >= _testFrames.size()) + { + std::cout << "All eth messages received" << std::endl; + _ethReaderAllReceivedPromise.set_value(); // Promise for ethWriter + ethReaderAllReceivedPromiseLocal.set_value(); // Promise for this thread + } + }); _ethReaderRegisteredPromise.set_value(); @@ -163,8 +164,8 @@ class FTest_EthWithoutSync : public testing::Test void ExecuteTest() { - std::thread ethReaderThread{ [this] { EthReader(); } }; - std::thread ethWriterThread{ [this] { EthWriter(); } }; + std::thread ethReaderThread{[this] { EthReader(); }}; + std::thread ethWriterThread{[this] { EthWriter(); }}; ethReaderThread.join(); ethWriterThread.join(); for (auto&& message : _testFrames) @@ -191,7 +192,7 @@ class FTest_EthWithoutSync : public testing::Test SilKit::Services::Ethernet::EthernetFrameTransmitEvent receivedAck; }; - std::string _registryUri; + std::string _registryUri; std::vector _testFrames; std::promise _ethReaderRegisteredPromise; std::promise _ethReaderAllReceivedPromise; diff --git a/SilKit/IntegrationTests/FTest_PubSubPerf.cpp b/SilKit/IntegrationTests/FTest_PubSubPerf.cpp index 110d826ca..fce1a3a09 100644 --- a/SilKit/IntegrationTests/FTest_PubSubPerf.cpp +++ b/SilKit/IntegrationTests/FTest_PubSubPerf.cpp @@ -45,10 +45,7 @@ auto Now() class FTest_PubSubPerf : public testing::Test { protected: - - FTest_PubSubPerf() - { - } + FTest_PubSubPerf() {} enum class TopicMode { @@ -68,8 +65,8 @@ class FTest_PubSubPerf : public testing::Test PubFirst }; - void ExecuteTest(std::vector numberOfTopicsList, TopicMode topicModePub, LabelMode labelModePub, TopicMode topicModeSub, - LabelMode labelModeSub, StartOrderMode startOrder) + void ExecuteTest(std::vector numberOfTopicsList, TopicMode topicModePub, LabelMode labelModePub, + TopicMode topicModeSub, LabelMode labelModeSub, StartOrderMode startOrder) { for (auto numberOfTopics : numberOfTopicsList) { @@ -80,8 +77,7 @@ class FTest_PubSubPerf : public testing::Test auto registryUri = MakeTestRegistryUri(); SilKit::Tests::SimTestHarness testHarness(syncParticipantNames, registryUri, true); - auto definePubSpec = [topicModePub, labelModePub](int i) - { + auto definePubSpec = [topicModePub, labelModePub](int i) { std::string topic = "Topic"; if (topicModePub == TopicMode::IndividualTopics) { @@ -145,7 +141,7 @@ class FTest_PubSubPerf : public testing::Test bool allPublished = false; auto* timeSyncService = publisher->GetOrCreateTimeSyncService(); - auto CreatePub = [timeSyncService , &allPublished, testData, &publisher, &pubController, definePubSpec, + auto CreatePub = [timeSyncService, &allPublished, testData, &publisher, &pubController, definePubSpec, numberOfTopics]() { for (auto i = 0; i < numberOfTopics; i++) { @@ -153,18 +149,16 @@ class FTest_PubSubPerf : public testing::Test SilKit::Services::PubSub::PubSubSpec dataSpec = definePubSpec(i); pubController.push_back(publisher->Participant()->CreateDataPublisher(controllerName, dataSpec, 0)); } - timeSyncService->SetSimulationStepHandler( - [&allPublished, testData, pubController](auto, auto) { - if (!allPublished) + timeSyncService->SetSimulationStepHandler([&allPublished, testData, pubController](auto, auto) { + if (!allPublished) + { + for (auto p : pubController) { - for (auto p : pubController) - { - p->Publish(testData); - } - allPublished = true; + p->Publish(testData); } - }, - 1ms); + allPublished = true; + } + }, 1ms); }; // Subscriber @@ -173,22 +167,24 @@ class FTest_PubSubPerf : public testing::Test auto* subLifecycleService = subscriber->GetOrCreateLifecycleService(); auto CreateSub = [subLifecycleService, &receptionCount, &subscriber, defineSubSpec, numberOfTopics]() { - //auto subLogger = subscriber->GetOrGetLogger(); + //auto subLogger = subscriber->GetLogger(); //subLogger->Info(">>> Created Subscriber participant"); for (auto i = 0; i < numberOfTopics; i++) { const auto controllerName = "Sub-" + std::to_string(i); SilKit::Services::PubSub::PubSubSpec dataSpec = defineSubSpec(i); - (void)subscriber->Participant()->CreateDataSubscriber(controllerName, dataSpec, + (void)subscriber->Participant()->CreateDataSubscriber( + controllerName, dataSpec, [&receptionCount, numberOfTopics, &subLifecycleService]( - SilKit::Services::PubSub::IDataSubscriber* /*subscriber*/, const SilKit::Services::PubSub::DataMessageEvent& /*data*/) { - receptionCount++; - if (receptionCount == numberOfTopics) - { - subLifecycleService->Stop("Reception complete"); - } - }); + SilKit::Services::PubSub::IDataSubscriber* /*subscriber*/, + const SilKit::Services::PubSub::DataMessageEvent& /*data*/) { + receptionCount++; + if (receptionCount == numberOfTopics) + { + subLifecycleService->Stop("Reception complete"); + } + }); } }; @@ -219,7 +215,7 @@ TEST_F(FTest_PubSubPerf, test_pubsub_performance) TopicMode topicModeSub; LabelMode labelModeSub; StartOrderMode startOrder; - + // Larger set for production //std::vector testSetBadScaling{10, 100, 500}; //std::vector testSetGoodScaling{10, 100, 500, 1000, 5000, 10000}; @@ -231,40 +227,50 @@ TEST_F(FTest_PubSubPerf, test_pubsub_performance) std::cout << std::endl; std::cout << "# IndividualTopics + NoLabels + Pub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::IndividualTopics; labelModePub = LabelMode::NoLabels; - topicModeSub = TopicMode::IndividualTopics; labelModeSub = LabelMode::NoLabels; + topicModePub = TopicMode::IndividualTopics; + labelModePub = LabelMode::NoLabels; + topicModeSub = TopicMode::IndividualTopics; + labelModeSub = LabelMode::NoLabels; startOrder = StartOrderMode::PubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); std::cout << std::endl; std::cout << "# IndividualTopics + NoLabels + Sub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::IndividualTopics; labelModePub = LabelMode::NoLabels; - topicModeSub = TopicMode::IndividualTopics; labelModeSub = LabelMode::NoLabels; + topicModePub = TopicMode::IndividualTopics; + labelModePub = LabelMode::NoLabels; + topicModeSub = TopicMode::IndividualTopics; + labelModeSub = LabelMode::NoLabels; startOrder = StartOrderMode::SubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); - + std::cout << std::endl; std::cout << "# IndividualTopics + IndividualLabels + Pub Mandatory + Sub Mandatory + Pub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::IndividualTopics; labelModePub = LabelMode::IndividualLabelsMandatory; - topicModeSub = TopicMode::IndividualTopics; labelModeSub = LabelMode::IndividualLabelsMandatory; + topicModePub = TopicMode::IndividualTopics; + labelModePub = LabelMode::IndividualLabelsMandatory; + topicModeSub = TopicMode::IndividualTopics; + labelModeSub = LabelMode::IndividualLabelsMandatory; startOrder = StartOrderMode::PubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); std::cout << std::endl; std::cout << "# IndividualTopics + IndividualLabels + Pub Mandatory + Sub Mandatory + Sub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::IndividualTopics; labelModePub = LabelMode::IndividualLabelsMandatory; - topicModeSub = TopicMode::IndividualTopics; labelModeSub = LabelMode::IndividualLabelsMandatory; + topicModePub = TopicMode::IndividualTopics; + labelModePub = LabelMode::IndividualLabelsMandatory; + topicModeSub = TopicMode::IndividualTopics; + labelModeSub = LabelMode::IndividualLabelsMandatory; startOrder = StartOrderMode::SubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); - + std::cout << std::endl; std::cout << "# CommonTopic + NoLabels + Pub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::NoLabels; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::NoLabels; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::NoLabels; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::NoLabels; startOrder = StartOrderMode::PubFirst; ExecuteTest(testSetBadScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); @@ -281,67 +287,82 @@ TEST_F(FTest_PubSubPerf, test_pubsub_performance) std::cout << std::endl; std::cout << "# CommonTopic + IndividualLabels + Pub Optional + Sub Optional + Pub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::IndividualLabelsOptional; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::IndividualLabelsOptional; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::IndividualLabelsOptional; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::IndividualLabelsOptional; startOrder = StartOrderMode::PubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); std::cout << std::endl; std::cout << "# CommonTopic + IndividualLabels + Pub Optional + Sub Optional + Sub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::IndividualLabelsOptional; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::IndividualLabelsOptional; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::IndividualLabelsOptional; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::IndividualLabelsOptional; startOrder = StartOrderMode::SubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); - + std::cout << std::endl; std::cout << "# CommonTopic + IndividualLabels + Pub Mandatory + Sub Mandatory + Pub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::IndividualLabelsMandatory; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::IndividualLabelsMandatory; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::IndividualLabelsMandatory; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::IndividualLabelsMandatory; startOrder = StartOrderMode::PubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); std::cout << std::endl; std::cout << "# CommonTopic + IndividualLabels + Pub Mandatory + Sub Mandatory + Sub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::IndividualLabelsMandatory; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::IndividualLabelsMandatory; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::IndividualLabelsMandatory; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::IndividualLabelsMandatory; startOrder = StartOrderMode::SubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); std::cout << std::endl; std::cout << "# CommonTopic + IndividualLabels + Pub Mandatory + Sub Optional + Pub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::IndividualLabelsMandatory; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::IndividualLabelsOptional; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::IndividualLabelsMandatory; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::IndividualLabelsOptional; startOrder = StartOrderMode::PubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); std::cout << std::endl; std::cout << "# CommonTopic + IndividualLabels + Pub Mandatory + Sub Optional + Sub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::IndividualLabelsMandatory; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::IndividualLabelsOptional; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::IndividualLabelsMandatory; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::IndividualLabelsOptional; startOrder = StartOrderMode::SubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); std::cout << std::endl; std::cout << "# CommonTopic + IndividualLabels + Pub Optional + Sub Mandatory + Pub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::IndividualLabelsOptional; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::IndividualLabelsMandatory; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::IndividualLabelsOptional; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::IndividualLabelsMandatory; startOrder = StartOrderMode::PubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); std::cout << std::endl; std::cout << "# CommonTopic + IndividualLabels + Pub Optional + Sub Mandatory + Sub first" << std::endl; std::cout << "# NumberOfTopics Runtime(s)" << std::endl; - topicModePub = TopicMode::CommonTopic; labelModePub = LabelMode::IndividualLabelsOptional; - topicModeSub = TopicMode::CommonTopic; labelModeSub = LabelMode::IndividualLabelsMandatory; + topicModePub = TopicMode::CommonTopic; + labelModePub = LabelMode::IndividualLabelsOptional; + topicModeSub = TopicMode::CommonTopic; + labelModeSub = LabelMode::IndividualLabelsMandatory; startOrder = StartOrderMode::SubFirst; ExecuteTest(testSetGoodScaling, topicModePub, labelModePub, topicModeSub, labelModeSub, startOrder); - } } // anonymous namespace diff --git a/SilKit/IntegrationTests/FTest_ServiceDiscoveryPerf.cpp b/SilKit/IntegrationTests/FTest_ServiceDiscoveryPerf.cpp index bb2b56ac1..bac00520b 100644 --- a/SilKit/IntegrationTests/FTest_ServiceDiscoveryPerf.cpp +++ b/SilKit/IntegrationTests/FTest_ServiceDiscoveryPerf.cpp @@ -45,10 +45,7 @@ auto Now() class FTest_ServiceDiscoveryPerf : public testing::Test { protected: - - FTest_ServiceDiscoveryPerf() - { - } + FTest_ServiceDiscoveryPerf() {} void ExecuteTest(int numberOfServices, std::chrono::seconds timeout) { @@ -59,7 +56,7 @@ class FTest_ServiceDiscoveryPerf : public testing::Test SilKit::Tests::SimTestHarness testHarness(syncParticipantNames, registryUri, true); auto&& publisher = testHarness.GetParticipant("Publisher"); - + for (auto i = 0; i < numberOfServices; i++) { const auto topic = "TopicName-" + std::to_string(i); @@ -68,7 +65,7 @@ class FTest_ServiceDiscoveryPerf : public testing::Test (void)publisher->Participant()->CreateDataPublisher(controllerName, dataSpec, 0); } - auto logger = publisher->GetOrGetLogger(); + auto logger = publisher->GetLogger(); auto* lifecycleService = publisher->GetOrCreateLifecycleService(); auto* timeSyncService = publisher->GetOrCreateTimeSyncService(); @@ -76,9 +73,8 @@ class FTest_ServiceDiscoveryPerf : public testing::Test logger->Info("::::::::::: Sending STOP"); lifecycleService->Stop("Test complete"); }, 1ms); - - auto makeSubscriber = [&](auto subscriberName) - { + + auto makeSubscriber = [&](auto subscriberName) { auto&& subscriber = testHarness.GetParticipant(subscriberName)->Participant(); for (auto i = 0; i < numberOfServices; i++) @@ -87,9 +83,10 @@ class FTest_ServiceDiscoveryPerf : public testing::Test const auto controllerName = "SubCtrl" + std::to_string(i); SilKit::Services::PubSub::PubSubSpec dataSpec{topic, {}}; - (void)subscriber->CreateDataSubscriber(controllerName, dataSpec, - [](SilKit::Services::PubSub::IDataSubscriber* /*subscriber*/, const SilKit::Services::PubSub::DataMessageEvent& /*data*/) { - }); + (void)subscriber->CreateDataSubscriber( + controllerName, dataSpec, + [](SilKit::Services::PubSub::IDataSubscriber* /*subscriber*/, + const SilKit::Services::PubSub::DataMessageEvent& /*data*/) {}); } }; //ensure the subscriber is created after the publisher, to check announcements, not just incremental notifications @@ -99,15 +96,15 @@ class FTest_ServiceDiscoveryPerf : public testing::Test makeSubscriber("Subscriber2"); std::chrono::duration duration = Now() - start; - std::cout << "Test with " << numberOfServices << " services startup time: " << duration.count() << "sec" << std::endl; + std::cout << "Test with " << numberOfServices << " services startup time: " << duration.count() << "sec" + << std::endl; ASSERT_LT(duration, timeout) << "ServiceDiscovery should not have substantial impact on startup time" - << ": duration=" << duration.count(); + << ": duration=" << duration.count(); auto ok = testHarness.Run(timeout); // short timeout is significant for this test - ASSERT_TRUE(ok) - << " Expected a short startup time, not blocked by service discovery: timeout=" - << timeout.count(); + ASSERT_TRUE(ok) << " Expected a short startup time, not blocked by service discovery: timeout=" + << timeout.count(); } }; diff --git a/SilKit/IntegrationTests/GetTestPid.hpp b/SilKit/IntegrationTests/GetTestPid.hpp index fa262718d..bb5edb7d4 100644 --- a/SilKit/IntegrationTests/GetTestPid.hpp +++ b/SilKit/IntegrationTests/GetTestPid.hpp @@ -23,10 +23,10 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #if defined(_WIN32) -# include -# define getpid _getpid +#include +#define getpid _getpid #else // assume POSIX -# include +#include #endif inline auto MakeTestRegistryUri() diff --git a/SilKit/IntegrationTests/Hourglass/CMakeLists.txt b/SilKit/IntegrationTests/Hourglass/CMakeLists.txt index 19717b0f4..2e6d5c0d2 100644 --- a/SilKit/IntegrationTests/Hourglass/CMakeLists.txt +++ b/SilKit/IntegrationTests/Hourglass/CMakeLists.txt @@ -116,3 +116,10 @@ add_silkit_test_to_executable(SilKitHourglassTests LIBS S_Test_Hourglass ) + +add_silkit_test_to_executable(SilKitHourglassTests + SOURCES + Test_HourglassNetSim.cpp + LIBS + S_Test_Hourglass +) diff --git a/SilKit/IntegrationTests/Hourglass/MockCapi.cpp b/SilKit/IntegrationTests/Hourglass/MockCapi.cpp index 8ac042a31..0ab83ff4b 100644 --- a/SilKit/IntegrationTests/Hourglass/MockCapi.cpp +++ b/SilKit/IntegrationTests/Hourglass/MockCapi.cpp @@ -382,8 +382,8 @@ extern "C" return globalCapi->SilKit_LinController_Init(controller, config); } - SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_InitDynamic(SilKit_LinController* controller, - const SilKit_Experimental_LinControllerDynamicConfig* config) + SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_InitDynamic( + SilKit_LinController* controller, const SilKit_Experimental_LinControllerDynamicConfig* config) { return globalCapi->SilKit_Experimental_LinController_InitDynamic(controller, config); } @@ -515,8 +515,8 @@ extern "C" return globalCapi->SilKit_Experimental_LinController_RemoveFrameHeaderHandler(controller, handlerId); } - SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_SendDynamicResponse( - SilKit_LinController* controller, const SilKit_LinFrame* frame) + SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_SendDynamicResponse(SilKit_LinController* controller, + const SilKit_LinFrame* frame) { return globalCapi->SilKit_Experimental_LinController_SendDynamicResponse(controller, frame); } @@ -779,6 +779,13 @@ extern "C" participantConfigurationString); } + SilKit_ReturnCode SilKitCALL SilKit_ParticipantConfiguration_FromFile( + SilKit_ParticipantConfiguration** outParticipantConfiguration, const char* participantConfigurationFilename) + { + return globalCapi->SilKit_ParticipantConfiguration_FromFile(outParticipantConfiguration, + participantConfigurationFilename); + } + SilKit_ReturnCode SilKitCALL SilKit_ParticipantConfiguration_Destroy(SilKit_ParticipantConfiguration* participantConfiguration) { @@ -871,12 +878,11 @@ extern "C" } SilKit_ReturnCode SilKitCALL SilKit_RpcClient_CallWithTimeout(SilKit_RpcClient* self, - const SilKit_ByteVector* argumentData, - SilKit_NanosecondsTime timeout, - void* userContext) + const SilKit_ByteVector* argumentData, + SilKit_NanosecondsTime timeout, void* userContext) { return globalCapi->SilKit_RpcClient_CallWithTimeout(self, argumentData, timeout, userContext); - } + } SilKit_ReturnCode SilKitCALL SilKit_RpcClient_SetCallResultHandler(SilKit_RpcClient* self, void* context, SilKit_RpcCallResultHandler_t handler) @@ -953,4 +959,64 @@ extern "C" { return globalCapi->SilKit_Version_GitHash(outVersionGitHash); } + + // Network Simulator + + SilKit_ReturnCode SilKitCALL SilKit_Experimental_NetworkSimulator_Create( + SilKit_Experimental_NetworkSimulator** outNetworkSimulator, SilKit_Participant* participant) + { + return globalCapi->SilKit_Experimental_NetworkSimulator_Create(outNetworkSimulator, participant); + } + + SilKit_ReturnCode SilKitCALL SilKit_Experimental_NetworkSimulator_SimulateNetwork( + SilKit_Experimental_NetworkSimulator* networkSimulator, const char* networkName, + SilKit_Experimental_SimulatedNetworkType networkType, void* simulatedNetwork, + const SilKit_Experimental_SimulatedNetworkFunctions* simulatedNetworkFunctions) + { + return globalCapi->SilKit_Experimental_NetworkSimulator_SimulateNetwork( + networkSimulator, networkName, networkType, simulatedNetwork, simulatedNetworkFunctions); + } + + SilKit_ReturnCode SilKitCALL + SilKit_Experimental_NetworkSimulator_Start(SilKit_Experimental_NetworkSimulator* networkSimulator) + { + return globalCapi->SilKit_Experimental_NetworkSimulator_Start(networkSimulator); + } + + // CanEventProducer + + SilKit_ReturnCode SilKitCALL SilKit_Experimental_CanEventProducer_Produce( + SilKit_Experimental_CanEventProducer* eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers) + { + return globalCapi->SilKit_Experimental_CanEventProducer_Produce(eventProducer, cEvent, receivers); + } + + // FlexRayEventProducer + + SilKit_ReturnCode SilKitCALL SilKit_Experimental_FlexRayEventProducer_Produce( + SilKit_Experimental_FlexRayEventProducer* eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers) + { + return globalCapi->SilKit_Experimental_FlexRayEventProducer_Produce(eventProducer, cEvent, receivers); + } + + // EthEventProducer + + SilKit_ReturnCode SilKitCALL SilKit_Experimental_EthernetEventProducer_Produce( + SilKit_Experimental_EthernetEventProducer* eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers) + { + return globalCapi->SilKit_Experimental_EthernetEventProducer_Produce(eventProducer, cEvent, receivers); + } + + + // LinEventProducer + + SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinEventProducer_Produce( + SilKit_Experimental_LinEventProducer* eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers) + { + return globalCapi->SilKit_Experimental_LinEventProducer_Produce(eventProducer, cEvent, receivers); + } } diff --git a/SilKit/IntegrationTests/Hourglass/MockCapi.hpp b/SilKit/IntegrationTests/Hourglass/MockCapi.hpp index da9bcd325..a348cd3e0 100644 --- a/SilKit/IntegrationTests/Hourglass/MockCapi.hpp +++ b/SilKit/IntegrationTests/Hourglass/MockCapi.hpp @@ -422,6 +422,10 @@ class MockCapi (SilKit_ParticipantConfiguration * *outParticipantConfiguration, const char* participantConfigurationString)); + MOCK_METHOD(SilKit_ReturnCode, SilKit_ParticipantConfiguration_FromFile, + (SilKit_ParticipantConfiguration * *outParticipantConfiguration, + const char* participantConfigurationFilename)); + MOCK_METHOD(SilKit_ReturnCode, SilKit_ParticipantConfiguration_Destroy, (SilKit_ParticipantConfiguration * participantConfiguration)); @@ -471,9 +475,9 @@ class MockCapi MOCK_METHOD(SilKit_ReturnCode, SilKit_RpcClient_Call, (SilKit_RpcClient * self, const SilKit_ByteVector* argumentData, void* userContext)); - MOCK_METHOD( SilKit_ReturnCode, SilKit_RpcClient_CallWithTimeout,(SilKit_RpcClient* self, - const SilKit_ByteVector* argumentData, - SilKit_NanosecondsTime timeout, void* userContext)); + MOCK_METHOD(SilKit_ReturnCode, SilKit_RpcClient_CallWithTimeout, + (SilKit_RpcClient * self, const SilKit_ByteVector* argumentData, SilKit_NanosecondsTime timeout, + void* userContext)); MOCK_METHOD(SilKit_ReturnCode, SilKit_RpcClient_SetCallResultHandler, (SilKit_RpcClient * self, void* context, SilKit_RpcCallResultHandler_t handler)); @@ -512,6 +516,43 @@ class MockCapi MOCK_METHOD(SilKit_ReturnCode, SilKit_Version_VersionSuffix, (const char** outVersionVersionSuffix)); MOCK_METHOD(SilKit_ReturnCode, SilKit_Version_GitHash, (const char** outVersionGitHash)); + + + // NetworkSimulator + + MOCK_METHOD(SilKit_ReturnCode, SilKit_Experimental_NetworkSimulator_Create, + (SilKit_Experimental_NetworkSimulator * *outNetworkSimulator, SilKit_Participant* participant)); + + MOCK_METHOD(SilKit_ReturnCode, SilKit_Experimental_NetworkSimulator_Start, + (SilKit_Experimental_NetworkSimulator * networkSimulator)); + + MOCK_METHOD(SilKit_ReturnCode, SilKit_Experimental_NetworkSimulator_SimulateNetwork, + (SilKit_Experimental_NetworkSimulator * networkSimulator, const char* networkName, + SilKit_Experimental_SimulatedNetworkType networkType, void* simulatedNetwork, + const SilKit_Experimental_SimulatedNetworkFunctions* simulatedNetworkFunctions)); + + // CanEventProducer + + MOCK_METHOD(SilKit_ReturnCode, SilKit_Experimental_CanEventProducer_Produce, + (SilKit_Experimental_CanEventProducer * eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers)); + + // FlexRayEventProducer + + MOCK_METHOD(SilKit_ReturnCode, SilKit_Experimental_FlexRayEventProducer_Produce, + (SilKit_Experimental_FlexRayEventProducer * eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers)); + + // EthEventProducer + + MOCK_METHOD(SilKit_ReturnCode, SilKit_Experimental_EthernetEventProducer_Produce, + (SilKit_Experimental_EthernetEventProducer * eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers)); + // LinEventProducer + + MOCK_METHOD(SilKit_ReturnCode, SilKit_Experimental_LinEventProducer_Produce, + (SilKit_Experimental_LinEventProducer * eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers)); }; -} // namespace SilKitHourglassTests \ No newline at end of file +} // namespace SilKitHourglassTests diff --git a/SilKit/IntegrationTests/Hourglass/MockCapiTest.hpp b/SilKit/IntegrationTests/Hourglass/MockCapiTest.hpp index 2a0194c31..a444a514f 100644 --- a/SilKit/IntegrationTests/Hourglass/MockCapiTest.hpp +++ b/SilKit/IntegrationTests/Hourglass/MockCapiTest.hpp @@ -32,8 +32,14 @@ class MockCapiTest : public testing::Test MockCapi capi; protected: - void SetUp() override { capi.SetUpGlobalCapi(); } - void TearDown() override { capi.TearDownGlobalCapi(); } + void SetUp() override + { + capi.SetUpGlobalCapi(); + } + void TearDown() override + { + capi.TearDownGlobalCapi(); + } }; } // namespace SilKitHourglassTests diff --git a/SilKit/IntegrationTests/Hourglass/Test_HourglassLin.cpp b/SilKit/IntegrationTests/Hourglass/Test_HourglassLin.cpp index 30a142b4e..9fe18201d 100644 --- a/SilKit/IntegrationTests/Hourglass/Test_HourglassLin.cpp +++ b/SilKit/IntegrationTests/Hourglass/Test_HourglassLin.cpp @@ -78,9 +78,7 @@ MATCHER_P(LinControllerDynamicConfigMatcher, controlFrame, "") const auto sameControllerMode = static_cast(config1.controllerMode) == static_cast(config2->controllerMode); - if ((config1.baudRate != config2->baudRate) - || !sameControllerMode - ) + if ((config1.baudRate != config2->baudRate) || !sameControllerMode) { return false; } @@ -162,7 +160,8 @@ TEST_F(Test_HourglassLin, SilKit_LinController_InitDynamic) controllerConfig.baudRate = 1234; controllerConfig.controllerMode = LinControllerMode::Master; - EXPECT_CALL(capi, SilKit_Experimental_LinController_InitDynamic(mockLinController, LinControllerDynamicConfigMatcher(controllerConfig))) + EXPECT_CALL(capi, SilKit_Experimental_LinController_InitDynamic( + mockLinController, LinControllerDynamicConfigMatcher(controllerConfig))) .Times(1); LinController.ExperimentalInitDynamic(controllerConfig); } diff --git a/SilKit/IntegrationTests/Hourglass/Test_HourglassNetSim.cpp b/SilKit/IntegrationTests/Hourglass/Test_HourglassNetSim.cpp new file mode 100644 index 000000000..680390544 --- /dev/null +++ b/SilKit/IntegrationTests/Hourglass/Test_HourglassNetSim.cpp @@ -0,0 +1,1305 @@ +/* Copyright (c) 2022 Vector Informatik GmbH + +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. */ + +#include "gtest/gtest.h" +#include "gmock/gmock.h" + +#include "silkit/capi/SilKit.h" + +#include "silkit/SilKit.hpp" +#include "silkit/detail/impl/ThrowOnError.hpp" + +#include "MockCapiTest.hpp" + +namespace { + +using testing::DoAll; +using testing::SetArgPointee; +using testing::Return; + +using namespace SilKit::Experimental::NetworkSimulation; + +MATCHER_P(ReceiverMatcher, controlReceivers, "") +{ + *result_listener + << "Matches SilKit_Experimental_EventReceivers (arg, C-API) to EventReceivers (controlFrame Cpp API)"; + const SilKit::Util::Span cppReceivers = controlReceivers; + const SilKit_Experimental_EventReceivers* cReceivers = arg; + if (cppReceivers.size() != cReceivers->numReceivers) + { + return false; + } + for (size_t i = 0; i < cppReceivers.size(); i++) + { + if (cppReceivers[i] != cReceivers->controllerDescriptors[i]) + { + return false; + } + } + return true; +} + +// ----------------------------- +// Matcher for Can +// ----------------------------- + +bool CompareCanFrame(const SilKit::Services::Can::CanFrame& cppFrame, const SilKit_CanFrame* cFrame) +{ + using namespace SilKit::Services::Can; + + if (cppFrame.canId != cFrame->id || cppFrame.dlc != cFrame->dlc || cppFrame.dataField.size() != cFrame->data.size) + { + return false; + } + for (size_t i = 0; i < cppFrame.dataField.size(); i++) + { + if (cppFrame.dataField[i] != cFrame->data.data[i]) + { + return false; + } + } + if (cppFrame.sdt != cFrame->sdt || cppFrame.vcid != cFrame->vcid || cppFrame.af != cFrame->af) + { + return false; + } + if (((cppFrame.flags & static_cast(CanFrameFlag::Ide)) != 0) + != ((cFrame->flags & SilKit_CanFrameFlag_ide) != 0)) + { + return false; + } + if (((cppFrame.flags & static_cast(CanFrameFlag::Fdf)) != 0) + != ((cFrame->flags & SilKit_CanFrameFlag_fdf) != 0)) + { + return false; + } + if (((cppFrame.flags & static_cast(CanFrameFlag::Brs)) != 0) + != ((cFrame->flags & SilKit_CanFrameFlag_brs) != 0)) + { + return false; + } + if (((cppFrame.flags & static_cast(CanFrameFlag::Esi)) != 0) + != ((cFrame->flags & SilKit_CanFrameFlag_esi) != 0)) + { + return false; + } + if (((cppFrame.flags & static_cast(CanFrameFlag::Rtr)) != 0) + != ((cFrame->flags & SilKit_CanFrameFlag_rtr) != 0)) + { + return false; + } + if (((cppFrame.flags & static_cast(CanFrameFlag::Xlf)) != 0) + != ((cFrame->flags & SilKit_CanFrameFlag_xlf) != 0)) + { + return false; + } + if (((cppFrame.flags & static_cast(CanFrameFlag::Sec)) != 0) + != ((cFrame->flags & SilKit_CanFrameFlag_sec) != 0)) + { + return false; + } + return true; +} + +MATCHER_P(CanFrameEventMatcher, controlFrame, "") +{ + using namespace SilKit::Services::Can; + *result_listener << "Matches SilKit_CanFrameEvent (arg, C-API) to CanFrameEvent (controlFrame Cpp API)"; + const CanFrameEvent cppFrameEvent = controlFrame; + const SilKit_CanFrameEvent* cFrameEvent = (SilKit_CanFrameEvent*)arg; + + if ((SilKit_Direction)cppFrameEvent.direction != cFrameEvent->direction + || static_cast(cppFrameEvent.timestamp.count()) != cFrameEvent->timestamp + || cppFrameEvent.userContext != cFrameEvent->userContext) + { + return false; + } + + return CompareCanFrame(cppFrameEvent.frame, cFrameEvent->frame); +} + +MATCHER_P(NetSimCanFrameRequestMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_CanFrameRequest (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::CanFrameRequest (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_CanFrameRequest cFrameRequest = (SilKit_Experimental_NetSim_CanFrameRequest)controlMsg; + SilKit::Experimental::NetworkSimulation::Can::CanFrameRequest cppFrameRequest = + (SilKit::Experimental::NetworkSimulation::Can::CanFrameRequest)arg; + + if (cppFrameRequest.userContext != cFrameRequest.userContext) + { + return false; + } + + return CompareCanFrame(cppFrameRequest.frame, cFrameRequest.frame); +} + +MATCHER_P(NetSimCanConfigureBaudrateMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_CanConfigureBaudrate (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::CanConfigureBaudrate (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_CanConfigureBaudrate cCanConfigureBaudrate = + (SilKit_Experimental_NetSim_CanConfigureBaudrate)controlMsg; + SilKit::Experimental::NetworkSimulation::Can::CanConfigureBaudrate cppCanConfigureBaudrate = + (SilKit::Experimental::NetworkSimulation::Can::CanConfigureBaudrate)arg; + + if (cppCanConfigureBaudrate.baudRate != cCanConfigureBaudrate.rate + || cppCanConfigureBaudrate.fdBaudRate != cCanConfigureBaudrate.fdRate + || cppCanConfigureBaudrate.xlBaudRate != cCanConfigureBaudrate.xlRate) + { + return false; + } + + return true; +} + + +MATCHER_P(NetSimCanControllerModeMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_CanControllerMode (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::CanControllerMode (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_CanControllerMode cCanControllerMode = + (SilKit_Experimental_NetSim_CanControllerMode)controlMsg; + SilKit::Experimental::NetworkSimulation::Can::CanControllerMode cppCanControllerMode = + (SilKit::Experimental::NetworkSimulation::Can::CanControllerMode)arg; + + if (cppCanControllerMode.canControllerModeFlags != cCanControllerMode.canControllerModeFlags + || (SilKit_CanControllerState)cppCanControllerMode.state != cCanControllerMode.state) + { + return false; + } + + return true; +} + +// ----------------------------- +// Matcher for Ethernet +// ----------------------------- + +bool CompareEthernetFrame(const SilKit::Services::Ethernet::EthernetFrame& cppFrame, const SilKit_EthernetFrame* cFrame) +{ + using namespace SilKit::Services::Ethernet; + + if (cppFrame.raw.size() != cFrame->raw.size) + { + return false; + } + for (size_t i = 0; i < cppFrame.raw.size(); i++) + { + if (cppFrame.raw[i] != cFrame->raw.data[i]) + { + return false; + } + } + return true; +} + +MATCHER_P(EthernetFrameEventMatcher, controlFrame, "") +{ + using namespace SilKit::Services::Ethernet; + *result_listener << "Matches SilKit_EthernetFrameEvent (arg, C-API) to EthernetFrameEvent (controlFrame Cpp API)"; + const EthernetFrameEvent cppFrameEvent = controlFrame; + const SilKit_EthernetFrameEvent* cFrameEvent = (SilKit_EthernetFrameEvent*)arg; + + if ((SilKit_Direction)cppFrameEvent.direction != cFrameEvent->direction + || static_cast(cppFrameEvent.timestamp.count()) != cFrameEvent->timestamp + || cppFrameEvent.userContext != cFrameEvent->userContext) + { + return false; + } + + return CompareEthernetFrame(cppFrameEvent.frame, cFrameEvent->ethernetFrame); +} + +MATCHER_P(NetSimEthernetFrameRequestMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_EthernetFrameRequest (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::EthernetFrameRequest (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_EthernetFrameRequest cFrameRequest = + (SilKit_Experimental_NetSim_EthernetFrameRequest)controlMsg; + SilKit::Experimental::NetworkSimulation::Ethernet::EthernetFrameRequest cppFrameRequest = + (SilKit::Experimental::NetworkSimulation::Ethernet::EthernetFrameRequest)arg; + + if (cppFrameRequest.userContext != cFrameRequest.userContext) + { + return false; + } + + return CompareEthernetFrame(cppFrameRequest.ethernetFrame, cFrameRequest.ethernetFrame); +} + +MATCHER_P(NetSimEthernetControllerModeMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_EthernetControllerMode (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::EthernetControllerMode (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_EthernetControllerMode cControllerMode = + (SilKit_Experimental_NetSim_EthernetControllerMode)controlMsg; + SilKit::Experimental::NetworkSimulation::Ethernet::EthernetControllerMode cppControllerMode = + (SilKit::Experimental::NetworkSimulation::Ethernet::EthernetControllerMode)arg; + + if ((SilKit_EthernetControllerMode)cppControllerMode.mode != cControllerMode.mode) + { + return false; + } + + return true; +} + +// ----------------------------- +// Matcher for FlexRay +// ----------------------------- + +bool CompareFlexrayFrame(const SilKit::Services::Flexray::FlexrayFrame& cppFrame, const SilKit_FlexrayFrame* cFrame) +{ + if (cppFrame.header.cycleCount != cFrame->header->cycleCount || cppFrame.header.flags != cFrame->header->flags + || cppFrame.header.frameId != cFrame->header->frameId || cppFrame.header.headerCrc != cFrame->header->headerCrc + || cppFrame.header.payloadLength != cFrame->header->payloadLength) + { + return false; + } + if (cppFrame.payload.size() != cFrame->payload.size) + { + return false; + } + for (size_t i = 0; i < cppFrame.payload.size(); i++) + { + if (cppFrame.payload[i] != cFrame->payload.data[i]) + { + return false; + } + } + return true; +} + + +bool CompareFlexrayTxBufferConfig(const SilKit::Services::Flexray::FlexrayTxBufferConfig& cppTxBufferConfig, + const SilKit_FlexrayTxBufferConfig* cTxBufferConfig) +{ + if ((SilKit_FlexrayChannel)cppTxBufferConfig.channels != cTxBufferConfig->channels + || (SilKit_Bool)cppTxBufferConfig.hasPayloadPreambleIndicator != cTxBufferConfig->hasPayloadPreambleIndicator + || cppTxBufferConfig.headerCrc != cTxBufferConfig->headerCrc + || cppTxBufferConfig.offset != cTxBufferConfig->offset + || cppTxBufferConfig.repetition != cTxBufferConfig->repetition + || cppTxBufferConfig.slotId != cTxBufferConfig->slotId + || (SilKit_FlexrayTransmissionMode)cppTxBufferConfig.transmissionMode != cTxBufferConfig->transmissionMode) + { + return false; + } + return true; +} + +MATCHER_P(FlexrayFrameEventMatcher, controlFrame, "") +{ + using namespace SilKit::Services::Flexray; + *result_listener << "Matches SilKit_FlexrayFrameEvent (arg, C-API) to FlexrayFrameEvent (controlFrame Cpp API)"; + const FlexrayFrameEvent cppFrameEvent = controlFrame; + const SilKit_FlexrayFrameEvent* cFrameEvent = (SilKit_FlexrayFrameEvent*)arg; + + if ((SilKit_FlexrayChannel)cppFrameEvent.channel != cFrameEvent->channel + || static_cast(cppFrameEvent.timestamp.count()) != cFrameEvent->timestamp) + { + return false; + } + + return CompareFlexrayFrame(cppFrameEvent.frame, cFrameEvent->frame); +} + +MATCHER_P(NetSimFlexrayHostCommandMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_FlexrayHostCommand (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::Flexray::FlexrayHostCommand (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_FlexrayHostCommand cHostCommand = + (SilKit_Experimental_NetSim_FlexrayHostCommand)controlMsg; + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayHostCommand cppHostCommand = + (SilKit::Experimental::NetworkSimulation::Flexray::FlexrayHostCommand)arg; + + if ((uint8_t)cppHostCommand.command != cHostCommand.chiCommand) + { + return false; + } + + return true; +} + +MATCHER_P(NetSimFlexrayControllerConfigMatcher, controlMsg, "") +{ + *result_listener + << "Matches SilKit_Experimental_NetSim_FlexrayControllerConfig (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_FlexrayControllerConfig cControllerConfig = + (SilKit_Experimental_NetSim_FlexrayControllerConfig)controlMsg; + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig cppControllerConfig = + (SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig)arg; + + if (cppControllerConfig.bufferConfigs.size() != cControllerConfig.numBufferConfigs) + { + return false; + } + for (size_t i = 0; i < cppControllerConfig.bufferConfigs.size(); i++) + { + if (!CompareFlexrayTxBufferConfig(cppControllerConfig.bufferConfigs[i], &cControllerConfig.bufferConfigs[i])) + { + return false; + } + } + + if (cppControllerConfig.clusterParams.gColdstartAttempts != cControllerConfig.clusterParams->gColdstartAttempts + || cppControllerConfig.clusterParams.gCycleCountMax != cControllerConfig.clusterParams->gCycleCountMax + || cppControllerConfig.clusterParams.gdActionPointOffset != cControllerConfig.clusterParams->gdActionPointOffset + || cppControllerConfig.clusterParams.gdDynamicSlotIdlePhase + != cControllerConfig.clusterParams->gdDynamicSlotIdlePhase + || cppControllerConfig.clusterParams.gdMiniSlot != cControllerConfig.clusterParams->gdMiniSlot + || cppControllerConfig.clusterParams.gdMiniSlotActionPointOffset + != cControllerConfig.clusterParams->gdMiniSlotActionPointOffset + || cppControllerConfig.clusterParams.gdStaticSlot != cControllerConfig.clusterParams->gdStaticSlot + || cppControllerConfig.clusterParams.gdSymbolWindow != cControllerConfig.clusterParams->gdSymbolWindow + || cppControllerConfig.clusterParams.gdSymbolWindowActionPointOffset + != cControllerConfig.clusterParams->gdSymbolWindowActionPointOffset + || cppControllerConfig.clusterParams.gdTSSTransmitter != cControllerConfig.clusterParams->gdTSSTransmitter + || cppControllerConfig.clusterParams.gdWakeupTxActive != cControllerConfig.clusterParams->gdWakeupTxActive + || cppControllerConfig.clusterParams.gdWakeupTxIdle != cControllerConfig.clusterParams->gdWakeupTxIdle + || cppControllerConfig.clusterParams.gListenNoise != cControllerConfig.clusterParams->gListenNoise + || cppControllerConfig.clusterParams.gMacroPerCycle != cControllerConfig.clusterParams->gMacroPerCycle + || cppControllerConfig.clusterParams.gMaxWithoutClockCorrectionFatal + != cControllerConfig.clusterParams->gMaxWithoutClockCorrectionFatal + || cppControllerConfig.clusterParams.gMaxWithoutClockCorrectionPassive + != cControllerConfig.clusterParams->gMaxWithoutClockCorrectionPassive + || cppControllerConfig.clusterParams.gNumberOfMiniSlots != cControllerConfig.clusterParams->gNumberOfMiniSlots + || cppControllerConfig.clusterParams.gNumberOfStaticSlots + != cControllerConfig.clusterParams->gNumberOfStaticSlots + || cppControllerConfig.clusterParams.gPayloadLengthStatic + != cControllerConfig.clusterParams->gPayloadLengthStatic + || cppControllerConfig.clusterParams.gSyncFrameIDCountMax + != cControllerConfig.clusterParams->gSyncFrameIDCountMax) + { + return false; + } + + if (cppControllerConfig.nodeParams.pAllowHaltDueToClock != cControllerConfig.nodeParams->pAllowHaltDueToClock + || cppControllerConfig.nodeParams.pAllowPassiveToActive != cControllerConfig.nodeParams->pAllowPassiveToActive + || (SilKit_FlexrayChannel)cppControllerConfig.nodeParams.pChannels != cControllerConfig.nodeParams->pChannels + || cppControllerConfig.nodeParams.pClusterDriftDamping != cControllerConfig.nodeParams->pClusterDriftDamping + || cppControllerConfig.nodeParams.pdAcceptedStartupRange != cControllerConfig.nodeParams->pdAcceptedStartupRange + || cppControllerConfig.nodeParams.pdListenTimeout != cControllerConfig.nodeParams->pdListenTimeout + || (SilKit_FlexrayClockPeriod)cppControllerConfig.nodeParams.pdMicrotick + != cControllerConfig.nodeParams->pdMicrotick + || cppControllerConfig.nodeParams.pKeySlotId != cControllerConfig.nodeParams->pKeySlotId + || cppControllerConfig.nodeParams.pKeySlotOnlyEnabled != cControllerConfig.nodeParams->pKeySlotOnlyEnabled + || cppControllerConfig.nodeParams.pKeySlotUsedForStartup != cControllerConfig.nodeParams->pKeySlotUsedForStartup + || cppControllerConfig.nodeParams.pKeySlotUsedForSync != cControllerConfig.nodeParams->pKeySlotUsedForSync + || cppControllerConfig.nodeParams.pLatestTx != cControllerConfig.nodeParams->pLatestTx + || cppControllerConfig.nodeParams.pMacroInitialOffsetA != cControllerConfig.nodeParams->pMacroInitialOffsetA + || cppControllerConfig.nodeParams.pMacroInitialOffsetB != cControllerConfig.nodeParams->pMacroInitialOffsetB + || cppControllerConfig.nodeParams.pMicroInitialOffsetA != cControllerConfig.nodeParams->pMicroInitialOffsetA + || cppControllerConfig.nodeParams.pMicroInitialOffsetB != cControllerConfig.nodeParams->pMicroInitialOffsetB + || cppControllerConfig.nodeParams.pMicroPerCycle != cControllerConfig.nodeParams->pMicroPerCycle + || cppControllerConfig.nodeParams.pOffsetCorrectionOut != cControllerConfig.nodeParams->pOffsetCorrectionOut + || cppControllerConfig.nodeParams.pOffsetCorrectionStart != cControllerConfig.nodeParams->pOffsetCorrectionStart + || cppControllerConfig.nodeParams.pRateCorrectionOut != cControllerConfig.nodeParams->pRateCorrectionOut + || cppControllerConfig.nodeParams.pSamplesPerMicrotick != cControllerConfig.nodeParams->pSamplesPerMicrotick + || (SilKit_FlexrayChannel)cppControllerConfig.nodeParams.pWakeupChannel + != cControllerConfig.nodeParams->pWakeupChannel + || cppControllerConfig.nodeParams.pWakeupPattern != cControllerConfig.nodeParams->pWakeupPattern) + { + return false; + } + + return true; +} + +MATCHER_P(NetSimFlexrayTxBufferConfigUpdateMatcher, controlMsg, "") +{ + *result_listener + << "Matches SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferConfigUpdate (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate cTxBufferConfigUpdate = + (SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate)controlMsg; + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferConfigUpdate cppTxBufferConfigUpdate = + (SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferConfigUpdate)arg; + + if (cppTxBufferConfigUpdate.txBufferIndex != cTxBufferConfigUpdate.txBufferIdx) + { + return false; + } + + return CompareFlexrayTxBufferConfig(cppTxBufferConfigUpdate.txBufferConfig, cTxBufferConfigUpdate.txBufferConfig); +} + +MATCHER_P(NetSimFlexrayTxBufferUpdateMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_FlexrayTxBufferUpdate (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_FlexrayTxBufferUpdate cTxBufferUpdate = + (SilKit_Experimental_NetSim_FlexrayTxBufferUpdate)controlMsg; + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate cppTxBufferUpdate = + (SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate)arg; + + if ((SilKit_Bool)cppTxBufferUpdate.payloadDataValid != cTxBufferUpdate.payloadDataValid) + { + return false; + } + + if (cppTxBufferUpdate.payload.size() != cTxBufferUpdate.payload.size) + { + return false; + } + for (size_t i = 0; i < cppTxBufferUpdate.payload.size(); i++) + { + if (cppTxBufferUpdate.payload[i] != cTxBufferUpdate.payload.data[i]) + { + return false; + } + } + return true; +} + +// ----------------------------- +// Matcher for Lin +// ----------------------------- + +bool CompareLinFrame(const SilKit::Services::Lin::LinFrame& cppFrame, const SilKit_LinFrame* cFrame) +{ + using namespace SilKit::Services::Lin; + if ((SilKit_LinChecksumModel)cppFrame.checksumModel != cFrame->checksumModel + || cppFrame.dataLength != cFrame->dataLength || cppFrame.id != cFrame->id) + { + return false; + } + for (size_t i = 0; i < cppFrame.data.size(); i++) + { + if (cppFrame.data[i] != cFrame->data[i]) + { + return false; + } + } + return true; +} + +MATCHER_P(LinFrameStatusEventMatcher, controlFrame, "") +{ + using namespace SilKit::Services::Lin; + *result_listener << "Matches SilKit_LinFrameStatusEvent (arg, C-API) to LinFrameStatusEvent (controlFrame Cpp API)"; + const LinFrameStatusEvent cppFrameEvent = controlFrame; + const SilKit_LinFrameStatusEvent* cFrameEvent = (SilKit_LinFrameStatusEvent*)arg; + + if ((SilKit_LinFrameStatus)cppFrameEvent.status != cFrameEvent->status + || static_cast(cppFrameEvent.timestamp.count()) != cFrameEvent->timestamp) + { + return false; + } + + return CompareLinFrame(cppFrameEvent.frame, cFrameEvent->frame); +} + + +MATCHER_P(NetSimLinFrameRequestMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_LinFrameRequest (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::LinFrameRequest (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_LinFrameRequest cFrameRequest = (SilKit_Experimental_NetSim_LinFrameRequest)controlMsg; + SilKit::Experimental::NetworkSimulation::Lin::LinFrameRequest cppFrameRequest = + (SilKit::Experimental::NetworkSimulation::Lin::LinFrameRequest)arg; + + if ((SilKit_LinFrameResponseType)cppFrameRequest.responseType != cFrameRequest.responseType) + { + return false; + } + + return CompareLinFrame(cppFrameRequest.frame, cFrameRequest.frame); +} + + +MATCHER_P(NetSimLinFrameHeaderRequestMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_LinFrameHeaderRequest (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::LinFrameHeaderRequest (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_LinFrameHeaderRequest cFrameHeaderRequest = + (SilKit_Experimental_NetSim_LinFrameHeaderRequest)controlMsg; + SilKit::Experimental::NetworkSimulation::Lin::LinFrameHeaderRequest cppFrameHeaderRequest = + (SilKit::Experimental::NetworkSimulation::Lin::LinFrameHeaderRequest)arg; + + if (cppFrameHeaderRequest.id != cFrameHeaderRequest.id) + { + return false; + } + + return true; +} + +MATCHER_P(NetSimLinWakeupPulseMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_LinWakeupPulse (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::LinWakeupPulse (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_LinWakeupPulse cWakeupPulse = (SilKit_Experimental_NetSim_LinWakeupPulse)controlMsg; + SilKit::Experimental::NetworkSimulation::Lin::LinWakeupPulse cppWakeupPulse = + (SilKit::Experimental::NetworkSimulation::Lin::LinWakeupPulse)arg; + + if (static_cast(cppWakeupPulse.timestamp.count()) != cWakeupPulse.timestamp) + { + return false; + } + + return true; +} + +MATCHER_P(NetSimLinControllerConfigMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_LinControllerConfig (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::LinControllerConfig (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_LinControllerConfig cControllerConfig = + (SilKit_Experimental_NetSim_LinControllerConfig)controlMsg; + SilKit::Experimental::NetworkSimulation::Lin::LinControllerConfig cppControllerConfig = + (SilKit::Experimental::NetworkSimulation::Lin::LinControllerConfig)arg; + + if (cppControllerConfig.baudRate != cControllerConfig.baudRate + || (SilKit_LinControllerMode)cppControllerConfig.controllerMode != cControllerConfig.controllerMode + || (uint8_t)cppControllerConfig.simulationMode != cControllerConfig.simulationMode) + { + return false; + } + + if (cppControllerConfig.frameResponses.size() != cControllerConfig.numFrameResponses) + { + return false; + } + + for (size_t i = 0; i < cppControllerConfig.frameResponses.size(); i++) + { + if ((SilKit_LinFrameResponseMode)cppControllerConfig.frameResponses[i].responseMode + != cControllerConfig.frameResponses[i].responseMode) + { + return false; + } + if (!CompareLinFrame(cppControllerConfig.frameResponses[i].frame, cControllerConfig.frameResponses[i].frame)) + { + return false; + } + } + + return true; +} + + +MATCHER_P(NetSimLinFrameResponseUpdateMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_LinFrameResponseUpdate (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::LinFrameResponseUpdate (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_LinFrameResponseUpdate cFrameResponseUpdate = + (SilKit_Experimental_NetSim_LinFrameResponseUpdate)controlMsg; + SilKit::Experimental::NetworkSimulation::Lin::LinFrameResponseUpdate cppFrameResponseUpdate = + (SilKit::Experimental::NetworkSimulation::Lin::LinFrameResponseUpdate)arg; + + for (size_t i = 0; i < cppFrameResponseUpdate.frameResponses.size(); i++) + { + if ((SilKit_LinFrameResponseMode)cppFrameResponseUpdate.frameResponses[i].responseMode + != cFrameResponseUpdate.frameResponses[i].responseMode) + { + return false; + } + if (!CompareLinFrame(cppFrameResponseUpdate.frameResponses[i].frame, + cFrameResponseUpdate.frameResponses[i].frame)) + { + return false; + } + } + + return true; +} + + +MATCHER_P(NetSimLinControllerStatusUpdateMatcher, controlMsg, "") +{ + *result_listener << "Matches SilKit_Experimental_NetSim_LinControllerStatusUpdate (arg, C-API) to " + "SilKit::Experimental::NetworkSimulation::LinControllerStatusUpdate (controlMsg Cpp API)"; + SilKit_Experimental_NetSim_LinControllerStatusUpdate cControllerStatusUpdate = + (SilKit_Experimental_NetSim_LinControllerStatusUpdate)controlMsg; + SilKit::Experimental::NetworkSimulation::Lin::LinControllerStatusUpdate cppControllerStatusUpdate = + (SilKit::Experimental::NetworkSimulation::Lin::LinControllerStatusUpdate)arg; + + if (static_cast(cppControllerStatusUpdate.timestamp.count()) != cControllerStatusUpdate.timestamp) + { + return false; + } + + if ((SilKit_LinControllerStatus)cppControllerStatusUpdate.status != cControllerStatusUpdate.status) + { + return false; + } + + return true; +} + +// ----------------------- + +class Test_HourglassNetSim : public SilKitHourglassTests::MockCapiTest +{ +public: + SilKit_Experimental_NetworkSimulator* mockNetSim{ + reinterpret_cast(uintptr_t(0x12345678))}; + SilKit_Experimental_CanEventProducer* mockCanEventProducer{ + reinterpret_cast(uintptr_t(0x12345678))}; + + Test_HourglassNetSim() + { + using testing::_; + ON_CALL(capi, SilKit_Experimental_NetworkSimulator_Create(_, _)) + .WillByDefault(DoAll(SetArgPointee<0>(mockNetSim), Return(SilKit_ReturnCode_SUCCESS))); + } +}; + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_NetworkSimulator_Create) +{ + SilKit_Participant* participant{(SilKit_Participant*)123456}; + EXPECT_CALL(capi, SilKit_Experimental_NetworkSimulator_Create(testing::_, participant)).Times(1); + SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental::NetworkSimulation::NetworkSimulator netSim( + participant); +} + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_NetworkSimulator_Start) +{ + SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental::NetworkSimulation::NetworkSimulator netSim( + nullptr); + EXPECT_CALL(capi, SilKit_Experimental_NetworkSimulator_Start(mockNetSim)).Times(1); + netSim.Start(); +} + +class MockSimulatedCanController : public SilKit::Experimental::NetworkSimulation::Can::ISimulatedCanController +{ +public: + MOCK_METHOD(void, OnSetBaudrate, (const SilKit::Experimental::NetworkSimulation::Can::CanConfigureBaudrate& msg), + (override)); + MOCK_METHOD(void, OnFrameRequest, (const SilKit::Experimental::NetworkSimulation::Can::CanFrameRequest& msg), + (override)); + MOCK_METHOD(void, OnSetControllerMode, (const SilKit::Experimental::NetworkSimulation::Can::CanControllerMode& msg), + (override)); +}; + +class MockSimulatedEthernetController + : public SilKit::Experimental::NetworkSimulation::Ethernet::ISimulatedEthernetController +{ +public: + MOCK_METHOD(void, OnFrameRequest, + (const SilKit::Experimental::NetworkSimulation::Ethernet::EthernetFrameRequest& msg), (override)); + MOCK_METHOD(void, OnSetControllerMode, + (const SilKit::Experimental::NetworkSimulation::Ethernet::EthernetControllerMode& msg), (override)); +}; + +class MockSimulatedLinController : public SilKit::Experimental::NetworkSimulation::Lin::ISimulatedLinController +{ +public: + MOCK_METHOD(void, OnFrameRequest, (const SilKit::Experimental::NetworkSimulation::Lin::LinFrameRequest& msg), + (override)); + MOCK_METHOD(void, OnFrameHeaderRequest, + (const SilKit::Experimental::NetworkSimulation::Lin::LinFrameHeaderRequest& msg), (override)); + MOCK_METHOD(void, OnWakeupPulse, (const SilKit::Experimental::NetworkSimulation::Lin::LinWakeupPulse& msg), + (override)); + MOCK_METHOD(void, OnControllerConfig, + (const SilKit::Experimental::NetworkSimulation::Lin::LinControllerConfig& msg), (override)); + MOCK_METHOD(void, OnFrameResponseUpdate, + (const SilKit::Experimental::NetworkSimulation::Lin::LinFrameResponseUpdate& msg), (override)); + MOCK_METHOD(void, OnControllerStatusUpdate, + (const SilKit::Experimental::NetworkSimulation::Lin::LinControllerStatusUpdate& msg), (override)); +}; + +class MockSimulatedFlexRayController + : public SilKit::Experimental::NetworkSimulation::Flexray::ISimulatedFlexRayController +{ +public: + MOCK_METHOD(void, OnHostCommand, (const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayHostCommand& msg), + (override)); + MOCK_METHOD(void, OnControllerConfig, + (const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig& msg), (override)); + MOCK_METHOD(void, OnTxBufferConfigUpdate, + (const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferConfigUpdate& msg), (override)); + MOCK_METHOD(void, OnTxBufferUpdate, + (const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate& msg), (override)); +}; + + +template +class TestSimulatedNetwork : public SilKit::Experimental::NetworkSimulation::ISimulatedNetwork +{ +public: + ControllerType testSimulatedController; + + auto ProvideSimulatedController( + SilKit::Experimental::NetworkSimulation::ControllerDescriptor /*controllerDescriptor*/) + -> SilKit::Experimental::NetworkSimulation::ISimulatedController* override + { + return &testSimulatedController; + } + + void SimulatedControllerRemoved( + SilKit::Experimental::NetworkSimulation::ControllerDescriptor /*controllerDescriptor*/) override + { + } + + void SetEventProducer( + std::unique_ptr /*eventProducer*/) override + { + } +}; + +// -------------------------- +// Test reception callbacks +// -------------------------- + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_SimulatedCanControllerFunctions) +{ + // This implements the cpp interfaces and provides a simulated can controller + TestSimulatedNetwork testSimulatedNetwork; + + // The C-API call populates the functions + void* simulatedController{nullptr}; + const void* simulatedControllerFunctions{nullptr}; + SilKit_Experimental_ControllerDescriptor controllerDescriptor{34}; + auto simulatedNetworkFunctions = SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental:: + NetworkSimulation::MakeSimulatedNetworkFunctions(SimulatedNetworkType::CAN); + simulatedNetworkFunctions.ProvideSimulatedController(&simulatedController, &simulatedControllerFunctions, + controllerDescriptor, (void*)(&testSimulatedNetwork)); + + // We should get the simulated controller we provided + EXPECT_EQ(simulatedController, &testSimulatedNetwork.testSimulatedController); + auto functions = (SilKit_Experimental_SimulatedCanControllerFunctions*)simulatedControllerFunctions; + + // ---------------------------- + // OnFrameRequest + // -------------------------- + + SilKit_CanFrame cFrame; + SilKit_Struct_Init(SilKit_CanFrame, cFrame); + cFrame.af = 5; + auto payload = std::vector{1, 2, 3, 4}; + cFrame.data = SilKit::Util::ToSilKitByteVector(payload); + cFrame.dlc = static_cast(payload.size()); + cFrame.flags |= SilKit_CanFrameFlag_fdf | SilKit_CanFrameFlag_brs; + cFrame.id = 3; + cFrame.sdt = 4; + cFrame.vcid = 6; + + SilKit_Experimental_NetSim_CanFrameRequest cCanFrameRequest; + SilKit_Struct_Init(SilKit_Experimental_NetSim_CanFrameRequest, cCanFrameRequest); + cCanFrameRequest.userContext = reinterpret_cast(0x13356489); + cCanFrameRequest.frame = &cFrame; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnFrameRequest(NetSimCanFrameRequestMatcher(cCanFrameRequest))) + .Times(1); + functions->OnFrameRequest(simulatedController, &cCanFrameRequest); + + // ---------------------------- + // OnSetBaudrate + // -------------------------- + + SilKit_Experimental_NetSim_CanConfigureBaudrate cCanConfigureBaudrate; + SilKit_Struct_Init(SilKit_Experimental_NetSim_CanConfigureBaudrate, cCanConfigureBaudrate); + cCanConfigureBaudrate.fdRate = 42; + cCanConfigureBaudrate.rate = 43; + cCanConfigureBaudrate.xlRate = 44; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnSetBaudrate(NetSimCanConfigureBaudrateMatcher(cCanConfigureBaudrate))) + .Times(1); + functions->OnSetBaudrate(simulatedController, &cCanConfigureBaudrate); + + // ---------------------------- + // OnSetControllerMode + // -------------------------- + + SilKit_Experimental_NetSim_CanControllerMode cCanControllerMode; + SilKit_Struct_Init(SilKit_Experimental_NetSim_CanControllerMode, cCanControllerMode); + cCanControllerMode.canControllerModeFlags = SilKit_Experimental_NetSim_CanControllerModeFlags_CancelTransmitRequests + | SilKit_Experimental_NetSim_CanControllerModeFlags_ResetErrorHandling; + cCanControllerMode.state = SilKit_CanControllerState_Started; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnSetControllerMode(NetSimCanControllerModeMatcher(cCanControllerMode))) + .Times(1); + functions->OnSetControllerMode(simulatedController, &cCanControllerMode); +} + + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_SimulatedEthernetControllerFunctions) +{ + // This implements the cpp interfaces and provides a simulated can controller + TestSimulatedNetwork testSimulatedNetwork; + + // The C-API call populates the functions + void* simulatedController{nullptr}; + const void* simulatedControllerFunctions{nullptr}; + SilKit_Experimental_ControllerDescriptor controllerDescriptor{34}; + auto simulatedNetworkFunctions = SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental:: + NetworkSimulation::MakeSimulatedNetworkFunctions(SimulatedNetworkType::Ethernet); + simulatedNetworkFunctions.ProvideSimulatedController(&simulatedController, &simulatedControllerFunctions, + controllerDescriptor, (void*)(&testSimulatedNetwork)); + + // We should get the simulated controller we provided + EXPECT_EQ(simulatedController, &testSimulatedNetwork.testSimulatedController); + auto functions = (SilKit_Experimental_SimulatedEthernetControllerFunctions*)simulatedControllerFunctions; + + // ---------------------------- + // OnFrameRequest + // -------------------------- + + SilKit_EthernetFrame cFrame; + SilKit_Struct_Init(SilKit_EthernetFrame, cFrame); + std::array payload{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + cFrame.raw = {payload.data(), payload.size()}; + + SilKit_Experimental_NetSim_EthernetFrameRequest cEthernetFrameRequest; + SilKit_Struct_Init(SilKit_Experimental_NetSim_EthernetFrameRequest, cEthernetFrameRequest); + cEthernetFrameRequest.userContext = reinterpret_cast(0x13356489); + cEthernetFrameRequest.ethernetFrame = &cFrame; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnFrameRequest(NetSimEthernetFrameRequestMatcher(cEthernetFrameRequest))) + .Times(1); + functions->OnFrameRequest(simulatedController, &cEthernetFrameRequest); + + // ---------------------------- + // OnSetControllerMode + + SilKit_Experimental_NetSim_EthernetControllerMode cEthernetControllerMode; + SilKit_Struct_Init(SilKit_Experimental_NetSim_EthernetControllerMode, cEthernetControllerMode); + cEthernetControllerMode.mode = SilKit_EthernetControllerMode_Active; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnSetControllerMode(NetSimEthernetControllerModeMatcher(cEthernetControllerMode))) + .Times(1); + functions->OnSetControllerMode(simulatedController, &cEthernetControllerMode); +} + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_SimulatedFlexRayControllerFunctions) +{ + // This implements the cpp interfaces and provides a simulated can controller + TestSimulatedNetwork testSimulatedNetwork; + + // The C-API call populates the functions + void* simulatedController{nullptr}; + const void* simulatedControllerFunctions{nullptr}; + SilKit_Experimental_ControllerDescriptor controllerDescriptor{34}; + auto simulatedNetworkFunctions = SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental:: + NetworkSimulation::MakeSimulatedNetworkFunctions(SimulatedNetworkType::FlexRay); + simulatedNetworkFunctions.ProvideSimulatedController(&simulatedController, &simulatedControllerFunctions, + controllerDescriptor, (void*)(&testSimulatedNetwork)); + + // We should get the simulated controller we provided + EXPECT_EQ(simulatedController, &testSimulatedNetwork.testSimulatedController); + auto functions = (SilKit_Experimental_SimulatedFlexRayControllerFunctions*)simulatedControllerFunctions; + + // ---------------------------- + // OnHostCommand + // ---------------------------- + + SilKit_Experimental_NetSim_FlexrayHostCommand cHostCommand; + SilKit_Struct_Init(SilKit_Experimental_NetSim_FlexrayHostCommand, cHostCommand); + cHostCommand.chiCommand = SilKit_FlexrayChiCommand_ALL_SLOTS; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnHostCommand(NetSimFlexrayHostCommandMatcher(cHostCommand))) + .Times(1); + functions->OnHostCommand(simulatedController, &cHostCommand); + + // ---------------------------- + // OnControllerConfig + // ---------------------------- + + SilKit_FlexrayTxBufferConfig cTxBufferConfig1; + SilKit_Struct_Init(SilKit_FlexrayTxBufferConfig, cTxBufferConfig1); + cTxBufferConfig1.channels = SilKit_FlexrayChannel_AB; + cTxBufferConfig1.hasPayloadPreambleIndicator = SilKit_False; + cTxBufferConfig1.headerCrc = 23; + cTxBufferConfig1.offset = 21; + cTxBufferConfig1.repetition = 2; + cTxBufferConfig1.slotId = 25; + cTxBufferConfig1.transmissionMode = SilKit_FlexrayTransmissionMode_Continuous; + + SilKit_FlexrayTxBufferConfig cTxBufferConfig2; + SilKit_Struct_Init(SilKit_FlexrayTxBufferConfig, cTxBufferConfig2); + cTxBufferConfig2.channels = SilKit_FlexrayChannel_A; + cTxBufferConfig2.hasPayloadPreambleIndicator = SilKit_True; + cTxBufferConfig2.headerCrc = 13; + cTxBufferConfig2.offset = 51; + cTxBufferConfig2.repetition = 3; + cTxBufferConfig2.slotId = 15; + cTxBufferConfig2.transmissionMode = SilKit_FlexrayTransmissionMode_SingleShot; + + SilKit_FlexrayClusterParameters cClusterParameters; + SilKit_Struct_Init(SilKit_FlexrayClusterParameters, cClusterParameters); + cClusterParameters.gColdstartAttempts = 8; + cClusterParameters.gCycleCountMax = 63; + cClusterParameters.gdActionPointOffset = 2; + cClusterParameters.gdDynamicSlotIdlePhase = 1; + cClusterParameters.gdMiniSlot = 5; + cClusterParameters.gdMiniSlotActionPointOffset = 2; + cClusterParameters.gdStaticSlot = 31; + cClusterParameters.gdSymbolWindow = 0; + cClusterParameters.gdSymbolWindowActionPointOffset = 1; + cClusterParameters.gdTSSTransmitter = 9; + cClusterParameters.gdWakeupTxActive = 60; + cClusterParameters.gdWakeupTxIdle = 180; + cClusterParameters.gListenNoise = 2; + cClusterParameters.gMacroPerCycle = 3636; + cClusterParameters.gMaxWithoutClockCorrectionFatal = 2; + cClusterParameters.gMaxWithoutClockCorrectionPassive = 2; + cClusterParameters.gNumberOfMiniSlots = 291; + cClusterParameters.gNumberOfStaticSlots = 70; + cClusterParameters.gPayloadLengthStatic = 13; + cClusterParameters.gSyncFrameIDCountMax = 15; + + SilKit_FlexrayNodeParameters cNodeParameters; + SilKit_Struct_Init(SilKit_FlexrayNodeParameters, cNodeParameters); + cNodeParameters.pAllowHaltDueToClock = 1; + cNodeParameters.pAllowPassiveToActive = 2; + cNodeParameters.pChannels = SilKit_FlexrayChannel_AB; + cNodeParameters.pClusterDriftDamping = 10; + cNodeParameters.pdAcceptedStartupRange = 2743; + cNodeParameters.pdListenTimeout = 2567692; + cNodeParameters.pdMicrotick = SilKit_FlexrayClockPeriod_T25NS; + cNodeParameters.pKeySlotId = 1023; + cNodeParameters.pKeySlotOnlyEnabled = 3; + cNodeParameters.pKeySlotUsedForStartup = 4; + cNodeParameters.pKeySlotUsedForSync = 5; + cNodeParameters.pLatestTx = 7988; + cNodeParameters.pMacroInitialOffsetA = 68; + cNodeParameters.pMacroInitialOffsetB = 67; + cNodeParameters.pMicroInitialOffsetA = 239; + cNodeParameters.pMicroInitialOffsetB = 238; + cNodeParameters.pMicroPerCycle = 1280000; + cNodeParameters.pOffsetCorrectionOut = 16082; + cNodeParameters.pOffsetCorrectionStart = 15999; + cNodeParameters.pRateCorrectionOut = 3846; + cNodeParameters.pSamplesPerMicrotick = 6; + cNodeParameters.pWakeupChannel = SilKit_FlexrayChannel_B; + cNodeParameters.pWakeupPattern = 7; + + SilKit_Experimental_NetSim_FlexrayControllerConfig cFlexrayControllerConfig; + SilKit_Struct_Init(SilKit_Experimental_NetSim_FlexrayControllerConfig, cFlexrayControllerConfig); + std::vector bufferConfigs{cTxBufferConfig1, cTxBufferConfig2}; + cFlexrayControllerConfig.bufferConfigs = bufferConfigs.data(); + cFlexrayControllerConfig.numBufferConfigs = 2; + cFlexrayControllerConfig.clusterParams = &cClusterParameters; + cFlexrayControllerConfig.nodeParams = &cNodeParameters; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnControllerConfig(NetSimFlexrayControllerConfigMatcher(cFlexrayControllerConfig))) + .Times(1); + functions->OnControllerConfig(simulatedController, &cFlexrayControllerConfig); + + // ---------------------------- + // OnTxBufferConfigUpdate + // ---------------------------- + + SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate cFlexrayTxBufferConfigUpdate; + SilKit_Struct_Init(SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate, cFlexrayTxBufferConfigUpdate); + cFlexrayTxBufferConfigUpdate.txBufferIdx = 3; + cFlexrayTxBufferConfigUpdate.txBufferConfig = &cTxBufferConfig1; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnTxBufferConfigUpdate(NetSimFlexrayTxBufferConfigUpdateMatcher(cFlexrayTxBufferConfigUpdate))) + .Times(1); + functions->OnTxBufferConfigUpdate(simulatedController, &cFlexrayTxBufferConfigUpdate); + + // ---------------------------- + // OnTxBufferUpdate + // ---------------------------- + + SilKit_Experimental_NetSim_FlexrayTxBufferUpdate cFlexrayTxBufferUpdate; + SilKit_Struct_Init(SilKit_Experimental_NetSim_FlexrayTxBufferUpdate, cFlexrayTxBufferUpdate); + std::vector payload{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + cFlexrayTxBufferUpdate.payload = {payload.data(), payload.size()}; + cFlexrayTxBufferUpdate.payloadDataValid = SilKit_True; + cFlexrayTxBufferUpdate.txBufferIndex = 12; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnTxBufferUpdate(NetSimFlexrayTxBufferUpdateMatcher(cFlexrayTxBufferUpdate))) + .Times(1); + functions->OnTxBufferUpdate(simulatedController, &cFlexrayTxBufferUpdate); +} + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_SimulatedLinControllerFunctions) +{ + // This implements the cpp interfaces and provides a simulated can controller + TestSimulatedNetwork testSimulatedNetwork; + + // The C-API call populates the functions + void* simulatedController{nullptr}; + const void* simulatedControllerFunctions{nullptr}; + SilKit_Experimental_ControllerDescriptor controllerDescriptor{34}; + auto simulatedNetworkFunctions = SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental:: + NetworkSimulation::MakeSimulatedNetworkFunctions(SimulatedNetworkType::LIN); + simulatedNetworkFunctions.ProvideSimulatedController(&simulatedController, &simulatedControllerFunctions, + controllerDescriptor, (void*)(&testSimulatedNetwork)); + + // We should get the simulated controller we provided + EXPECT_EQ(simulatedController, &testSimulatedNetwork.testSimulatedController); + auto functions = (SilKit_Experimental_SimulatedLinControllerFunctions*)simulatedControllerFunctions; + + // ---------------------------- + // OnFrameRequest + // ---------------------------- + + SilKit_LinFrame cFrame1; + SilKit_Struct_Init(SilKit_LinFrame, cFrame1); + cFrame1.checksumModel = SilKit_LinChecksumModel_Classic; + uint8_t frame1Payload[8] = {1, 2, 3, 4, 5, 6, 7, 8}; + memcpy(cFrame1.data, frame1Payload, sizeof(cFrame1.data)); + cFrame1.dataLength = 6; + cFrame1.id = 16; + + SilKit_LinFrame cFrame2; + SilKit_Struct_Init(SilKit_LinFrame, cFrame2); + cFrame1.checksumModel = SilKit_LinChecksumModel_Enhanced; + uint8_t frame2Payload[8] = {2, 3, 4, 5, 6, 7, 8, 9}; + memcpy(cFrame2.data, frame2Payload, sizeof(cFrame2.data)); + cFrame2.dataLength = 5; + cFrame2.id = 17; + + SilKit_Experimental_NetSim_LinFrameRequest cLinFrameRequest; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinFrameRequest, cLinFrameRequest); + cLinFrameRequest.responseType = SilKit_LinFrameResponseType_SlaveResponse; + cLinFrameRequest.frame = &cFrame1; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnFrameRequest(NetSimLinFrameRequestMatcher(cLinFrameRequest))) + .Times(1); + functions->OnFrameRequest(simulatedController, &cLinFrameRequest); + + // ---------------------------- + // OnFrameHeaderRequest + // ---------------------------- + + SilKit_Experimental_NetSim_LinFrameHeaderRequest cLinFrameHeaderRequest; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinFrameHeaderRequest, cLinFrameHeaderRequest); + cLinFrameHeaderRequest.id = 23; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnFrameHeaderRequest(NetSimLinFrameHeaderRequestMatcher(cLinFrameHeaderRequest))) + .Times(1); + functions->OnFrameHeaderRequest(simulatedController, &cLinFrameHeaderRequest); + + // ---------------------------- + // OnWakeupPulse + // ---------------------------- + + SilKit_Experimental_NetSim_LinWakeupPulse cLinWakeupPulse; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinWakeupPulse, cLinWakeupPulse); + cLinWakeupPulse.timestamp = 12353543; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnWakeupPulse(NetSimLinWakeupPulseMatcher(cLinWakeupPulse))) + .Times(1); + functions->OnWakeupPulse(simulatedController, &cLinWakeupPulse); + + // ---------------------------- + // OnControllerConfig + // ---------------------------- + + SilKit_Experimental_NetSim_LinControllerConfig cLinControllerConfig; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinControllerConfig, cLinControllerConfig); + cLinControllerConfig.baudRate = 23; + cLinControllerConfig.controllerMode = SilKit_LinControllerMode_Master; + + SilKit_LinFrameResponse frameResponse1; + SilKit_Struct_Init(SilKit_LinFrameResponse, frameResponse1); + frameResponse1.frame = &cFrame1; + frameResponse1.responseMode = SilKit_LinFrameResponseMode_TxUnconditional; + SilKit_LinFrameResponse frameResponse2; + SilKit_Struct_Init(SilKit_LinFrameResponse, frameResponse2); + frameResponse2.frame = &cFrame2; + frameResponse2.responseMode = SilKit_LinFrameResponseMode_Rx; + std::vector frameResponses{frameResponse1, frameResponse2}; + cLinControllerConfig.frameResponses = frameResponses.data(); + + cLinControllerConfig.numFrameResponses = frameResponses.size(); + cLinControllerConfig.simulationMode = SilKit_Experimental_NetSim_LinSimulationMode_Dynamic; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnControllerConfig(NetSimLinControllerConfigMatcher(cLinControllerConfig))) + .Times(1); + functions->OnControllerConfig(simulatedController, &cLinControllerConfig); + + // ---------------------------- + // OnFrameResponseUpdate + // ---------------------------- + + SilKit_Experimental_NetSim_LinFrameResponseUpdate cLinFrameResponseUpdate; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinFrameResponseUpdate, cLinFrameResponseUpdate); + + cLinFrameResponseUpdate.frameResponses = frameResponses.data(); + cLinFrameResponseUpdate.numFrameResponses = frameResponses.size(); + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnFrameResponseUpdate(NetSimLinFrameResponseUpdateMatcher(cLinFrameResponseUpdate))) + .Times(1); + functions->OnFrameResponseUpdate(simulatedController, &cLinFrameResponseUpdate); + + + // ---------------------------- + // OnControllerStatusUpdate + // ---------------------------- + + SilKit_Experimental_NetSim_LinControllerStatusUpdate cLinControllerStatusUpdate; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinControllerStatusUpdate, cLinControllerStatusUpdate); + cLinControllerStatusUpdate.status = SilKit_LinControllerStatus_Operational; + cLinControllerStatusUpdate.timestamp = 4328974; + + EXPECT_CALL(testSimulatedNetwork.testSimulatedController, + OnControllerStatusUpdate(NetSimLinControllerStatusUpdateMatcher(cLinControllerStatusUpdate))) + .Times(1); + functions->OnControllerStatusUpdate(simulatedController, &cLinControllerStatusUpdate); +} + +// ---------------------- +// Test EventProducer +// ---------------------- + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_CanEventProducer_Produce) +{ + using namespace SilKit::Services::Can; + SilKit_Experimental_CanEventProducer* cCanEventProducer{(SilKit_Experimental_CanEventProducer*)123456}; + // C++ event + CanFrame canFrame{}; + canFrame.af = 21; + canFrame.canId = 3; + auto payload = std::vector{1, 2, 3, 4}; + canFrame.dataField = payload; + canFrame.dlc = static_cast(payload.size()); + canFrame.flags |= + static_cast(CanFrameFlag::Fdf) | static_cast(CanFrameFlag::Brs); + canFrame.sdt = 4; + canFrame.vcid = 6; + + CanFrameEvent canFrameEvent; + canFrameEvent.direction = SilKit::Services::TransmitDirection::TX; + canFrameEvent.frame = canFrame; + canFrameEvent.userContext = reinterpret_cast(0x23456789); + canFrameEvent.timestamp = std::chrono::nanoseconds{123}; + + std::array receiverArray{1, 2, 3}; + auto receivers = SilKit::Util::MakeSpan(receiverArray); + + EXPECT_CALL(capi, SilKit_Experimental_CanEventProducer_Produce( + cCanEventProducer, CanFrameEventMatcher(canFrameEvent), ReceiverMatcher(receivers))) + .Times(1); + + SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental::NetworkSimulation::CanEventProducer + canEventProducer(cCanEventProducer); + canEventProducer.Produce(canFrameEvent, receivers); +} + + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_EthernetEventProducer_Produce) +{ + using namespace SilKit::Services::Ethernet; + SilKit_Experimental_EthernetEventProducer* cEthernetEventProducer{ + (SilKit_Experimental_EthernetEventProducer*)123456}; + // C++ event + EthernetFrame ethernetFrame{}; + std::array payload{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + ethernetFrame.raw = {payload.data(), payload.size()}; + + EthernetFrameEvent ethernetFrameEvent; + ethernetFrameEvent.direction = SilKit::Services::TransmitDirection::TX; + ethernetFrameEvent.frame = ethernetFrame; + ethernetFrameEvent.userContext = reinterpret_cast(0x23456789); + ethernetFrameEvent.timestamp = std::chrono::nanoseconds{123}; + + std::array receiverArray{1, 2, 3}; + auto receivers = SilKit::Util::MakeSpan(receiverArray); + + EXPECT_CALL(capi, + SilKit_Experimental_EthernetEventProducer_Produce( + cEthernetEventProducer, EthernetFrameEventMatcher(ethernetFrameEvent), ReceiverMatcher(receivers))) + .Times(1); + + SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental::NetworkSimulation::EthernetEventProducer + ethernetEventProducer(cEthernetEventProducer); + ethernetEventProducer.Produce(ethernetFrameEvent, receivers); +} + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_FlexRayEventProducer_Produce) +{ + using namespace SilKit::Services::Flexray; + SilKit_Experimental_FlexRayEventProducer* cFlexRayEventProducer{(SilKit_Experimental_FlexRayEventProducer*)123456}; + + // C++ event + const uint8_t payloadLength = 3; + FlexrayHeader header; + header.cycleCount = 5; + header.flags = 1; + header.frameId = 2; + header.headerCrc = 4; + header.payloadLength = payloadLength; + + FlexrayFrame flexrayFrame{}; + std::array payload{0, 1, 2}; + flexrayFrame.header = header; + flexrayFrame.payload = {payload.data(), payload.size()}; + + FlexrayFrameEvent flexrayFrameEvent; + flexrayFrameEvent.channel = FlexrayChannel::AB; + flexrayFrameEvent.frame = flexrayFrame; + flexrayFrameEvent.timestamp = std::chrono::nanoseconds{123}; + + std::array receiverArray{1, 2, 3}; + auto receivers = SilKit::Util::MakeSpan(receiverArray); + + EXPECT_CALL(capi, + SilKit_Experimental_FlexRayEventProducer_Produce( + cFlexRayEventProducer, FlexrayFrameEventMatcher(flexrayFrameEvent), ReceiverMatcher(receivers))) + .Times(1); + + SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental::NetworkSimulation::FlexRayEventProducer + flexrayEventProducer(cFlexRayEventProducer); + flexrayEventProducer.Produce(flexrayFrameEvent, receivers); +} + +TEST_F(Test_HourglassNetSim, SilKit_Experimental_LinEventProducer_Produce) +{ + using namespace SilKit::Services::Lin; + SilKit_Experimental_LinEventProducer* cLinEventProducer{(SilKit_Experimental_LinEventProducer*)123456}; + // C++ event + LinFrame linFrame{}; + linFrame.checksumModel = LinChecksumModel::Enhanced; + linFrame.dataLength = 4; + linFrame.id = 42; + auto payload = std::array{1, 2, 3, 4, 5, 6, 7, 8}; + linFrame.data = payload; + + LinFrameStatusEvent linFrameStatusEvent; + linFrameStatusEvent.frame = linFrame; + linFrameStatusEvent.status = LinFrameStatus::LIN_TX_OK; + linFrameStatusEvent.timestamp = std::chrono::nanoseconds{123}; + + std::array receiverArray{1, 2, 3}; + auto receivers = SilKit::Util::MakeSpan(receiverArray); + + EXPECT_CALL(capi, + SilKit_Experimental_LinEventProducer_Produce( + cLinEventProducer, LinFrameStatusEventMatcher(linFrameStatusEvent), ReceiverMatcher(receivers))) + .Times(1); + + SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Experimental::NetworkSimulation::LinEventProducer + linEventProducer(cLinEventProducer); + linEventProducer.Produce(linFrameStatusEvent, receivers); +} + +} //namespace diff --git a/SilKit/IntegrationTests/Hourglass/Test_HourglassOrchestration.cpp b/SilKit/IntegrationTests/Hourglass/Test_HourglassOrchestration.cpp index 2c3a52fb9..9314b0ae8 100644 --- a/SilKit/IntegrationTests/Hourglass/Test_HourglassOrchestration.cpp +++ b/SilKit/IntegrationTests/Hourglass/Test_HourglassOrchestration.cpp @@ -94,9 +94,8 @@ MATCHER_P(WorkflowConfigurationMatcher, workflowConfigurationParam, "") std::transform(cWorkflowConfiguration->requiredParticipantNames->strings, cWorkflowConfiguration->requiredParticipantNames->strings + cWorkflowConfiguration->requiredParticipantNames->numStrings, - std::inserter(cRequiredParticipantNames, cRequiredParticipantNames.begin()), [](char* name) { - return std::string{name}; - }); + std::inserter(cRequiredParticipantNames, cRequiredParticipantNames.begin()), + [](char* name) { return std::string{name}; }); if (cRequiredParticipantNames != cppRequiredParticipantNames) { @@ -390,11 +389,9 @@ TEST_F(Test_HourglassOrchestration, SilKit_TimeSyncService_SetSimulationStepHand EXPECT_CALL(capi, SilKit_TimeSyncService_SetSimulationStepHandler(mockTimeSyncService, testing::_, testing::_, initialStepSize.count())); - timeSyncService.SetSimulationStepHandler( - [](std::chrono::nanoseconds, std::chrono::nanoseconds) { - // do nothing - }, - initialStepSize); + timeSyncService.SetSimulationStepHandler([](std::chrono::nanoseconds, std::chrono::nanoseconds) { + // do nothing + }, initialStepSize); } TEST_F(Test_HourglassOrchestration, SilKit_TimeSyncService_SetSimulationStepHandlerAsync) @@ -407,11 +404,9 @@ TEST_F(Test_HourglassOrchestration, SilKit_TimeSyncService_SetSimulationStepHand EXPECT_CALL(capi, SilKit_TimeSyncService_SetSimulationStepHandlerAsync(mockTimeSyncService, testing::_, testing::_, initialStepSize.count())); - timeSyncService.SetSimulationStepHandlerAsync( - [](std::chrono::nanoseconds, std::chrono::nanoseconds) { - // do nothing - }, - initialStepSize); + timeSyncService.SetSimulationStepHandlerAsync([](std::chrono::nanoseconds, std::chrono::nanoseconds) { + // do nothing + }, initialStepSize); } TEST_F(Test_HourglassOrchestration, SilKit_TimeSyncService_CompleteSimulationStep) @@ -516,8 +511,8 @@ TEST_F(Test_HourglassOrchestration, SilKit_SystemMonitor_AddParticipantStatusHan const auto cppHandlerId = systemMonitor.AddParticipantStatusHandler([](const SilKit::Services::Orchestration::ParticipantStatus&) { - // do nothing - }); + // do nothing + }); systemMonitor.RemoveParticipantStatusHandler(cppHandlerId); } @@ -530,8 +525,8 @@ TEST_F(Test_HourglassOrchestration, SilKit_SystemMonitor_SetParticipantConnected systemMonitor.SetParticipantConnectedHandler( [](const SilKit::Services::Orchestration::ParticipantConnectionInformation&) { - // do nothing - }); + // do nothing + }); } TEST_F(Test_HourglassOrchestration, SilKit_SystemMonitor_SetParticipantDisconnectedHandler) @@ -544,8 +539,8 @@ TEST_F(Test_HourglassOrchestration, SilKit_SystemMonitor_SetParticipantDisconnec systemMonitor.SetParticipantDisconnectedHandler( [](const SilKit::Services::Orchestration::ParticipantConnectionInformation&) { - // do nothing - }); + // do nothing + }); } TEST_F(Test_HourglassOrchestration, SilKit_SystemMonitor_IsParticipantConnected) diff --git a/SilKit/IntegrationTests/Hourglass/Test_HourglassParticipantLogger.cpp b/SilKit/IntegrationTests/Hourglass/Test_HourglassParticipantLogger.cpp index 137f8d210..325b87f59 100644 --- a/SilKit/IntegrationTests/Hourglass/Test_HourglassParticipantLogger.cpp +++ b/SilKit/IntegrationTests/Hourglass/Test_HourglassParticipantLogger.cpp @@ -54,6 +54,8 @@ class Test_HourglassParticipantLogger : public SilKitHourglassTests::MockCapiTes .WillByDefault(DoAll(SetArgPointee<0>(mockLogger), Return(SilKit_ReturnCode_SUCCESS))); ON_CALL(capi, SilKit_ParticipantConfiguration_FromString(_, _)) .WillByDefault(DoAll(SetArgPointee<0>(mockConfiguration), Return(SilKit_ReturnCode_SUCCESS))); + ON_CALL(capi, SilKit_ParticipantConfiguration_FromFile(_, _)) + .WillByDefault(DoAll(SetArgPointee<0>(mockConfiguration), Return(SilKit_ReturnCode_SUCCESS))); } }; @@ -66,6 +68,15 @@ TEST_F(Test_HourglassParticipantLogger, SilKit_ParticipantConfiguration_FromStri SilKit::Config::ParticipantConfigurationFromString(configString); } +TEST_F(Test_HourglassParticipantLogger, SilKit_ParticipantConfiguration_FromFile) +{ + std::string configFilename = ""; + + EXPECT_CALL(capi, SilKit_ParticipantConfiguration_FromFile(testing::_, testing::StrEq(configFilename.c_str()))) + .Times(1); + SilKit::Config::ParticipantConfigurationFromFile(configFilename); +} + TEST_F(Test_HourglassParticipantLogger, SilKit_ParticipantConfiguration_Destroy) { std::string configString = ""; diff --git a/SilKit/IntegrationTests/Hourglass/Test_HourglassPubSub.cpp b/SilKit/IntegrationTests/Hourglass/Test_HourglassPubSub.cpp index 4964e8f83..d1aa42b05 100644 --- a/SilKit/IntegrationTests/Hourglass/Test_HourglassPubSub.cpp +++ b/SilKit/IntegrationTests/Hourglass/Test_HourglassPubSub.cpp @@ -110,8 +110,8 @@ MATCHER_P(PubSubSpecMatcher, pubSubSpecParam, "") MatchingLabelSet cLabels{}; std::transform(cDataSpec->labelList.labels, cDataSpec->labelList.labels + cDataSpec->labelList.numLabels, std::inserter(cLabels, cLabels.begin()), [](const SilKit_Label& cLabel) { - return MatchingLabel{cLabel.key, cLabel.value, static_cast(cLabel.kind)}; - }); + return MatchingLabel{cLabel.key, cLabel.value, static_cast(cLabel.kind)}; + }); if (!std::equal(cppLabels.begin(), cppLabels.end(), cLabels.begin(), cLabels.end(), MatchingLabelEquals{})) { @@ -201,8 +201,8 @@ TEST_F(Test_HourglassPubSub, SilKit_DataSubscriber_Create) SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Services::PubSub::DataSubscriber subscriber{ participant, subscriberName, pubSubSpec, [](IDataSubscriber*, const DataMessageEvent&) { - // do nothing - }}; + // do nothing + }}; } TEST_F(Test_HourglassPubSub, SilKit_DataSubscriber_SetDataMessageHandler) @@ -212,8 +212,8 @@ TEST_F(Test_HourglassPubSub, SilKit_DataSubscriber_SetDataMessageHandler) SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Services::PubSub::DataSubscriber subscriber{ participant, "DataSubscriber1", PubSubSpec{"Topic1", "MediaType1"}, [](IDataSubscriber*, const DataMessageEvent&) { - // do nothing - }}; + // do nothing + }}; EXPECT_CALL(capi, SilKit_DataSubscriber_SetDataMessageHandler(mockDataSubscriber, testing::_, testing::_)); diff --git a/SilKit/IntegrationTests/Hourglass/Test_HourglassRpc.cpp b/SilKit/IntegrationTests/Hourglass/Test_HourglassRpc.cpp index 8cfd13cb1..b2c76ac4d 100644 --- a/SilKit/IntegrationTests/Hourglass/Test_HourglassRpc.cpp +++ b/SilKit/IntegrationTests/Hourglass/Test_HourglassRpc.cpp @@ -110,8 +110,8 @@ MATCHER_P(RpcSpecMatcher, rpcSpecParam, "") MatchingLabelSet cLabels{}; std::transform(cRpcSpec->labelList.labels, cRpcSpec->labelList.labels + cRpcSpec->labelList.numLabels, std::inserter(cLabels, cLabels.begin()), [](const SilKit_Label& cLabel) { - return MatchingLabel{cLabel.key, cLabel.value, static_cast(cLabel.kind)}; - }); + return MatchingLabel{cLabel.key, cLabel.value, static_cast(cLabel.kind)}; + }); if (!std::equal(cppLabels.begin(), cppLabels.end(), cLabels.begin(), cLabels.end(), MatchingLabelEquals{})) { @@ -160,8 +160,8 @@ TEST_F(Test_HourglassRpc, SilKit_RpcServer_Create) SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Services::Rpc::RpcServer rpcServer{ participant, serverName, rpcSpec, [](IRpcServer*, const RpcCallEvent&) { - // do nothing - }}; + // do nothing + }}; } TEST_F(Test_HourglassRpc, SilKit_RpcServer_SubmitResult) @@ -169,8 +169,8 @@ TEST_F(Test_HourglassRpc, SilKit_RpcServer_SubmitResult) auto* const participant = reinterpret_cast(uintptr_t(123456)); SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Services::Rpc::RpcServer rpcServer{ participant, "RpcServer1", RpcSpec{"FunctionName1", "MediaType1"}, [](IRpcServer*, const RpcCallEvent&) { - // do nothing - }}; + // do nothing + }}; auto* const rpcCallHandle = reinterpret_cast(uintptr_t(654321)); @@ -187,8 +187,8 @@ TEST_F(Test_HourglassRpc, SilKit_RpcServer_SetCallHandler) auto* const participant = reinterpret_cast(uintptr_t(123456)); SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Services::Rpc::RpcServer rpcServer{ participant, "RpcServer1", RpcSpec{"FunctionName1", "MediaType1"}, [](IRpcServer*, const RpcCallEvent&) { - // do nothing - }}; + // do nothing + }}; EXPECT_CALL(capi, SilKit_RpcServer_SetCallHandler(mockRpcServer, testing::_, testing::_)); @@ -219,8 +219,8 @@ TEST_F(Test_HourglassRpc, SilKit_RpcClient_Create) SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Services::Rpc::RpcClient rpcClient{ participant, clientName, rpcSpec, [](IRpcClient*, const RpcCallResultEvent&) { - // do nothing - }}; + // do nothing + }}; } TEST_F(Test_HourglassRpc, SilKit_RpcClient_Call) @@ -229,8 +229,8 @@ TEST_F(Test_HourglassRpc, SilKit_RpcClient_Call) SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Services::Rpc::RpcClient rpcClient{ participant, "RpcClient1", RpcSpec{"FunctionName1", "MediaType1"}, [](IRpcClient*, const RpcCallResultEvent&) { - // do nothing - }}; + // do nothing + }}; std::vector bytes{1, 2, 3, 4, 5, 6, 7, 8, 9}; const Span byteSpan{bytes}; @@ -246,8 +246,8 @@ TEST_F(Test_HourglassRpc, SilKit_RpcClient_SetCallResultHandler) SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Impl::Services::Rpc::RpcClient rpcClient{ participant, "RpcClient1", RpcSpec{"FunctionName1", "MediaType1"}, [](IRpcClient*, const RpcCallResultEvent&) { - // do nothing - }}; + // do nothing + }}; EXPECT_CALL(capi, SilKit_RpcClient_SetCallResultHandler(mockRpcClient, testing::_, testing::_)); diff --git a/SilKit/IntegrationTests/ITestFixture.hpp b/SilKit/IntegrationTests/ITestFixture.hpp old mode 100755 new mode 100644 index b9bf2f152..f6fe6ddac --- a/SilKit/IntegrationTests/ITestFixture.hpp +++ b/SilKit/IntegrationTests/ITestFixture.hpp @@ -39,7 +39,7 @@ class ITest_SimTestHarness : public testing::Test { protected: //CTor and operators ITest_SimTestHarness() - : _registryUri{MakeTestRegistryUri()} + : _registryUri{MakeTestRegistryUri()} { } @@ -55,7 +55,7 @@ class ITest_SimTestHarness : public testing::Test _simTestHarness = std::make_unique(participantNames, _registryUri, true); } -protected:// members +protected: // members std::string _registryUri; std::unique_ptr _simTestHarness; }; diff --git a/SilKit/IntegrationTests/ITestThreadSafeLogger.hpp b/SilKit/IntegrationTests/ITestThreadSafeLogger.hpp index baff12464..400cf548c 100644 --- a/SilKit/IntegrationTests/ITestThreadSafeLogger.hpp +++ b/SilKit/IntegrationTests/ITestThreadSafeLogger.hpp @@ -50,7 +50,7 @@ struct ThreadSafeLogger ThreadSafeLogger(ThreadSafeLogger&&) = default; ThreadSafeLogger& operator=(ThreadSafeLogger&&) = default; - template + template auto operator<<(T&& arg) -> ThreadSafeLogger& { buf << std::forward(arg); diff --git a/SilKit/IntegrationTests/ITest_Abort.cpp b/SilKit/IntegrationTests/ITest_Abort.cpp index 9c1d35cb4..957207335 100644 --- a/SilKit/IntegrationTests/ITest_Abort.cpp +++ b/SilKit/IntegrationTests/ITest_Abort.cpp @@ -75,10 +75,10 @@ TEST_F(ITest_Abort, test_Abort_Paused_Simulation_Sync) required.push_back(p.name); } RunParticipants(monitorParticipants); - for (auto& p : monitorParticipants) - { - p.AwaitRunning(); - } + for (auto& p : monitorParticipants) + { + p.AwaitRunning(); + } RunSystemController(required); RunParticipants(syncParticipants); @@ -216,10 +216,14 @@ TEST_F(ITest_Abort, test_Abort_Stopped_Simulation_Sync) EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::CommunicationInitialized)).Times(size); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::ReadyToRun)).Times(size); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Running)).Times(size); - EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Aborting)).Times(size); + // The system controller stops the simulation and aborts in the stop handler. + // However it can happen that a participant is done with the stop before the abort arrives. + // Thus we can only expect 1 to N aborts. + EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Aborting)).Times(Between(1, size)); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Stopping)).Times(Between(1, size)); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Stopped)).Times(Between(0, size)); - EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::ShuttingDown)).Times(0); + // A participant may stop and shut down before the abort arrives. In this case ShuttingDown is reached. + EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::ShuttingDown)).Times(Between(0, size)); std::list monitorParticipants; monitorParticipants.push_back({"MonitorParticipant1", TimeMode::Async, OperationMode::Autonomous}); @@ -239,9 +243,8 @@ TEST_F(ITest_Abort, test_Abort_Stopped_Simulation_Sync) required.push_back(p.name); } auto setup = [this]() { - systemControllerParticipant.lifecycleService->SetStopHandler([this]() { - this->systemControllerParticipant.systemController->AbortSimulation(); - }); + systemControllerParticipant.lifecycleService->SetStopHandler( + [this]() { this->systemControllerParticipant.systemController->AbortSimulation(); }); }; // Each participant knows that all other participants have started. @@ -287,24 +290,20 @@ TEST_F(ITest_Abort, test_Abort_Communication_Ready_Simulation_Sync) // state. int size = static_cast(syncParticipants.size() + 1); // include system controller int requiredParticipantsSize = static_cast(syncParticipants.size()); - EXPECT_CALL(callbacks, AbortHandler(ParticipantState::ServicesCreated)) - .Times(Between(0, size)); + EXPECT_CALL(callbacks, AbortHandler(ParticipantState::ServicesCreated)).Times(Between(0, size)); EXPECT_CALL(callbacks, AbortHandler(ParticipantState::CommunicationInitializing)) .Times(Between(0, requiredParticipantsSize)); - EXPECT_CALL(callbacks, AbortHandler(ParticipantState::CommunicationInitialized)) - .Times(Between(0, size)); + EXPECT_CALL(callbacks, AbortHandler(ParticipantState::CommunicationInitialized)).Times(Between(0, size)); EXPECT_CALL(callbacks, AbortHandler(ParticipantState::ReadyToRun)).Times(Between(0, size)); EXPECT_CALL(callbacks, AbortHandler(ParticipantState::Running)).Times(Between(0, size)); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Shutdown)).Times(size); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Error)).Times(0); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Invalid)).Times(0); - EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::ServicesCreated)) - .Times(Between(1, size)); + EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::ServicesCreated)).Times(Between(1, size)); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::CommunicationInitializing)) .Times(Between(1, size)); - EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::CommunicationInitialized)) - .Times(Between(1, size)); + EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::CommunicationInitialized)).Times(Between(1, size)); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::ReadyToRun)).Times(Between(0, size)); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Running)).Times(Between(0, size)); EXPECT_CALL(callbacks, ParticipantStateHandler(ParticipantState::Aborting)).Times(size); @@ -330,9 +329,8 @@ TEST_F(ITest_Abort, test_Abort_Communication_Ready_Simulation_Sync) required.push_back(p.name); } auto setup = [this]() { - systemControllerParticipant.lifecycleService->SetCommunicationReadyHandler([this]() { - this->systemControllerParticipant.systemController->AbortSimulation(); - }); + systemControllerParticipant.lifecycleService->SetCommunicationReadyHandler( + [this]() { this->systemControllerParticipant.systemController->AbortSimulation(); }); }; RunParticipants(syncParticipants); RunSystemController(required, setup); diff --git a/SilKit/IntegrationTests/ITest_AsyncSimTask.cpp b/SilKit/IntegrationTests/ITest_AsyncSimTask.cpp old mode 100755 new mode 100644 index 6d6308af6..4aa7b0861 --- a/SilKit/IntegrationTests/ITest_AsyncSimTask.cpp +++ b/SilKit/IntegrationTests/ITest_AsyncSimTask.cpp @@ -71,25 +71,21 @@ TEST(ITest_AsyncSimTask, test_async_simtask_lockstep) }, 1ms); async->SetSimulationStepHandlerAsync([&](auto now, auto) { - std::cout << "Async SimTask now=" << now.count() - << " numActiveSimtasks=" << numActiveSimtasks - << " numSyncSimtasks=" << numSyncSimtasks - << std::endl; + std::cout << "Async SimTask now=" << now.count() << " numActiveSimtasks=" << numActiveSimtasks + << " numSyncSimtasks=" << numSyncSimtasks << std::endl; syncTimeNs = now; numActiveSimtasks++; - if(done) + if (done) { return; } - //wait until counter is evne + //wait until counter is even std::unique_lock lock(mx); - cv.wait(lock, [] { - return cvCounter % 2 == 0; - }); + cv.wait(lock, [] { return cvCounter % 2 == 0; }); // increment so that completer thread will be notified cvCounter++; @@ -103,25 +99,23 @@ TEST(ITest_AsyncSimTask, test_async_simtask_lockstep) } cv.notify_one(); + }, 1ms); - },1ms); - - auto completer = std::thread{[&](){ + auto completer = std::thread{[&]() { while (!done && (syncTimeNs.load() < expectedTime)) { std::unique_lock lock(mx); //wait for odd counter - cv.wait(lock, [] { - return cvCounter % 2 == 1; - }); - if(done) + cv.wait(lock, [] { return cvCounter % 2 == 1; }); + if (done) { return; } - std::cout <<"Completer numActiveSimtasks=" << numActiveSimtasks << std::endl; - if(numActiveSimtasks != 1) + std::cout << "Completer numActiveSimtasks=" << numActiveSimtasks << std::endl; + if (numActiveSimtasks != 1) { - ASSERT_EQ(numActiveSimtasks,0 ) << "Only one SimTask should be active until CompleteSimulationStep is called"; + ASSERT_EQ(numActiveSimtasks, 0) + << "Only one SimTask should be active until CompleteSimulationStep is called"; done = true; } numActiveSimtasks--; @@ -133,12 +127,11 @@ TEST(ITest_AsyncSimTask, test_async_simtask_lockstep) } }}; ASSERT_TRUE(testHarness.Run(5s)) << "TestSim Harness should not reach timeout" - << " numActiveSimtasks=" << numActiveSimtasks - << " numSyncSimtasks=" << numSyncSimtasks - ; - done=true; + << " numActiveSimtasks=" << numActiveSimtasks + << " numSyncSimtasks=" << numSyncSimtasks; + done = true; cv.notify_all(); - if(completer.joinable()) + if (completer.joinable()) { completer.join(); } @@ -163,9 +156,7 @@ TEST(ITest_AsyncSimTask, test_async_simtask_nodeadlock) }, 1ms); async->SetSimulationStepHandlerAsync([&](auto now, auto) { - std::cout << "Async SimTask now=" << now.count() - << " expectedTime=" << expectedTime.count() - << std::endl; + std::cout << "Async SimTask now=" << now.count() << " expectedTime=" << expectedTime.count() << std::endl; if (now == expectedTime) { std::cout << "Stopping simulation at expected time" << std::endl; @@ -178,11 +169,9 @@ TEST(ITest_AsyncSimTask, test_async_simtask_nodeadlock) auto isSame = expectedTime == syncTimeNs; auto isOffByOne = (syncTimeNs == (expectedTime + 1ms)) || (syncTimeNs == (expectedTime - 1ms)); - ASSERT_TRUE(isSame || isOffByOne) - << "Simulation time should be at most off by one expectedTime " - << " (due to NextSimTask handling in distributed participants): " - << " expectedTime=" << expectedTime.count() - << " syncTime=" << syncTimeNs.count(); + ASSERT_TRUE(isSame || isOffByOne) << "Simulation time should be at most off by one expectedTime " + << " (due to NextSimTask handling in distributed participants): " + << " expectedTime=" << expectedTime.count() << " syncTime=" << syncTimeNs.count(); } TEST(ITest_AsyncSimTask, test_async_simtask_different_periods) @@ -215,8 +204,7 @@ TEST(ITest_AsyncSimTask, test_async_simtask_different_periods) asyncParticipant->GetOrCreateLifecycleService()->Stop("Test"); } async->CompleteSimulationStep(); - }, - periodFactor * 1ms); + }, periodFactor * 1ms); // validate that they are called approximately equally often ASSERT_TRUE(std::abs(countAsync * periodFactor - countSync) < periodFactor); } @@ -255,8 +243,7 @@ TEST(ITest_AsyncSimTask, test_async_simtask_multiple_completion_calls) async->CompleteSimulationStep(); async->CompleteSimulationStep(); async->CompleteSimulationStep(); - }, - periodFactor * 1ms); + }, periodFactor * 1ms); // validate that they are called approximately equally often ASSERT_TRUE(std::abs(countAsync * periodFactor - countSync) < periodFactor); } diff --git a/SilKit/IntegrationTests/ITest_CanDemo.cpp b/SilKit/IntegrationTests/ITest_CanDemo.cpp old mode 100755 new mode 100644 index 0b0d72cc2..ad7938277 --- a/SilKit/IntegrationTests/ITest_CanDemo.cpp +++ b/SilKit/IntegrationTests/ITest_CanDemo.cpp @@ -88,176 +88,176 @@ TEST_F(ITest_CanDemo, can_demo) //Set up the Sending and receiving participants { - ///////////////////////////////////////////////////////////////////////// - // CanWriter - ///////////////////////////////////////////////////////////////////////// - const auto participantName = "CanWriter"; - auto&& simParticipant = _simTestHarness->GetParticipant(participantName); - auto&& participant = simParticipant->Participant(); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - auto&& canController = participant->CreateCanController("CanController1", "CAN1"); - - canController->AddFrameTransmitHandler([state](auto, const Can::CanFrameTransmitEvent& frameTransmitEvent) { - if (frameTransmitEvent.status == Can::CanTransmitStatus::Transmitted) - { - state->receivedTransmitted = true; - if((void*)(intptr_t)0xDEADBEEF == frameTransmitEvent.userContext) - { - state->writerHasValidUserContext = true; - } - } - if (frameTransmitEvent.status == Can::CanTransmitStatus::TransmitQueueFull) - { - state->receivedTransmitQueueFull = true; - } - }); - - canController->AddErrorStateChangeHandler([state](auto, const Can::CanErrorStateChangeEvent& errorStateChangeEvent) { - if (errorStateChangeEvent.errorState == Can::CanErrorState::ErrorActive) - { - state->receivedErrorActive = true; - } - }); - - lifecycleService->SetCommunicationReadyHandler([canController, participantName]() { - Log() << "--- " << participantName << ": Init called, setting baud rate and starting"; - canController->SetBaudRate(10'000, 1'000'000, 2'000'000); - canController->Start(); - }); - - timeSyncService->SetSimulationStepHandler( - [canController, state] (auto now, std::chrono::nanoseconds /*duration*/) { - //Cause transmit queue overrun - if (now == 0ms) - { - for (auto i = 0; i < 21; i++) //keep in sync with VCanController::cNumberOfTxObjects - { - canController->SendFrame(state->msg); - } - return; - } - - //Cause a collision - if (now == 10ms) - { - canController->SendFrame(state->msg); - } - - //Normal transmission - if (now > 20ms) - { - Log() << "--- CanWriter sending CanFrame"; - canController->SendFrame(state->msg, (void*)(intptr_t)(0xDEADBEEF)); - } - }, 1ms); - - canController->AddFrameHandler([state](auto, const Can::CanFrameEvent& frameEvent) { - //ignore early test messages - if(frameEvent.direction == SilKit::Services::TransmitDirection::TX) - { - state->writerHasReceivedTx = true; - } - - if(frameEvent.direction == SilKit::Services::TransmitDirection::RX) - { - state->writerHasReceivedRx = true; - } - }, ((DirectionMask)TransmitDirection::RX | (DirectionMask)TransmitDirection::TX) ); + ///////////////////////////////////////////////////////////////////////// + // CanWriter + ///////////////////////////////////////////////////////////////////////// + const auto participantName = "CanWriter"; + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& participant = simParticipant->Participant(); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& canController = participant->CreateCanController("CanController1", "CAN1"); + + canController->AddFrameTransmitHandler([state](auto, const Can::CanFrameTransmitEvent& frameTransmitEvent) { + if (frameTransmitEvent.status == Can::CanTransmitStatus::Transmitted) + { + state->receivedTransmitted = true; + if ((void*)(intptr_t)0xDEADBEEF == frameTransmitEvent.userContext) + { + state->writerHasValidUserContext = true; + } + } + if (frameTransmitEvent.status == Can::CanTransmitStatus::TransmitQueueFull) + { + state->receivedTransmitQueueFull = true; + } + }); + + canController->AddErrorStateChangeHandler( + [state](auto, const Can::CanErrorStateChangeEvent& errorStateChangeEvent) { + if (errorStateChangeEvent.errorState == Can::CanErrorState::ErrorActive) + { + state->receivedErrorActive = true; + } + }); + + lifecycleService->SetCommunicationReadyHandler([canController, participantName]() { + Log() << "--- " << participantName << ": Init called, setting baud rate and starting"; + canController->SetBaudRate(10'000, 1'000'000, 2'000'000); + canController->Start(); + }); + + timeSyncService->SetSimulationStepHandler( + [canController, state](auto now, std::chrono::nanoseconds /*duration*/) { + //Cause transmit queue overrun + if (now == 0ms) + { + for (auto i = 0; i < 21; i++) //keep in sync with VCanController::cNumberOfTxObjects + { + canController->SendFrame(state->msg); + } + return; + } + + //Cause a collision + if (now == 10ms) + { + canController->SendFrame(state->msg); + } + + //Normal transmission + if (now > 20ms) + { + Log() << "--- CanWriter sending CanFrame"; + canController->SendFrame(state->msg, (void*)(intptr_t)(0xDEADBEEF)); + } + }, 1ms); + + canController->AddFrameHandler([state](auto, const Can::CanFrameEvent& frameEvent) { + //ignore early test messages + if (frameEvent.direction == SilKit::Services::TransmitDirection::TX) + { + state->writerHasReceivedTx = true; + } + + if (frameEvent.direction == SilKit::Services::TransmitDirection::RX) + { + state->writerHasReceivedRx = true; + } + }, ((DirectionMask)TransmitDirection::RX | (DirectionMask)TransmitDirection::TX)); } { - ///////////////////////////////////////////////////////////////////////// - // CanReader - ///////////////////////////////////////////////////////////////////////// - const auto participantName = "CanReader"; - auto&& simParticipant = _simTestHarness->GetParticipant(participantName); - auto&& participant = simParticipant->Participant(); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - auto&& canController = participant->CreateCanController("CanController1", "CAN1"); - - lifecycleService->SetCommunicationReadyHandler([canController, participantName]() { - Log() << participantName << ": Init called, setting baud rate and starting"; - canController->SetBaudRate(10'000, 1'000'000, 2'000'000); - canController->Start(); - }); - - timeSyncService->SetSimulationStepHandler([canController, state](auto now, std::chrono::nanoseconds /*duration*/) { - state->receiveTime = std::chrono::duration_cast(now); - //Cause a collision - if (now == 10ms) - { - canController->SendFrame(state->msg); - } - + ///////////////////////////////////////////////////////////////////////// + // CanReader + ///////////////////////////////////////////////////////////////////////// + const auto participantName = "CanReader"; + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& participant = simParticipant->Participant(); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& canController = participant->CreateCanController("CanController1", "CAN1"); + + lifecycleService->SetCommunicationReadyHandler([canController, participantName]() { + Log() << participantName << ": Init called, setting baud rate and starting"; + canController->SetBaudRate(10'000, 1'000'000, 2'000'000); + canController->Start(); + }); + + timeSyncService->SetSimulationStepHandler( + [canController, state](auto now, std::chrono::nanoseconds /*duration*/) { + state->receiveTime = std::chrono::duration_cast(now); + //Cause a collision + if (now == 10ms) + { + canController->SendFrame(state->msg); + } }, 1ms); - canController->AddFrameHandler( - [state, lifecycleService](auto, const Can::CanFrameEvent& frameEvent) - { - if (frameEvent.timestamp < 20ms) - { - //Ignore the early test messages - return; - } - EXPECT_EQ(frameEvent.direction, SilKit::Services::TransmitDirection::RX); - - EXPECT_EQ(frameEvent.frame.canId, 123u); - - EXPECT_TRUE(frameEvent.userContext == (void*)((size_t)(0))); - - if (state->messageCount++ == 10) - { - lifecycleService->Stop("Test done"); - Log() << "--- CanReader: Sending Stop from"; - } - state->result = true; - }); - - canController->AddErrorStateChangeHandler([state](auto, const Can::CanErrorStateChangeEvent& errorStateChangeEvent) { - if (errorStateChangeEvent.errorState == Can::CanErrorState::ErrorActive) - { - state->readerReceivedErrorActive = true; - } - }); + canController->AddFrameHandler([state, lifecycleService](auto, const Can::CanFrameEvent& frameEvent) { + if (frameEvent.timestamp < 20ms) + { + //Ignore the early test messages + return; + } + EXPECT_EQ(frameEvent.direction, SilKit::Services::TransmitDirection::RX); + + EXPECT_EQ(frameEvent.frame.canId, 123u); + + EXPECT_TRUE(frameEvent.userContext == (void*)((size_t)(0))); + + if (state->messageCount++ == 10) + { + lifecycleService->Stop("Test done"); + Log() << "--- CanReader: Sending Stop from"; + } + state->result = true; + }); + + canController->AddErrorStateChangeHandler( + [state](auto, const Can::CanErrorStateChangeEvent& errorStateChangeEvent) { + if (errorStateChangeEvent.errorState == Can::CanErrorState::ErrorActive) + { + state->readerReceivedErrorActive = true; + } + }); } { - ///////////////////////////////////////////////////////////////////////// - // CanMonitor -- Ensure that the Can simulation behaves like a bus - ///////////////////////////////////////////////////////////////////////// - const auto participantName = "CanMonitor"; - auto&& simParticipant = _simTestHarness->GetParticipant(participantName); - auto&& participant = simParticipant->Participant(); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& canController = participant->CreateCanController("CanController1", "CAN1"); - - lifecycleService->SetCommunicationReadyHandler([canController, participantName]() { - Log() << participantName << ": Init called, setting baud rate and starting"; - canController->SetBaudRate(10'000, 1'000'000, 2'000'000); - canController->Start(); - }); - - canController->AddErrorStateChangeHandler([state](auto, const Can::CanErrorStateChangeEvent& errorStateChangeEvent) { - if (errorStateChangeEvent.errorState == Can::CanErrorState::ErrorActive) - { - state->monitorReceivedErrorActive = true; - } - }); - - canController->AddFrameHandler([state](auto, const Can::CanFrameEvent& ) { - state->monitorReceiveCount++; - }); + ///////////////////////////////////////////////////////////////////////// + // CanMonitor -- Ensure that the Can simulation behaves like a bus + ///////////////////////////////////////////////////////////////////////// + const auto participantName = "CanMonitor"; + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& participant = simParticipant->Participant(); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& canController = participant->CreateCanController("CanController1", "CAN1"); + + lifecycleService->SetCommunicationReadyHandler([canController, participantName]() { + Log() << participantName << ": Init called, setting baud rate and starting"; + canController->SetBaudRate(10'000, 1'000'000, 2'000'000); + canController->Start(); + }); + + canController->AddErrorStateChangeHandler( + [state](auto, const Can::CanErrorStateChangeEvent& errorStateChangeEvent) { + if (errorStateChangeEvent.errorState == Can::CanErrorState::ErrorActive) + { + state->monitorReceivedErrorActive = true; + } + }); + + canController->AddFrameHandler([state](auto, const Can::CanFrameEvent&) { state->monitorReceiveCount++; }); } - auto ok = _simTestHarness->Run(5s); + auto ok = _simTestHarness->Run(5s); ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; EXPECT_TRUE(state->result) << " Expecting a message"; EXPECT_TRUE(state->writerHasReceivedTx) << " Expecting a receive Message with Direction == TX on CanWriter"; EXPECT_TRUE(state->writerHasValidUserContext) << " Expecting a CanFrameTransmitEvent with a valid" - << " userContext during normal transmission"; - EXPECT_FALSE(state->receivedTransmitQueueFull) << " Sending too fast should NOT result in TransmitQueue full in trivial simulation"; + << " userContext during normal transmission"; + EXPECT_FALSE(state->receivedTransmitQueueFull) + << " Sending too fast should NOT result in TransmitQueue full in trivial simulation"; EXPECT_TRUE(state->receivedTransmitted) << " Sending should result in acknowledgment"; EXPECT_FALSE(state->receivedErrorActive) << " Collisions are not computed in trivial simulation"; EXPECT_FALSE(state->readerReceivedErrorActive) << " Collisions are not computed in trivial simulation"; diff --git a/SilKit/IntegrationTests/ITest_CatchExceptionsInCallbacks.cpp b/SilKit/IntegrationTests/ITest_CatchExceptionsInCallbacks.cpp old mode 100755 new mode 100644 index 7e76308ed..8b0ea8825 --- a/SilKit/IntegrationTests/ITest_CatchExceptionsInCallbacks.cpp +++ b/SilKit/IntegrationTests/ITest_CatchExceptionsInCallbacks.cpp @@ -48,9 +48,7 @@ using testing::Return; class ITest_CatchExceptionsInCallbacks : public testing::Test { protected: - ITest_CatchExceptionsInCallbacks() - { - } + ITest_CatchExceptionsInCallbacks() {} void Publish() { @@ -69,7 +67,8 @@ TEST_F(ITest_CatchExceptionsInCallbacks, please_dont_crash_vasio) { auto registryUri = MakeTestRegistryUri(); - auto registry = SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); + auto registry = + SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); registry->StartListening(registryUri); auto pubParticipant = @@ -84,9 +83,9 @@ TEST_F(ITest_CatchExceptionsInCallbacks, please_dont_crash_vasio) subscriber = subParticipant->CreateDataSubscriber( "SubCtrl1", matchingDataSpec, [this](auto* /*subscriber*/, const SilKit::Services::PubSub::DataMessageEvent& /*data*/) { - this->testOk.set_value(true); - throw SilKit::SilKitError{"CrashTest"}; - }); + this->testOk.set_value(true); + throw SilKit::SilKitError{"CrashTest"}; + }); std::this_thread::sleep_for(500ms); std::thread publishThread{[this] { this->Publish(); }}; diff --git a/SilKit/IntegrationTests/ITest_CommunicationGuarantees.cpp b/SilKit/IntegrationTests/ITest_CommunicationGuarantees.cpp index c0fd760b0..a5a8a8c5f 100644 --- a/SilKit/IntegrationTests/ITest_CommunicationGuarantees.cpp +++ b/SilKit/IntegrationTests/ITest_CommunicationGuarantees.cpp @@ -72,8 +72,7 @@ class TestParticipant TestParticipant& operator=(TestParticipant&&) = default; TestParticipant(const std::string& newName, std::vector newPubTopics, - std::vector newSubTopics, OperationMode newOperationMode, - TimeMode newTimeMode) + std::vector newSubTopics, OperationMode newOperationMode, TimeMode newTimeMode) { name = newName; operationMode = newOperationMode; @@ -105,14 +104,35 @@ class TestParticipant } } - void SetPublishInCommReady(bool on) { publishInCommReady = on; } - void SetPublishInStopHandler(bool on) { publishInStopHandler = on; } - void SetPublishInShutdownHandler(bool on) { publishInShutdownHandler = on; } - void SetPublishInAbortHandler(bool on) { publishInAbortHandler = on; } - void SetWaitForCommunicationInCommReadyHandler(bool on) { waitForCommunicationInCommReadyHandler = on; } + void SetPublishInCommReady(bool on) + { + publishInCommReady = on; + } + void SetPublishInStopHandler(bool on) + { + publishInStopHandler = on; + } + void SetPublishInShutdownHandler(bool on) + { + publishInShutdownHandler = on; + } + void SetPublishInAbortHandler(bool on) + { + publishInAbortHandler = on; + } + void SetWaitForCommunicationInCommReadyHandler(bool on) + { + waitForCommunicationInCommReadyHandler = on; + } - auto GetPubBuffer() { return pubBuffer; } - auto GetSubBuffer() { return subBuffer; } + auto GetPubBuffer() + { + return pubBuffer; + } + auto GetSubBuffer() + { + return subBuffer; + } void ResetReception() { @@ -218,9 +238,7 @@ class TestParticipant // Sync participant stop the test in the first SimTask timeSyncService = lifecycleService->CreateTimeSyncService(); timeSyncService->SetSimulationStepHandler( - [](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) { - }, - 1s); + [](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) {}, 1s); } // Async participant stop the test on enter RunningState @@ -311,17 +329,17 @@ class TestParticipant subControllers.push_back(participant->CreateDataSubscriber( controllerName, spec, [this](IDataSubscriber* /*subscriber*/, const DataMessageEvent& dataMessageEvent) { - if (!allReceived) + if (!allReceived) + { + receiveMsgCount++; + if (receiveMsgCount >= numMsgToReceiveTotal) { - receiveMsgCount++; - if (receiveMsgCount >= numMsgToReceiveTotal) - { - Log() << "[" << name << "] All received"; - AffirmCommunication(); - } + Log() << "[" << name << "] All received"; + AffirmCommunication(); } - subBuffer.push_back(SilKit::Util::ToStdVector(dataMessageEvent.data)); - })); + } + subBuffer.push_back(SilKit::Util::ToStdVector(dataMessageEvent.data)); + })); } Log() << "[" << name << "] ...created subscribers"; } @@ -337,7 +355,10 @@ class TestParticipant AffirmFinalState(); } - auto Name() const -> std::string { return name; } + auto Name() const -> std::string + { + return name; + } public: std::string name; @@ -441,9 +462,10 @@ class ITest_CommunicationGuarantees : public testing::Test void RunSystemMaster(const std::string& registryUri) { systemController.participant = SilKit::CreateParticipant(SilKit::Config::ParticipantConfigurationFromString(""), - systemMasterName, registryUri); + systemMasterName, registryUri); - systemController.lifecycleService = systemController.participant->CreateLifecycleService({OperationMode::Coordinated}); + systemController.lifecycleService = + systemController.participant->CreateLifecycleService({OperationMode::Coordinated}); systemController.systemController = SilKit::Experimental::Participant::CreateSystemController(systemController.participant.get()); @@ -452,13 +474,11 @@ class ITest_CommunicationGuarantees : public testing::Test systemController.systemController->SetWorkflowConfiguration({requiredParticipantNames}); - systemController.systemMonitor->AddSystemStateHandler([this](SystemState newState) { - SystemStateHandler(newState); - }); + systemController.systemMonitor->AddSystemStateHandler( + [this](SystemState newState) { SystemStateHandler(newState); }); - systemController.systemMonitor->AddParticipantStatusHandler([this](ParticipantStatus newStatus) { - ParticipantStatusHandler(newStatus); - }); + systemController.systemMonitor->AddParticipantStatusHandler( + [this](ParticipantStatus newStatus) { ParticipantStatusHandler(newStatus); }); systemController.systemStateRunning = systemController.systemStateRunningPromise.get_future(); @@ -469,9 +489,7 @@ class ITest_CommunicationGuarantees : public testing::Test { for (auto& p : participants) { - participantThreads.emplace_back([&p, registryUri] { - p.ParticipantThread(registryUri); - }); + participantThreads.emplace_back([&p, registryUri] { p.ParticipantThread(registryUri); }); } } @@ -540,7 +558,7 @@ class ITest_CommunicationGuarantees : public testing::Test for (auto& p : participants) { if (p.operationMode == OperationMode::Autonomous) - p.lifecycleService->Stop("End test"); + p.lifecycleService->Stop("End test"); } Log() << ">> Joining participant threads"; @@ -571,11 +589,11 @@ class ITest_CommunicationGuarantees : public testing::Test participants.push_back({"Pub", {topic1}, {}, OperationMode::Autonomous, TimeMode::Async}); auto& pubParticipant = participants.at(0); if (handlerToTest == "Stop") - pubParticipant.SetPublishInStopHandler(true); + pubParticipant.SetPublishInStopHandler(true); else if (handlerToTest == "Shutdown") - pubParticipant.SetPublishInShutdownHandler(true); + pubParticipant.SetPublishInShutdownHandler(true); else if (handlerToTest == "Abort") - pubParticipant.SetPublishInAbortHandler(true); + pubParticipant.SetPublishInAbortHandler(true); participants.push_back({"Sub", {}, {topic1}, OperationMode::Autonomous, TimeMode::Async}); auto& subParticipant = participants.at(1); @@ -766,10 +784,8 @@ TEST_F(ITest_CommunicationGuarantees, test_receive_in_comm_ready_handler_mixed) } std::vector coordinatedSyncParticipantsSub; - coordinatedSyncParticipantsSub.push_back( - {"CoordSub1", {}, topics, OperationMode::Coordinated, TimeMode::Sync}); - coordinatedSyncParticipantsSub.push_back( - {"CoordSub2", {}, topics, OperationMode::Coordinated, TimeMode::Sync}); + coordinatedSyncParticipantsSub.push_back({"CoordSub1", {}, topics, OperationMode::Coordinated, TimeMode::Sync}); + coordinatedSyncParticipantsSub.push_back({"CoordSub2", {}, topics, OperationMode::Coordinated, TimeMode::Sync}); std::vector autonomousAsyncParticipantsPub; autonomousAsyncParticipantsPub.push_back({"Pub", topics, {}, OperationMode::Autonomous, TimeMode::Async}); diff --git a/SilKit/IntegrationTests/ITest_Dashboard.cpp b/SilKit/IntegrationTests/ITest_Dashboard.cpp old mode 100755 new mode 100644 index d2c94c6ca..1424d5732 --- a/SilKit/IntegrationTests/ITest_Dashboard.cpp +++ b/SilKit/IntegrationTests/ITest_Dashboard.cpp @@ -66,9 +66,8 @@ class ITest_Dashboard : public ITest_DashboardTestHarness (void)participant->CreateCanController(canonicalName, networkName); auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - timeSyncService->SetSimulationStepHandler( - CreateSimulationStepHandler(participantName1, lifecycleService), - 10ms); + timeSyncService->SetSimulationStepHandler(CreateSimulationStepHandler(participantName1, lifecycleService), + 10ms); } { auto&& simParticipant = _simTestHarness->GetParticipant(participantName2); @@ -146,8 +145,8 @@ class ITest_Dashboard : public ITest_DashboardTestHarness void CheckStates(std::set actual, std::set expected, const std::string& participantName, uint64_t simulationId) { - ASSERT_GE(actual.size(), expected.size()) << "Wrong number of states for " << participantName << " of simulation " - << simulationId << "!"; + ASSERT_GE(actual.size(), expected.size()) + << "Wrong number of states for " << participantName << " of simulation " << simulationId << "!"; for (auto&& state : expected) { ASSERT_TRUE(actual.find(state) != actual.end()) @@ -283,12 +282,10 @@ TEST_F(ITest_Dashboard, dashboard_no_simulation) { SetupFromParticipantLists({}, {}); auto testResult = SilKit::Dashboard::RunDashboardTest( - ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, - [this]() { - auto ok = _simTestHarness->Run(5s); - ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; - }, - 0); + ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, [this]() { + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + }, 0); _simTestHarness->ResetRegistry(); CheckTestResult(testResult, CreateExpectedTestResult({}, false)); } @@ -306,8 +303,8 @@ TEST_F(ITest_Dashboard, dashboard_unicode_emoji_coordinated) auto testResult = SilKit::Dashboard::RunDashboardTest( ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, [this, &participantName1, &participantName2, &canonicalName, &networkName]() { - RunCanDemo(participantName1, participantName2, canonicalName, networkName); - }); + RunCanDemo(participantName1, participantName2, canonicalName, networkName); + }); _simTestHarness->ResetRegistry(); CheckTestResult(testResult, CreateExpectedTestResult( @@ -326,8 +323,8 @@ TEST_F(ITest_Dashboard, dashboard_can_coordinated) auto testResult = SilKit::Dashboard::RunDashboardTest( ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, [this, &participantName1, &participantName2, &canonicalName, &networkName]() { - RunCanDemo(participantName1, participantName2, canonicalName, networkName); - }); + RunCanDemo(participantName1, participantName2, canonicalName, networkName); + }); _simTestHarness->ResetRegistry(); CheckTestResult( testResult, @@ -346,10 +343,9 @@ TEST_F(ITest_Dashboard, dashboard_can_repeat) auto testResult = SilKit::Dashboard::RunDashboardTest( ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, [this, &participantName1, &participantName2, &canonicalName, &networkName]() { - RunCanDemo(participantName1, participantName2, canonicalName, networkName); - RunCanDemo(participantName1, participantName2, canonicalName, networkName); - }, - 2); + RunCanDemo(participantName1, participantName2, canonicalName, networkName); + RunCanDemo(participantName1, participantName2, canonicalName, networkName); + }, 2); _simTestHarness->ResetRegistry(); std::map> simulation{ {participantName1, {{6, {"", "cancontroller", canonicalName, networkName, {}}}}}, @@ -375,30 +371,29 @@ TEST_F(ITest_Dashboard, dashboard_pubsub_mix) auto testResult = SilKit::Dashboard::RunDashboardTest( ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, [this, &participantName1, &canonicalName1, &spec1, &participantName2, &canonicalName2, &spec2]() { - _simTestHarness->CreateSystemController(); - { - auto&& simParticipant = _simTestHarness->GetParticipant(participantName1); - auto&& participant = simParticipant->Participant(); - (void)participant->CreateDataPublisher(canonicalName1, spec1); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - timeSyncService->SetSimulationStepHandler( - CreateSimulationStepHandler(participantName1, lifecycleService), 10ms); - } - { - auto&& simParticipant = _simTestHarness->GetParticipant(participantName2); - auto&& participant = simParticipant->Participant(); - (void)participant->CreateDataSubscriber(canonicalName2, spec2, [](auto, const auto&) { - }); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& systemMonitor = simParticipant->GetOrCreateSystemMonitor(); - (void)systemMonitor->AddParticipantStatusHandler( - CreateAutonomousParticipantStatusHandler(participantName2, lifecycleService)); - } - auto ok = _simTestHarness->Run(5s); - ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; - _simTestHarness->ResetParticipants(); - }); + _simTestHarness->CreateSystemController(); + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName1); + auto&& participant = simParticipant->Participant(); + (void)participant->CreateDataPublisher(canonicalName1, spec1); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + timeSyncService->SetSimulationStepHandler(CreateSimulationStepHandler(participantName1, lifecycleService), + 10ms); + } + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName2); + auto&& participant = simParticipant->Participant(); + (void)participant->CreateDataSubscriber(canonicalName2, spec2, [](auto, const auto&) {}); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& systemMonitor = simParticipant->GetOrCreateSystemMonitor(); + (void)systemMonitor->AddParticipantStatusHandler( + CreateAutonomousParticipantStatusHandler(participantName2, lifecycleService)); + } + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + _simTestHarness->ResetParticipants(); + }); _simTestHarness->ResetRegistry(); CheckTestResult( testResult, @@ -429,30 +424,28 @@ TEST_F(ITest_Dashboard, dashboard_rpc_autonomous) auto testResult = SilKit::Dashboard::RunDashboardTest( ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, [this, &participantName1, &canonicalName1, &spec1, &participantName2, &canonicalName2, &spec2]() { - { - auto&& simParticipant = _simTestHarness->GetParticipant(participantName1); - auto&& participant = simParticipant->Participant(); - (void)participant->CreateRpcClient(canonicalName1, spec1, [](auto*, const auto&) { - }); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& systemMonitor = simParticipant->GetOrCreateSystemMonitor(); - (void)systemMonitor->AddParticipantStatusHandler( - CreateAutonomousParticipantStatusHandler(participantName1, lifecycleService)); - } - { - auto&& simParticipant = _simTestHarness->GetParticipant(participantName2); - auto&& participant = simParticipant->Participant(); - (void)participant->CreateRpcServer(canonicalName2, spec2, [](auto*, const auto&) { - }); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& systemMonitor = simParticipant->GetOrCreateSystemMonitor(); - (void)systemMonitor->AddParticipantStatusHandler( - CreateAutonomousParticipantStatusHandler(participantName2, lifecycleService)); - } - auto ok = _simTestHarness->Run(5s); - ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; - _simTestHarness->ResetParticipants(); - }); + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName1); + auto&& participant = simParticipant->Participant(); + (void)participant->CreateRpcClient(canonicalName1, spec1, [](auto*, const auto&) {}); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& systemMonitor = simParticipant->GetOrCreateSystemMonitor(); + (void)systemMonitor->AddParticipantStatusHandler( + CreateAutonomousParticipantStatusHandler(participantName1, lifecycleService)); + } + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName2); + auto&& participant = simParticipant->Participant(); + (void)participant->CreateRpcServer(canonicalName2, spec2, [](auto*, const auto&) {}); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& systemMonitor = simParticipant->GetOrCreateSystemMonitor(); + (void)systemMonitor->AddParticipantStatusHandler( + CreateAutonomousParticipantStatusHandler(participantName2, lifecycleService)); + } + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + _simTestHarness->ResetParticipants(); + }); _simTestHarness->ResetRegistry(); CheckTestResult( testResult, @@ -469,43 +462,44 @@ TEST_F(ITest_Dashboard, dashboard_netsim_coordinated) { const auto participantName = "NetSim"; SetupFromParticipantLists({participantName}, {}); - auto testResult = SilKit::Dashboard::RunDashboardTest( - ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, - [this, &participantName]() { - _simTestHarness->CreateSystemController(); - { - auto&& simParticipant = _simTestHarness->GetParticipant(participantName, _participantConfig); - auto&& participant = simParticipant->Participant(); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - auto&& participantInternal = &SilKit::Tests::ToParticipantInternal(*participant); - auto&& serviceDiscovery = participantInternal->GetServiceDiscovery(); - - lifecycleService->SetCommunicationReadyHandler([participantName, serviceDiscovery]() { - ServiceDescriptor linkDescriptor{}; - linkDescriptor.SetServiceType(ServiceType::Link); - linkDescriptor.SetParticipantNameAndComputeId(participantName); - for (auto cfg : - {std::make_pair(NetworkType::CAN, "CAN1"), std::make_pair(NetworkType::Ethernet, "ETH1"), - std::make_pair(NetworkType::FlexRay, "FR1"), std::make_pair(NetworkType::LIN, "LIN1")}) - { - linkDescriptor.SetNetworkType(cfg.first); - linkDescriptor.SetNetworkName(cfg.second); - linkDescriptor.SetServiceName(cfg.second); - serviceDiscovery->NotifyServiceCreated(std::move(linkDescriptor)); - } - }); - timeSyncService->SetSimulationStepHandler( - [simParticipant](auto, auto) { - Log() << simParticipant->Name() << ": stopping"; - simParticipant->Stop(); - }, - 10ms); - } - auto ok = _simTestHarness->Run(5s); - ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; - _simTestHarness->ResetParticipants(); - }); + auto testResult = + SilKit::Dashboard::RunDashboardTest(ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), + _registryUri, _dashboardUri, [this, &participantName]() { + _simTestHarness->CreateSystemController(); + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName, _participantConfig); + auto&& participant = simParticipant->Participant(); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& participantInternal = &SilKit::Tests::ToParticipantInternal(*participant); + auto&& serviceDiscovery = participantInternal->GetServiceDiscovery(); + + lifecycleService->SetCommunicationReadyHandler([participantName, serviceDiscovery]() { + ServiceDescriptor linkDescriptor{}; + linkDescriptor.SetServiceType(ServiceType::Link); + linkDescriptor.SetParticipantNameAndComputeId(participantName); + for (auto cfg : + {std::make_pair(NetworkType::CAN, "CAN1"), std::make_pair(NetworkType::Ethernet, "ETH1"), + std::make_pair(NetworkType::FlexRay, "FR1"), std::make_pair(NetworkType::LIN, "LIN1")}) + { + linkDescriptor.SetNetworkType(cfg.first); + linkDescriptor.SetNetworkName(cfg.second); + linkDescriptor.SetServiceName(cfg.second); + serviceDiscovery->NotifyServiceCreated(std::move(linkDescriptor)); + } + }); + timeSyncService->SetSimulationStepHandler([simParticipant](auto currentSimTime, auto duration) { + if (currentSimTime > duration) + { + Log() << simParticipant->Name() << ": stopping"; + simParticipant->Stop(); + } + }, 10ms); + } + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + _simTestHarness->ResetParticipants(); + }); _simTestHarness->ResetRegistry(); auto expected = ITest_Dashboard::CreateExpectedTestResult({{{participantName, {}}}}, true); expected.dataBySimulation[1].linksByParticipant = { diff --git a/SilKit/IntegrationTests/ITest_DashboardServerTimeout.cpp b/SilKit/IntegrationTests/ITest_DashboardServerTimeout.cpp index e734d92a2..1b79ef68f 100644 --- a/SilKit/IntegrationTests/ITest_DashboardServerTimeout.cpp +++ b/SilKit/IntegrationTests/ITest_DashboardServerTimeout.cpp @@ -54,22 +54,18 @@ TEST_F(ITest_DashboardServerTimeout, dashboard_creationtimeout) auto testResult = SilKit::Dashboard::RunDashboardTest( ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, [this, &participantName, &canonicalName, &networkName]() { - _simTestHarness->CreateSystemController(); - auto&& simParticipant = _simTestHarness->GetParticipant(participantName, _participantConfig); - auto&& participant = simParticipant->Participant(); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - (void)participant->CreateCanController(canonicalName, networkName); - timeSyncService->SetSimulationStepHandler( - [lifecycleService](auto, auto) { - lifecycleService->Stop("Test done"); - }, - 1ms); - auto ok = _simTestHarness->Run(5s); - ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; - _simTestHarness->ResetParticipants(); - }, - 1, std::chrono::seconds{7}, std::chrono::seconds{0}); + _simTestHarness->CreateSystemController(); + auto&& simParticipant = _simTestHarness->GetParticipant(participantName, _participantConfig); + auto&& participant = simParticipant->Participant(); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + (void)participant->CreateCanController(canonicalName, networkName); + timeSyncService->SetSimulationStepHandler( + [lifecycleService](auto, auto) { lifecycleService->Stop("Test done"); }, 1ms); + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + _simTestHarness->ResetParticipants(); + }, 1, std::chrono::seconds{7}, std::chrono::seconds{0}); ASSERT_FALSE(testResult.allSimulationsFinished) << "Simulation should not be finished!"; _simTestHarness->ResetRegistry(); } @@ -83,22 +79,18 @@ TEST_F(ITest_DashboardServerTimeout, dashboard_updatetimeout) auto testResult = SilKit::Dashboard::RunDashboardTest( ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri, [this, &participantName, &canonicalName, &networkName]() { - _simTestHarness->CreateSystemController(); - auto&& simParticipant = _simTestHarness->GetParticipant(participantName, _participantConfig); - auto&& participant = simParticipant->Participant(); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - (void)participant->CreateCanController(canonicalName, networkName); - timeSyncService->SetSimulationStepHandler( - [lifecycleService](auto, auto) { - lifecycleService->Stop("Test done"); - }, - 1ms); - auto ok = _simTestHarness->Run(5s); - ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; - _simTestHarness->ResetParticipants(); - }, - 1, std::chrono::seconds{0}, std::chrono::seconds{7}); + _simTestHarness->CreateSystemController(); + auto&& simParticipant = _simTestHarness->GetParticipant(participantName, _participantConfig); + auto&& participant = simParticipant->Participant(); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + (void)participant->CreateCanController(canonicalName, networkName); + timeSyncService->SetSimulationStepHandler( + [lifecycleService](auto, auto) { lifecycleService->Stop("Test done"); }, 1ms); + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + _simTestHarness->ResetParticipants(); + }, 1, std::chrono::seconds{0}, std::chrono::seconds{7}); ASSERT_FALSE(testResult.allSimulationsFinished) << "Simulation should not be finished!"; _simTestHarness->ResetRegistry(); } diff --git a/SilKit/IntegrationTests/ITest_DashboardServerUnavailable.cpp b/SilKit/IntegrationTests/ITest_DashboardServerUnavailable.cpp index 0012705b3..08e77b29d 100644 --- a/SilKit/IntegrationTests/ITest_DashboardServerUnavailable.cpp +++ b/SilKit/IntegrationTests/ITest_DashboardServerUnavailable.cpp @@ -50,8 +50,8 @@ TEST_F(ITest_DashboardServerUnavailable, dashboard_server_unavailable) const auto networkName = "CAN1"; SetupFromParticipantLists({participantName}, {}); { - auto dashboard = - SilKit::Dashboard::CreateDashboard(ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri); + auto dashboard = SilKit::Dashboard::CreateDashboard( + ParticipantConfigurationFromStringImpl(_dashboardParticipantConfig), _registryUri, _dashboardUri); { _simTestHarness->CreateSystemController(); auto&& simParticipant = _simTestHarness->GetParticipant(participantName, _participantConfig); @@ -60,10 +60,7 @@ TEST_F(ITest_DashboardServerUnavailable, dashboard_server_unavailable) auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); (void)participant->CreateCanController(canonicalName, networkName); timeSyncService->SetSimulationStepHandler( - [lifecycleService](auto, auto) { - lifecycleService->Stop("Test done"); - }, - 1ms); + [lifecycleService](auto, auto) { lifecycleService->Stop("Test done"); }, 1ms); auto ok = _simTestHarness->Run(5s); ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; _simTestHarness->ResetParticipants(); diff --git a/SilKit/IntegrationTests/ITest_DeterministicSimVAsio.cpp b/SilKit/IntegrationTests/ITest_DeterministicSimVAsio.cpp index ba3209a1a..23fff9876 100644 --- a/SilKit/IntegrationTests/ITest_DeterministicSimVAsio.cpp +++ b/SilKit/IntegrationTests/ITest_DeterministicSimVAsio.cpp @@ -66,7 +66,7 @@ std::istream& operator>>(std::istream& in, nanoseconds& timestamp) class Publisher { public: - Publisher(const std::string& registryUri, const uint32_t publisherIndex, const uint32_t testSize) + Publisher(const std::string& registryUri, const uint32_t publisherIndex, const uint32_t testSize) : _testSize{testSize} { _participantName = "Publisher" + std::to_string(publisherIndex); @@ -79,15 +79,12 @@ class Publisher auto* timeSyncService = _lifecycleService->CreateTimeSyncService(); SilKit::Services::PubSub::PubSubSpec dataSpec{topicName, {}}; auto* publisher = _participant->CreateDataPublisher("PubCtrl1", dataSpec, 0); - timeSyncService->SetSimulationStepHandler( - [this, publisher](const nanoseconds now, nanoseconds /*duration*/) { - + timeSyncService->SetSimulationStepHandler([this, publisher](const nanoseconds now, nanoseconds /*duration*/) { if (_messageIndex < _testSize) { PublishMessage(publisher, now, _messageIndex++); } - }, - period); + }, period); } void RunAsync() @@ -124,13 +121,14 @@ class Publisher uint32_t _messageIndex{0u}; uint32_t _testSize{0u}; std::future _simulationFuture; - std::string _participantName; + std::string _participantName; }; class Subscriber { public: - Subscriber(const std::string& participantName, const std::string& registryUri, const uint32_t& publisherCount, const uint32_t testSize) + Subscriber(const std::string& participantName, const std::string& registryUri, const uint32_t& publisherCount, + const uint32_t testSize) : _publisherCount{publisherCount} , _messageIndexes(publisherCount, 0u) , _testSize{testSize} @@ -155,17 +153,13 @@ class Subscriber _participant->CreateDataSubscriber( "SubCtrl" + std::to_string(publisherIndex), dataSpec, [this, publisherIndex](IDataSubscriber* subscriber, const DataMessageEvent& dataMessageEvent) { - ReceiveMessage(subscriber, dataMessageEvent, publisherIndex); - }); + ReceiveMessage(subscriber, dataMessageEvent, publisherIndex); + }); } - timeSyncService->SetSimulationStepHandler( - [this](const nanoseconds now, nanoseconds /*duration*/) { - + timeSyncService->SetSimulationStepHandler([this](const nanoseconds now, nanoseconds /*duration*/) { _currentTick = now; - - }, - period); + }, period); } std::future RunAsync() const @@ -179,10 +173,11 @@ class Subscriber } private: - void ReceiveMessage(IDataSubscriber* /*subscriber*/, const DataMessageEvent& dataMessageEvent, const uint32_t publisherIndex) + void ReceiveMessage(IDataSubscriber* /*subscriber*/, const DataMessageEvent& dataMessageEvent, + const uint32_t publisherIndex) { auto& messageIndex = _messageIndexes[publisherIndex]; - const std::string message{ dataMessageEvent.data.begin(), dataMessageEvent.data.end()}; + const std::string message{dataMessageEvent.data.begin(), dataMessageEvent.data.end()}; std::string receivedMessage; nanoseconds sentTick = {}; @@ -211,7 +206,7 @@ class Subscriber ASSERT_TRUE(_currentTick == sentTick || _currentTick + period == sentTick); // This expectation tests the order of the messages per publisher. - // For each publisher each send message should come in order. The order is tested + // For each publisher each send message should come in order. The order is tested // by incrementing the messageIndex for each message in the Publisher and Subscriber. ASSERT_EQ(messageIndex, receivedIndex); @@ -262,7 +257,8 @@ TEST_F(ITest_DeterministicSimVAsio, deterministic_simulation_vasio) syncParticipantNames.push_back("Publisher" + std::to_string(i)); } - auto registry = SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); + auto registry = + SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); registry->StartListening(registryUri); // The subscriber assumes the role of the system controller and initiates simulation state changes diff --git a/SilKit/IntegrationTests/ITest_DifferentPeriods.cpp b/SilKit/IntegrationTests/ITest_DifferentPeriods.cpp index e8ac8005b..4e9027d83 100644 --- a/SilKit/IntegrationTests/ITest_DifferentPeriods.cpp +++ b/SilKit/IntegrationTests/ITest_DifferentPeriods.cpp @@ -67,7 +67,8 @@ std::istream& operator>>(std::istream& in, nanoseconds& timestamp) class Publisher { public: - Publisher(const std::string& registryUri, const uint32_t publisherIndex, const uint32_t numMessages, std::chrono::nanoseconds period) + Publisher(const std::string& registryUri, const uint32_t publisherIndex, const uint32_t numMessages, + std::chrono::nanoseconds period) : _numMessages{numMessages} { _participantName = "Publisher" + std::to_string(publisherIndex); @@ -83,12 +84,12 @@ class Publisher timeSyncService->SetSimulationStepHandler( [this, publisher, period](const nanoseconds now, nanoseconds /*duration*/) { - ASSERT_TRUE((now.count() % period.count()) == 0); - if (_messageIndex < _numMessages) - { - PublishMessage(publisher, now, _messageIndex++); - } - }, period); + ASSERT_TRUE((now.count() % period.count()) == 0); + if (_messageIndex < _numMessages) + { + PublishMessage(publisher, now, _messageIndex++); + } + }, period); } void RunAsync() @@ -136,7 +137,7 @@ class Subscriber : _publisherCount{publisherCount} , _messageIndexes(publisherCount, 0u) , _numMessages{numMessages} - , _syncParticipantNames { syncParticipantNames } + , _syncParticipantNames{syncParticipantNames} , _participantName{participantName} { _participant = SilKit::CreateParticipant(SilKit::Config::ParticipantConfigurationFromString(""), @@ -158,15 +159,13 @@ class Subscriber _participant->CreateDataSubscriber( "SubCtrl" + std::to_string(publisherIndex), dataSpec, [this, publisherIndex](IDataSubscriber* subscriber, const DataMessageEvent& dataMessageEvent) { - ReceiveMessage(subscriber, dataMessageEvent, publisherIndex); - }); + ReceiveMessage(subscriber, dataMessageEvent, publisherIndex); + }); } - timeSyncService->SetSimulationStepHandler( - [this](const nanoseconds now, nanoseconds /*duration*/) { + timeSyncService->SetSimulationStepHandler([this](const nanoseconds now, nanoseconds /*duration*/) { _currentTime = now; ASSERT_TRUE((_currentTime.count() % subscriberPeriod.count()) == 0); - }, - subscriberPeriod); + }, subscriberPeriod); } std::future RunAsync() const @@ -180,12 +179,11 @@ class Subscriber } private: - void ReceiveMessage(IDataSubscriber* /*subscriber*/, const DataMessageEvent& dataMessageEvent, const uint32_t publisherIndex) { auto& messageIndex = _messageIndexes[publisherIndex]; - const std::string message{ dataMessageEvent.data.begin(), dataMessageEvent.data.end()}; + const std::string message{dataMessageEvent.data.begin(), dataMessageEvent.data.end()}; std::string receivedMessage; nanoseconds sentTime = {}; @@ -205,7 +203,7 @@ class Subscriber // The constant testMessage should have been sent and received correctly EXPECT_EQ(testMessage, receivedMessage); - + ASSERT_TRUE(sentTime >= _currentTime - subscriberPeriod); ASSERT_TRUE(sentTime <= _currentTime + subscriberPeriod); @@ -248,7 +246,6 @@ class ITest_DifferentPeriods : public testing::Test protected: std::string registryUri; - }; @@ -270,7 +267,8 @@ TEST_F(ITest_DifferentPeriods, different_simtask_periods) syncParticipantNames.push_back("Publisher" + std::to_string(i)); } - auto registry = SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); + auto registry = + SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); registry->StartListening(registryUri); // The subscriber assumes the role of the system controller and initiates simulation state changes diff --git a/SilKit/IntegrationTests/ITest_EthernetDemo.cpp b/SilKit/IntegrationTests/ITest_EthernetDemo.cpp old mode 100755 new mode 100644 index 7a3af086c..37c3fd9f7 --- a/SilKit/IntegrationTests/ITest_EthernetDemo.cpp +++ b/SilKit/IntegrationTests/ITest_EthernetDemo.cpp @@ -55,16 +55,17 @@ struct ITest_EthernetDemo : ITest_SimTestHarness TEST_F(ITest_EthernetDemo, ethernet_demo) { - //Create a simulation setup with 2 participants + //Create a simulation setup with 2 participants SetupFromParticipantList({"EthernetReader", "EthernetWriter"}); const EthernetMac writerMac{00, 22, 33, 44, 55, 66}; const EthernetMac readerMac{00, 88, 99, 00, 11, 22}; - const EthernetEtherType etherType{ 0x0800 }; + const EthernetEtherType etherType{0x0800}; //Test Data - auto frameData = CreateEthernetFrameFromString(readerMac, writerMac, etherType, - "Hello World! We need a minimum size of 64 bytes for the frame so here is some useless data"); + auto frameData = CreateEthernetFrameFromString( + readerMac, writerMac, etherType, + "Hello World! We need a minimum size of 64 bytes for the frame so here is some useless data"); auto frame = SilKit::Services::Ethernet::EthernetFrame{frameData}; //Test Results @@ -97,55 +98,53 @@ TEST_F(ITest_EthernetDemo, ethernet_demo) }); ethernetController->AddBitrateChangeHandler([&](auto, Ethernet::EthernetBitrateChangeEvent bitrateChangeEvent) { - linkBitrate = bitrateChangeEvent.bitrate; + linkBitrate = bitrateChangeEvent.bitrate; }); ethernetController->AddFrameHandler( [&writerReceivedRxCount](auto, const SilKit::Services::Ethernet::EthernetFrameEvent& event) { - ASSERT_EQ(event.direction, TransmitDirection::RX); - ASSERT_EQ(event.userContext, nullptr); - writerReceivedRxCount++; - }, - static_cast(SilKit::Services::TransmitDirection::RX)); + ASSERT_EQ(event.direction, TransmitDirection::RX); + ASSERT_EQ(event.userContext, nullptr); + writerReceivedRxCount++; + }, static_cast(SilKit::Services::TransmitDirection::RX)); ethernetController->AddFrameHandler( [&writerReceivedTxCount](auto, const SilKit::Services::Ethernet::EthernetFrameEvent& event) { - ASSERT_EQ(event.direction, TransmitDirection::TX); - ASSERT_EQ(event.userContext, reinterpret_cast(sendFrameUserContext)); - writerReceivedTxCount++; - }, - static_cast(SilKit::Services::TransmitDirection::TX)); + ASSERT_EQ(event.direction, TransmitDirection::TX); + ASSERT_EQ(event.userContext, reinterpret_cast(sendFrameUserContext)); + writerReceivedTxCount++; + }, static_cast(SilKit::Services::TransmitDirection::TX)); ethernetController->AddStateChangeHandler([&](auto, Ethernet::EthernetStateChangeEvent stateChangeEvent) { - if (stateChangeEvent.state == Ethernet::EthernetState::LinkDown) - { - receivedLinkDown = true; - } - if (stateChangeEvent.state == Ethernet::EthernetState::LinkUp) - { - receivedLinkUp = true; - } + if (stateChangeEvent.state == Ethernet::EthernetState::LinkDown) + { + receivedLinkDown = true; + } + if (stateChangeEvent.state == Ethernet::EthernetState::LinkUp) + { + receivedLinkUp = true; + } }); ethernetController->AddFrameTransmitHandler([&](auto, auto ack) { - if (ack.status == Ethernet::EthernetTransmitStatus::Transmitted) - { - receivedAckTransmitted = true; - } - if (ack.status == Ethernet::EthernetTransmitStatus::Dropped) - { - receivedAckDropped = true; - } + if (ack.status == Ethernet::EthernetTransmitStatus::Transmitted) + { + receivedAckTransmitted = true; + } + if (ack.status == Ethernet::EthernetTransmitStatus::Dropped) + { + receivedAckDropped = true; + } }); timeSyncService->SetSimulationStepHandler( - [ethernetController, &sendCount, &frame](auto now, std::chrono::nanoseconds /*duration*/) { + [ethernetController, &sendCount, &frame](auto now, std::chrono::nanoseconds /*duration*/) { // Send while link is down if (now == 10ms) { - Log() << "--- EthernetWriter sending EthernetFrame which should cause LinkDown status"; - ethernetController->SendFrame(frame, reinterpret_cast(sendFrameUserContext)); + Log() << "--- EthernetWriter sending EthernetFrame which should cause LinkDown status"; + ethernetController->SendFrame(frame, reinterpret_cast(sendFrameUserContext)); } //give the Ethernet link some time to get into the 'UP' state @@ -153,16 +152,16 @@ TEST_F(ITest_EthernetDemo, ethernet_demo) //Cause a queue overflow by sending too fast if (now == 51ms) { - for (auto i = 0; i < 33;i++) // keep this in sync with EthernetController mTxQueueLimit - { - ethernetController->SendFrame(frame, reinterpret_cast(sendFrameUserContext)); - } + for (auto i = 0; i < 33; i++) // keep this in sync with EthernetController mTxQueueLimit + { + ethernetController->SendFrame(frame, reinterpret_cast(sendFrameUserContext)); + } } // Send controlled number of messages - if (now > 55ms && (sendCount++ <= 10)) + if (now > 55ms && (sendCount++ <= 10)) { - Log() << "--- EthernetWriter sending EthernetFrame"; - ethernetController->SendFrame(frame, reinterpret_cast(sendFrameUserContext)); + Log() << "--- EthernetWriter sending EthernetFrame"; + ethernetController->SendFrame(frame, reinterpret_cast(sendFrameUserContext)); } }, 1ms); } @@ -178,7 +177,7 @@ TEST_F(ITest_EthernetDemo, ethernet_demo) auto&& ethernetController = participant->CreateEthernetController("EthernetController2", "ETH1"); timeSyncService->SetSimulationStepHandler([&](auto now, std::chrono::nanoseconds /*duration*/) { - readerTime = std::chrono::duration_cast(now); + readerTime = std::chrono::duration_cast(now); }, 1ms); lifecycleService->SetCommunicationReadyHandler([ethernetController]() { @@ -189,31 +188,30 @@ TEST_F(ITest_EthernetDemo, ethernet_demo) ethernetController->AddFrameHandler( [&readerTime, &receivedMessage, &frame, &readerReceivedRxCount, lifecycleService]( auto, const SilKit::Services::Ethernet::EthernetFrameEvent& event) { - ASSERT_EQ(event.direction, TransmitDirection::RX); + ASSERT_EQ(event.direction, TransmitDirection::RX); - if (readerTime < 55ms) - { - // ignore the messages from the Queue-overflow attempt and LinkUp - return; - } + if (readerTime < 55ms) + { + // ignore the messages from the Queue-overflow attempt and LinkUp + return; + } - ASSERT_EQ(event.userContext, nullptr); - ASSERT_TRUE(SilKit::Util::ItemsAreEqual(frame.raw, event.frame.raw)); - if (readerReceivedRxCount++ == 10) - { - receivedMessage = true; - lifecycleService->Stop("Test done"); - Log() << "--- EthernetReader: Sending Stop "; - } - }, + ASSERT_EQ(event.userContext, nullptr); + ASSERT_TRUE(SilKit::Util::ItemsAreEqual(frame.raw, event.frame.raw)); + if (readerReceivedRxCount++ == 10) + { + receivedMessage = true; + lifecycleService->Stop("Test done"); + Log() << "--- EthernetReader: Sending Stop "; + } + }, static_cast(SilKit::Services::TransmitDirection::RX)); ethernetController->AddFrameHandler( [&readerReceivedTxCount](auto, const SilKit::Services::Ethernet::EthernetFrameEvent& event) { - ASSERT_EQ(event.direction, TransmitDirection::TX); - readerReceivedTxCount++; - }, - static_cast(SilKit::Services::TransmitDirection::TX)); + ASSERT_EQ(event.direction, TransmitDirection::TX); + readerReceivedTxCount++; + }, static_cast(SilKit::Services::TransmitDirection::TX)); } diff --git a/SilKit/IntegrationTests/ITest_Internals_DataPubSub.cpp b/SilKit/IntegrationTests/ITest_Internals_DataPubSub.cpp index fb66503f4..157935a55 100644 --- a/SilKit/IntegrationTests/ITest_Internals_DataPubSub.cpp +++ b/SilKit/IntegrationTests/ITest_Internals_DataPubSub.cpp @@ -40,8 +40,8 @@ TEST_F(ITest_Internals_DataPubSub, test_1pub_1sub_sync) const uint32_t numMsgToReceive = numMsgToPublish; std::vector pubsubs; - pubsubs.push_back({ "Pub1", {{ "PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}}, {} }); - pubsubs.push_back({ "Sub1", {}, {{"SubCtrl1", "TopicA", {"A"}, {}, defaultMsgSize, numMsgToReceive, 1 }} }); + pubsubs.push_back({"Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}}, {}}); + pubsubs.push_back({"Sub1", {}, {{"SubCtrl1", "TopicA", {"A"}, {}, defaultMsgSize, numMsgToReceive, 1}}}); RunSyncTest(pubsubs); } @@ -115,25 +115,47 @@ ParticipantName: PubSub2 auto configPubSub2 = SilKit::Config::ParticipantConfigurationFromStringImpl(configStringPubSub2); std::vector pubsubs; - pubsubs.push_back({ - "PubSub1", - { - {"PubCtrl1", "ShouldBeOverwritten", "A", {}, 0, defaultMsgSize, numMsgToPublish}, // Publishes for PubSub2->SubCtrl1 - {"PubCtrl2", "TopicC", "A", {}, 0, defaultMsgSize, numMsgToPublish} // Has no topic configured. - }, - {{"SubCtrl1", "ShouldBeOverwritten", "A", {}, defaultMsgSize, numMsgToReceive, 6}}, // Receives by PubSub2->PubCtrl1 - configPubSub1 - }); - - pubsubs.push_back({ - "PubSub2", - {{"PubCtrl1", "ShouldBeOverwritten", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}}, // Publishes for PubSub1->SubCtrl1 + pubsubs.push_back( + {"PubSub1", + { + {"PubCtrl1", + "ShouldBeOverwritten", + "A", + {}, + 0, + defaultMsgSize, + numMsgToPublish}, // Publishes for PubSub2->SubCtrl1 + {"PubCtrl2", "TopicC", "A", {}, 0, defaultMsgSize, numMsgToPublish} // Has no topic configured. + }, + {{"SubCtrl1", + "ShouldBeOverwritten", + "A", + {}, + defaultMsgSize, + numMsgToReceive, + 6}}, // Receives by PubSub2->PubCtrl1 + configPubSub1}); + + pubsubs.push_back( + {"PubSub2", + {{"PubCtrl1", + "ShouldBeOverwritten", + {"A"}, + {}, + 0, + defaultMsgSize, + numMsgToPublish}}, // Publishes for PubSub1->SubCtrl1 { - {"SubCtrl1", "ShouldBeOverwritten", {"A"}, {}, defaultMsgSize, numMsgToReceive, 6}, // Receives by PubSub1->PubCtrl1 + {"SubCtrl1", + "ShouldBeOverwritten", + {"A"}, + {}, + defaultMsgSize, + numMsgToReceive, + 6}, // Receives by PubSub1->PubCtrl1 {"SubCtrl2", "TopicC", {"A"}, {}, defaultMsgSize, numMsgToReceive, 6}, // Has no topic configured. }, - configPubSub2 - }); + configPubSub2}); RunSyncTest(pubsubs); } @@ -143,11 +165,11 @@ TEST_F(ITest_Internals_DataPubSub, test_1pub_1sub_sync_largemsg) { const uint32_t numMsgToPublish = defaultNumMsgToPublish; const uint32_t numMsgToReceive = numMsgToPublish; - const size_t messageSize = 250000; + const size_t messageSize = 250000; std::vector pubsubs; - pubsubs.push_back({ "Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, messageSize, numMsgToPublish}}, {} }); - pubsubs.push_back({ "Sub1", {}, {{"SubCtrl1", "TopicA", {"A"}, {}, messageSize, numMsgToReceive, 1}} }); + pubsubs.push_back({"Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, messageSize, numMsgToPublish}}, {}}); + pubsubs.push_back({"Sub1", {}, {{"SubCtrl1", "TopicA", {"A"}, {}, messageSize, numMsgToReceive, 1}}}); RunSyncTest(pubsubs); } @@ -157,19 +179,19 @@ TEST_F(ITest_Internals_DataPubSub, test_1pub_1sub_sync_100topics) { const uint32_t numMsgToPublish = 1; const uint32_t numMsgToReceive = numMsgToPublish; - const int numTopics = 100; + const int numTopics = 100; std::vector pubsubs; - - pubsubs.push_back({ "Pub1" }); - pubsubs.push_back({ "Sub1" }); + + pubsubs.push_back({"Pub1"}); + pubsubs.push_back({"Sub1"}); for (int i = 0; i < numTopics; i++) { std::string topic = std::to_string(i); std::string pubControllerName = "PubCtrl" + std::to_string(i); std::string subControllerName = "SubCtrl" + std::to_string(i); - DataPublisherInfo pInfo{ pubControllerName, topic, {"A"}, {}, 1, defaultMsgSize, numMsgToPublish }; - DataSubscriberInfo sInfo{ subControllerName, topic, {"A"}, {}, defaultMsgSize, numMsgToReceive, 1}; + DataPublisherInfo pInfo{pubControllerName, topic, {"A"}, {}, 1, defaultMsgSize, numMsgToPublish}; + DataSubscriberInfo sInfo{subControllerName, topic, {"A"}, {}, defaultMsgSize, numMsgToReceive, 1}; pubsubs[0].dataPublishers.push_back(std::move(pInfo)); pubsubs[1].dataSubscribers.push_back(std::move(sInfo)); } @@ -184,9 +206,9 @@ TEST_F(ITest_Internals_DataPubSub, test_1pub_2sub_sync) const uint32_t numMsgToReceive = numMsgToPublish; std::vector pubsubs; - pubsubs.push_back({"Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}},{}}); - pubsubs.push_back({"Sub1", {}, {{"SubCtrl1", "TopicA", {"A"}, {}, defaultMsgSize, numMsgToReceive, 1}}}); - pubsubs.push_back({"Sub2", {}, {{"SubCtrl1", "TopicA", {"A"}, {}, defaultMsgSize, numMsgToReceive, 1}}}); + pubsubs.push_back({"Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}}, {}}); + pubsubs.push_back({"Sub1", {}, {{"SubCtrl1", "TopicA", {"A"}, {}, defaultMsgSize, numMsgToReceive, 1}}}); + pubsubs.push_back({"Sub2", {}, {{"SubCtrl1", "TopicA", {"A"}, {}, defaultMsgSize, numMsgToReceive, 1}}}); RunSyncTest(pubsubs); } @@ -198,11 +220,11 @@ TEST_F(ITest_Internals_DataPubSub, test_2pub_1sub_sync) const uint32_t numMsgToReceive = numMsgToPublish * 2; // PubCtrl1 and PubCtrl2 have the same Topic, mediatype and labels, // so only one call of the newSourceDiscoveryHandler is expected - const uint32_t numNewSouceDiscoveries = 1; + const uint32_t numNewSouceDiscoveries = 1; std::vector pubsubs; - pubsubs.push_back({"Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}}, {}}); - pubsubs.push_back({"Pub2", {{"PubCtrl2", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}}, {}}); + pubsubs.push_back({"Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}}, {}}); + pubsubs.push_back({"Pub2", {{"PubCtrl2", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}}, {}}); std::vector> expectedDataUnordered; for (uint8_t d = 0; d < numMsgToPublish; d++) { @@ -274,13 +296,22 @@ TEST_F(ITest_Internals_DataPubSub, test_3pub_4sub_sync_4topics) const uint32_t numMsgToReceive = numMsgToPublish; // PubCtrl1 on Pub1,2,3 have the same Topic, mediatype and labels, // so only one call of the newSourceDiscoveryHandler is expected - const uint32_t numNewSouceDiscoveries = 1; + const uint32_t numNewSouceDiscoveries = 1; std::vector pubsubs; - - pubsubs.push_back({ "Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}, {"PubCtrl2", "TopicB", "B", {}, 0, defaultMsgSize, numMsgToPublish}}, {} }); - pubsubs.push_back({ "Pub2", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}, {"PubCtrl2", "TopicC", "C", {}, 0, defaultMsgSize, numMsgToPublish}}, {} }); - pubsubs.push_back({ "Pub3", {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}, {"PubCtrl2", "TopicD", "D", {}, 0, defaultMsgSize, numMsgToPublish}}, {}}); + + pubsubs.push_back({"Pub1", + {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}, + {"PubCtrl2", "TopicB", "B", {}, 0, defaultMsgSize, numMsgToPublish}}, + {}}); + pubsubs.push_back({"Pub2", + {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}, + {"PubCtrl2", "TopicC", "C", {}, 0, defaultMsgSize, numMsgToPublish}}, + {}}); + pubsubs.push_back({"Pub3", + {{"PubCtrl1", "TopicA", {"A"}, {}, 0, defaultMsgSize, numMsgToPublish}, + {"PubCtrl2", "TopicD", "D", {}, 0, defaultMsgSize, numMsgToPublish}}, + {}}); std::vector> expectedDataUnordered; for (uint8_t d = 0; d < numMsgToPublish; d++) @@ -601,7 +632,7 @@ TEST_F(ITest_Internals_DataPubSub, test_1pub_1sub_sync_missing_mandatory_label_s } //-------------------- -// Self-delivery +// Self-delivery // 1 pub, 1 sub on a single participant TEST_F(ITest_Internals_DataPubSub, test_1_participant_selfdelivery) @@ -624,7 +655,7 @@ TEST_F(ITest_Internals_DataPubSub, test_1_participant_selfdelivery_same_topic) const uint32_t numMsgToReceive = numMsgToPublish; // PubCtrl1 and PubCtrl2 have the same Topic, mediatype and labels, // so only one call of the newSourceDiscoveryHandler is expected - const uint32_t numNewSouceDiscoveries = 1; + const uint32_t numNewSouceDiscoveries = 1; std::vector pubsubs; std::vector> expectedDataUnordered; @@ -643,8 +674,7 @@ TEST_F(ITest_Internals_DataPubSub, test_1_participant_selfdelivery_same_topic) defaultMsgSize, numMsgToReceive, numNewSouceDiscoveries, - expectedDataUnordered - }, + expectedDataUnordered}, {"SubCtrl2", "TopicA", {"A"}, @@ -652,8 +682,7 @@ TEST_F(ITest_Internals_DataPubSub, test_1_participant_selfdelivery_same_topic) defaultMsgSize, numMsgToReceive, numNewSouceDiscoveries, - expectedDataUnordered - }}}); + expectedDataUnordered}}}); RunSyncTest(pubsubs); } @@ -683,7 +712,7 @@ TEST_F(ITest_Internals_DataPubSub, test_1pub_1sub_async_rejoin) const uint32_t numMsgToPublish = 1; const uint32_t numRejoins = 10; const uint32_t numMsgToReceive = 1 * numMsgToPublish; - + std::vector publishers; publishers.push_back({"Pub1", {{"PubCtrl1", "TopicA", {"A"}, {}, 1, defaultMsgSize, numMsgToPublish}}, {}}); @@ -697,16 +726,17 @@ TEST_F(ITest_Internals_DataPubSub, test_1pub_1sub_async_rejoin) } subscribers.push_back({"Sub1", {}, - {{"SubCtrl1", - "TopicA", - {"A"}, - {}, - defaultMsgSize, - numMsgToReceive, - 1, - expectedDataUnordered, - }}}); - + {{ + "SubCtrl1", + "TopicA", + {"A"}, + {}, + defaultMsgSize, + numMsgToReceive, + 1, + expectedDataUnordered, + }}}); + auto registryUri = MakeTestRegistryUri(); _testSystem.SetupRegistryAndSystemMaster(registryUri, false, {}); diff --git a/SilKit/IntegrationTests/ITest_Internals_DataPubSub.hpp b/SilKit/IntegrationTests/ITest_Internals_DataPubSub.hpp index 9a8b0deff..590bedc0a 100644 --- a/SilKit/IntegrationTests/ITest_Internals_DataPubSub.hpp +++ b/SilKit/IntegrationTests/ITest_Internals_DataPubSub.hpp @@ -49,7 +49,8 @@ class ITest_Internals_DataPubSub : public testing::Test struct DataPublisherInfo { - DataPublisherInfo(const std::string& newControllerName, const std::string& newTopic, const std::string& newMediaType, + DataPublisherInfo(const std::string& newControllerName, const std::string& newTopic, + const std::string& newMediaType, const std::vector& newLabels, uint8_t newHistory, size_t newMessageSizeInBytes, uint32_t newNumMsgToPublish) { @@ -90,9 +91,9 @@ class ITest_Internals_DataPubSub : public testing::Test struct DataSubscriberInfo { - DataSubscriberInfo(const std::string& newControllerName, const std::string& newTopic, const std::string& newMediaType, - const std::vector& newLabels, - size_t newMessageSizeInBytes, + DataSubscriberInfo(const std::string& newControllerName, const std::string& newTopic, + const std::string& newMediaType, + const std::vector& newLabels, size_t newMessageSizeInBytes, uint32_t newNumMsgToReceive, uint32_t newExpectedSources) { expectIncreasingData = true; @@ -104,8 +105,9 @@ class ITest_Internals_DataPubSub : public testing::Test numMsgToReceive = newNumMsgToReceive; expectedSources = newExpectedSources; } - DataSubscriberInfo(const std::string& newControllerName, const std::string& newTopic, const std::string& newMediaType, const std::vector& newLabels, - size_t newMessageSizeInBytes, + DataSubscriberInfo(const std::string& newControllerName, const std::string& newTopic, + const std::string& newMediaType, + const std::vector& newLabels, size_t newMessageSizeInBytes, uint32_t newNumMsgToReceive, uint32_t newExpectedSources, const std::vector>& newExpectedDataUnordered) { @@ -150,8 +152,8 @@ class ITest_Internals_DataPubSub : public testing::Test { auto foundDataIter = std::find_if(expectedDataUnordered.begin(), expectedDataUnordered.end(), [&dataMessageEvent](const auto& expectedData) -> bool { - return SilKit::Util::ItemsAreEqual(SilKit::Util::ToSpan(expectedData), dataMessageEvent.data); - }); + return SilKit::Util::ItemsAreEqual(SilKit::Util::ToSpan(expectedData), dataMessageEvent.data); + }); EXPECT_EQ(foundDataIter != expectedDataUnordered.end(), true); if (foundDataIter != expectedDataUnordered.end()) { @@ -167,7 +169,8 @@ class ITest_Internals_DataPubSub : public testing::Test } } - void OnNewServiceDiscovery(const SilKit::Core::ServiceDescriptor /*sd*/) { + void OnNewServiceDiscovery(const SilKit::Core::ServiceDescriptor /*sd*/) + { newSourceCounter++; if (!allDiscovered) { @@ -181,7 +184,10 @@ class ITest_Internals_DataPubSub : public testing::Test struct PubSubParticipant { - PubSubParticipant(const std::string& newName) { name = newName; } + PubSubParticipant(const std::string& newName) + { + name = newName; + } PubSubParticipant(const std::string& newName, const std::vector& newDataPublishers, const std::vector& newDataSubscribers, std::shared_ptr newConfig = @@ -217,9 +223,8 @@ class ITest_Internals_DataPubSub : public testing::Test void PrepareAllReceivedPromise() { - if (std::all_of(dataSubscribers.begin(), dataSubscribers.end(), [](const auto& dsInfo) { - return dsInfo.numMsgToReceive == 0; - })) + if (std::all_of(dataSubscribers.begin(), dataSubscribers.end(), + [](const auto& dsInfo) { return dsInfo.numMsgToReceive == 0; })) { allReceived = true; allReceivedPromise.set_value(); @@ -227,9 +232,8 @@ class ITest_Internals_DataPubSub : public testing::Test } void PrepareAllDiscoveredPromise() { - if (std::all_of(dataSubscribers.begin(), dataSubscribers.end(), [](const auto& dsInfo) { - return dsInfo.expectedSources == 0; - })) + if (std::all_of(dataSubscribers.begin(), dataSubscribers.end(), + [](const auto& dsInfo) { return dsInfo.expectedSources == 0; })) { allDiscovered = true; allDiscoveredPromise.set_value(); @@ -239,8 +243,8 @@ class ITest_Internals_DataPubSub : public testing::Test void CheckAllReceivedPromise() { if (!allReceived && std::all_of(dataSubscribers.begin(), dataSubscribers.end(), [](const auto& dsInfo) { - return dsInfo.allReceived; - })) + return dsInfo.allReceived; + })) { allReceived = true; allReceivedPromise.set_value(); @@ -249,8 +253,8 @@ class ITest_Internals_DataPubSub : public testing::Test void CheckAllDiscoveredPromise() { if (!allDiscovered && std::all_of(dataSubscribers.begin(), dataSubscribers.end(), [](const auto& dsInfo) { - return dsInfo.allDiscovered; - })) + return dsInfo.allDiscovered; + })) { allDiscovered = true; allDiscoveredPromise.set_value(); @@ -258,9 +262,8 @@ class ITest_Internals_DataPubSub : public testing::Test } void CheckAllSentPromise() { - if (!allSent && std::all_of(dataPublishers.begin(), dataPublishers.end(), [](const auto& dp) { - return dp.allSent; - })) + if (!allSent + && std::all_of(dataPublishers.begin(), dataPublishers.end(), [](const auto& dp) { return dp.allSent; })) { allSent = true; allSentPromise.set_value(); @@ -270,7 +273,8 @@ class ITest_Internals_DataPubSub : public testing::Test void WaitForCreateParticipant() { auto futureStatus = participantCreatedPromise.get_future().wait_for(communicationTimeout); - EXPECT_EQ(futureStatus, std::future_status::ready) << "Test Failure: Awaiting participant creation timed out"; + EXPECT_EQ(futureStatus, std::future_status::ready) + << "Test Failure: Awaiting participant creation timed out"; } void WaitForAllSent() { @@ -315,14 +319,14 @@ class ITest_Internals_DataPubSub : public testing::Test participant.participantImpl->GetServiceDiscovery()->RegisterServiceDiscoveryHandler( [&ds, &participant](auto type, auto&& serviceDescr) { - if (type == SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated) + if (type == SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated) + { + if (serviceDescr.GetNetworkType() == SilKit::Config::NetworkType::Data) { - if (serviceDescr.GetNetworkType() == SilKit::Config::NetworkType::Data) - { - ds.OnNewServiceDiscovery(serviceDescr); - participant.CheckAllDiscoveredPromise(); - } + ds.OnNewServiceDiscovery(serviceDescr); + participant.CheckAllDiscoveredPromise(); } + } }); SilKit::Services::PubSub::PubSubSpec dataSpec{ds.topic, ds.mediaType}; @@ -332,16 +336,16 @@ class ITest_Internals_DataPubSub : public testing::Test } // Create DataSubscriber with default handler - if(participant.delayedDefaultDataHandler) + if (participant.delayedDefaultDataHandler) { - ds.dataSubscriber = participant.participant->CreateDataSubscriber( - ds.controllerName, dataSpec, nullptr); + ds.dataSubscriber = + participant.participant->CreateDataSubscriber(ds.controllerName, dataSpec, nullptr); ds.dataSubscriber->SetDataMessageHandler(receptionHandler); } else { - ds.dataSubscriber = participant.participant->CreateDataSubscriber( - ds.controllerName, dataSpec, receptionHandler); + ds.dataSubscriber = + participant.participant->CreateDataSubscriber(ds.controllerName, dataSpec, receptionHandler); } } @@ -353,7 +357,8 @@ class ITest_Internals_DataPubSub : public testing::Test { dataSpec.AddLabel(label); } - dp.dataPublisher = participant.participant->CreateDataPublisher(dp.controllerName, dataSpec, dp.history); + dp.dataPublisher = + participant.participant->CreateDataPublisher(dp.controllerName, dataSpec, dp.history); } auto publishTask = [&participant]() { for (auto& dp : participant.dataPublishers) @@ -371,12 +376,12 @@ class ITest_Internals_DataPubSub : public testing::Test timeSyncService->SetSimulationStepHandler( [&participant, publishTask](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) { - if (!participant.dataPublishers.empty()) - { - publishTask(); - participant.CheckAllSentPromise(); - } - }, + if (!participant.dataPublishers.empty()) + { + publishTask(); + participant.CheckAllSentPromise(); + } + }, 1s); auto finalStateFuture = lifecycleService->StartLifecycle(); finalStateFuture.get(); @@ -386,9 +391,7 @@ class ITest_Internals_DataPubSub : public testing::Test if (!participant.dataPublishers.empty()) { while (std::none_of(participant.dataPublishers.begin(), participant.dataPublishers.end(), - [](const DataPublisherInfo& dp) { - return dp.allSent; - })) + [](const DataPublisherInfo& dp) { return dp.allSent; })) { publishTask(); } diff --git a/SilKit/IntegrationTests/ITest_Internals_ParticipantModes.cpp b/SilKit/IntegrationTests/ITest_Internals_ParticipantModes.cpp index 356706bdf..8a46fbe07 100644 --- a/SilKit/IntegrationTests/ITest_Internals_ParticipantModes.cpp +++ b/SilKit/IntegrationTests/ITest_Internals_ParticipantModes.cpp @@ -197,31 +197,31 @@ class ITest_Internals_ParticipantModes : public testing::Test participantInternal->GetSystemController(); auto systemMonitor = participant->CreateSystemMonitor(); - systemMonitor->AddParticipantStatusHandler( - [&testParticipant, systemController, logger, this](const Services::Orchestration::ParticipantStatus& status) { - if (status.participantName == testParticipant.name) + systemMonitor->AddParticipantStatusHandler([&testParticipant, systemController, logger, + this](const Services::Orchestration::ParticipantStatus& status) { + if (status.participantName == testParticipant.name) + { + if (status.state == ParticipantState::Error && !testParticipant.i.errorStateReached) { - if (status.state == ParticipantState::Error && !testParticipant.i.errorStateReached) - { - testParticipant.i.errorStateReached = true; - testParticipant.errorStatePromise.set_value(); - - if (logging) - { - std::stringstream ss; - ss << "AbortSimulation due to ErrorState of participant \'" << testParticipant.name << "\'"; - logger->Info(ss.str()); - } - - systemController->AbortSimulation(); - } - else if (status.state == ParticipantState::Running && !testParticipant.i.runningStateReached) + testParticipant.i.errorStateReached = true; + testParticipant.errorStatePromise.set_value(); + + if (logging) { - testParticipant.i.runningStateReached = true; - testParticipant.runningStatePromise.set_value(); + std::stringstream ss; + ss << "AbortSimulation due to ErrorState of participant \'" << testParticipant.name << "\'"; + logger->Info(ss.str()); } + + systemController->AbortSimulation(); } - }); + else if (status.state == ParticipantState::Running && !testParticipant.i.runningStateReached) + { + testParticipant.i.runningStateReached = true; + testParticipant.runningStatePromise.set_value(); + } + } + }); ITimeSyncService* timeSyncService{}; @@ -237,40 +237,40 @@ class ITest_Internals_ParticipantModes : public testing::Test participant->CreateDataSubscriber( "TestSubscriber", matchingDataSpec, [&testParticipant](IDataSubscriber* /*subscriber*/, const DataMessageEvent& dataMessageEvent) { - if (!testParticipant.i.allReceived) + if (!testParticipant.i.allReceived) + { + auto participantId = dataMessageEvent.data[0]; + if (participantId != testParticipant.id) { - auto participantId = dataMessageEvent.data[0]; - if (participantId != testParticipant.id) + testParticipant.receivedIds.insert(dataMessageEvent.data[0]); + // No self delivery: Expect expectedReceptions-1 receptions + if (testParticipant.receivedIds.size() == expectedReceptions - 1) { - testParticipant.receivedIds.insert(dataMessageEvent.data[0]); - // No self delivery: Expect expectedReceptions-1 receptions - if (testParticipant.receivedIds.size() == expectedReceptions - 1) - { - testParticipant.i.allReceived = true; - testParticipant.allReceivedPromise.set_value(); - } + testParticipant.i.allReceived = true; + testParticipant.allReceivedPromise.set_value(); } } - }); + } + }); timeSyncService->SetSimulationStepHandler( [lifecycleService, logger, &testParticipant, publisher, this](std::chrono::nanoseconds now, - std::chrono::nanoseconds /*duration*/) { - publisher->Publish(std::vector{testParticipant.id}); - std::stringstream ss; - ss << "now=" << now.count() / 1e9 << "s"; - logger->Info(ss.str()); - if (!testParticipant.simtimePassed && now > simtimeToPass) - { - testParticipant.simtimePassed = true; - testParticipant.simtimePassedPromise.set_value(); - } - if (testParticipant.i.stopRequested) - { - testParticipant.i.stopRequested = false; - lifecycleService->Stop("End Test"); - } - }, + std::chrono::nanoseconds /*duration*/) { + publisher->Publish(std::vector{testParticipant.id}); + std::stringstream ss; + ss << "now=" << now.count() / 1e9 << "s"; + logger->Info(ss.str()); + if (!testParticipant.simtimePassed && now > simtimeToPass) + { + testParticipant.simtimePassed = true; + testParticipant.simtimePassedPromise.set_value(); + } + if (testParticipant.i.stopRequested) + { + testParticipant.i.stopRequested = false; + lifecycleService->Stop("End Test"); + } + }, 1s); if (testParticipant.lifeCycleOperationMode != OperationMode::Invalid) @@ -278,7 +278,6 @@ class ITest_Internals_ParticipantModes : public testing::Test auto finalStateFuture = lifecycleService->StartLifecycle(); finalStateFuture.get(); } - } void AsyncParticipantThread(TestParticipant& testParticipant) @@ -307,32 +306,32 @@ class ITest_Internals_ParticipantModes : public testing::Test Experimental::Services::Orchestration::ISystemController* systemController = participantInternal->GetSystemController(); auto systemMonitor = participant->CreateSystemMonitor(); - systemMonitor->AddParticipantStatusHandler( - [&testParticipant, systemController, logger, this](const Services::Orchestration::ParticipantStatus& status) { - if (status.participantName == testParticipant.name) + systemMonitor->AddParticipantStatusHandler([&testParticipant, systemController, logger, + this](const Services::Orchestration::ParticipantStatus& status) { + if (status.participantName == testParticipant.name) + { + if (status.state == ParticipantState::Error && !testParticipant.i.errorStateReached) { - if (status.state == ParticipantState::Error && !testParticipant.i.errorStateReached) - { - // We also set the runningStatePromise to skip waiting for this - testParticipant.runningStatePromise.set_value(); - - testParticipant.i.errorStateReached = true; - testParticipant.errorStatePromise.set_value(); - if (logging) - { - std::stringstream ss; - ss << "AbortSimulation due to ErrorState of participant \'" << testParticipant.name << "\'"; - logger->Info(ss.str()); - } - systemController->AbortSimulation(); - } - else if (status.state == ParticipantState::Running && !testParticipant.i.runningStateReached) + // We also set the runningStatePromise to skip waiting for this + testParticipant.runningStatePromise.set_value(); + + testParticipant.i.errorStateReached = true; + testParticipant.errorStatePromise.set_value(); + if (logging) { - testParticipant.i.runningStateReached = true; - testParticipant.runningStatePromise.set_value(); + std::stringstream ss; + ss << "AbortSimulation due to ErrorState of participant \'" << testParticipant.name << "\'"; + logger->Info(ss.str()); } + systemController->AbortSimulation(); } - }); + else if (status.state == ParticipantState::Running && !testParticipant.i.runningStateReached) + { + testParticipant.i.runningStateReached = true; + testParticipant.runningStatePromise.set_value(); + } + } + }); SilKit::Services::PubSub::PubSubSpec dataSpec{topic, mediaType}; SilKit::Services::PubSub::PubSubSpec matchingDataSpec{topic, mediaType}; @@ -340,21 +339,21 @@ class ITest_Internals_ParticipantModes : public testing::Test participant->CreateDataSubscriber( "TestSubscriber", matchingDataSpec, [&testParticipant](IDataSubscriber* /*subscriber*/, const DataMessageEvent& dataMessageEvent) { - if (!testParticipant.i.allReceived) + if (!testParticipant.i.allReceived) + { + auto participantId = dataMessageEvent.data[0]; + if (participantId != testParticipant.id) { - auto participantId = dataMessageEvent.data[0]; - if (participantId != testParticipant.id) + testParticipant.receivedIds.insert(dataMessageEvent.data[0]); + // No self delivery: Expect expectedReceptions-1 receptions + if (testParticipant.receivedIds.size() == expectedReceptions - 1) { - testParticipant.receivedIds.insert(dataMessageEvent.data[0]); - // No self delivery: Expect expectedReceptions-1 receptions - if (testParticipant.receivedIds.size() == expectedReceptions - 1) - { - testParticipant.i.allReceived = true; - testParticipant.allReceivedPromise.set_value(); - } + testParticipant.i.allReceived = true; + testParticipant.allReceivedPromise.set_value(); } } - }); + } + }); auto runTask = [&testParticipant, publisher]() { while (!testParticipant.i.stopRequested) @@ -387,7 +386,7 @@ class ITest_Internals_ParticipantModes : public testing::Test // Wait for task to have received a stop request auto simTaskFinishedFuture = testParticipant.simTaskFinishedPromise.get_future(); simTaskFinishedFuture.get(); - + // Stop the lifecycle lifecycleService->Stop("End Test"); @@ -402,7 +401,6 @@ class ITest_Internals_ParticipantModes : public testing::Test { runTask(); } - } void SystemControllerParticipantThread(const std::vector& required) @@ -459,9 +457,11 @@ class ITest_Internals_ParticipantModes : public testing::Test systemController->AbortSimulation(); break; - case SystemState::Running: break; + case SystemState::Running: + break; - default: break; + default: + break; } }); @@ -478,7 +478,7 @@ class ITest_Internals_ParticipantModes : public testing::Test { std::this_thread::sleep_for(1ms); } - + if (logging) { logger->Info("AbortSimulation requested"); @@ -509,9 +509,8 @@ class ITest_Internals_ParticipantModes : public testing::Test } required.push_back(systemControllerParticipantName); - participantThread_SystemController = ParticipantThread{[this, required] { - SystemControllerParticipantThread(required); - }}; + participantThread_SystemController = + ParticipantThread{[this, required] { SystemControllerParticipantThread(required); }}; } } @@ -533,7 +532,10 @@ class ITest_Internals_ParticipantModes : public testing::Test registry->StartListening(registryUri); } - void StopRegistry() { registry.reset(); } + void StopRegistry() + { + registry.reset(); + } void RunParticipants(std::list& participants) { @@ -543,42 +545,30 @@ class ITest_Internals_ParticipantModes : public testing::Test { if (p.lifeCycleOperationMode == OperationMode::Invalid) { - participantThreads_Async_Invalid.emplace_back([this, &p] { - AsyncParticipantThread(p); - }); + participantThreads_Async_Invalid.emplace_back([this, &p] { AsyncParticipantThread(p); }); } else if (p.lifeCycleOperationMode == OperationMode::Autonomous) { - participantThreads_Async_Autonomous.emplace_back([this, &p] { - AsyncParticipantThread(p); - }); + participantThreads_Async_Autonomous.emplace_back([this, &p] { AsyncParticipantThread(p); }); } else if (p.lifeCycleOperationMode == OperationMode::Coordinated) { - participantThreads_Async_Coordinated.emplace_back([this, &p] { - AsyncParticipantThread(p); - }); + participantThreads_Async_Coordinated.emplace_back([this, &p] { AsyncParticipantThread(p); }); } } else if (p.timeMode == TimeMode::Sync) { if (p.lifeCycleOperationMode == OperationMode::Invalid) { - participantThreads_Sync_Invalid.emplace_back([this, &p] { - SyncParticipantThread(p); - }); + participantThreads_Sync_Invalid.emplace_back([this, &p] { SyncParticipantThread(p); }); } else if (p.lifeCycleOperationMode == OperationMode::Autonomous) { - participantThreads_Sync_Autonomous.emplace_back([this, &p] { - SyncParticipantThread(p); - }); + participantThreads_Sync_Autonomous.emplace_back([this, &p] { SyncParticipantThread(p); }); } else if (p.lifeCycleOperationMode == OperationMode::Coordinated) { - participantThreads_Sync_Coordinated.emplace_back([this, &p] { - SyncParticipantThread(p); - }); + participantThreads_Sync_Coordinated.emplace_back([this, &p] { SyncParticipantThread(p); }); } } } @@ -706,7 +696,7 @@ TEST_F(ITest_Internals_ParticipantModes, test_AsyncCoordinatedNonReq_disallowed) // Participants std::list testParticipants; testParticipants.push_back({"AsyncCoordinated1", TimeMode::Async, OperationMode::Coordinated}); - + // Workflow configuration without "AsyncCoordinated1" RunSystemController({"NoSuchParticipant"}); @@ -986,7 +976,7 @@ TEST_F(ITest_Internals_ParticipantModes, test_SyncAutonomousReq) // Shutdown JoinParticipantThreads(participantThreads_Sync_Autonomous); - + AbortSystemController(); StopRegistry(); } @@ -1159,7 +1149,8 @@ TEST_F(ITest_Internals_ParticipantModes, test_Combinations) || (p2_timeMode == TimeMode::Sync && p2_operationMode == OperationMode::Autonomous && p1_timeMode == TimeMode::Sync && p1_operationMode == OperationMode::Coordinated)) { - std::cout << " -> Invalid combination (Sync+Autonomous with Sync+Coordinated), skip" << std::endl; + std::cout << " -> Invalid combination (Sync+Autonomous with Sync+Coordinated), skip" + << std::endl; continue; } diff --git a/SilKit/IntegrationTests/ITest_Internals_RequestReply.cpp b/SilKit/IntegrationTests/ITest_Internals_RequestReply.cpp index aa0674608..357fc03eb 100644 --- a/SilKit/IntegrationTests/ITest_Internals_RequestReply.cpp +++ b/SilKit/IntegrationTests/ITest_Internals_RequestReply.cpp @@ -47,10 +47,7 @@ using namespace SilKit::Core; class ITest_Internals_RequestReply : public testing::Test { protected: - ITest_Internals_RequestReply() - { - } - + ITest_Internals_RequestReply() {} }; TEST_F(ITest_Internals_RequestReply, participant_replies) @@ -62,38 +59,28 @@ TEST_F(ITest_Internals_RequestReply, participant_replies) // Create participants auto&& p1 = - SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), "P1", - registryUri); + SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), "P1", registryUri); auto&& p2 = - SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), "P2", - registryUri); + SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), "P2", registryUri); auto&& p3 = - SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), "P3", - registryUri); + SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), "P3", registryUri); auto participantReplies_p1 = dynamic_cast(p1.get())->GetParticipantRepliesProcedure(); auto participantReplies_p2 = dynamic_cast(p2.get())->GetParticipantRepliesProcedure(); auto participantReplies_p3 = dynamic_cast(p3.get())->GetParticipantRepliesProcedure(); - + std::promise receivedReplies_p1{}; - participantReplies_p1->CallAfterAllParticipantsReplied([&receivedReplies_p1]() { - receivedReplies_p1.set_value(); - }); + participantReplies_p1->CallAfterAllParticipantsReplied([&receivedReplies_p1]() { receivedReplies_p1.set_value(); }); std::promise receivedReplies_p2{}; - participantReplies_p2->CallAfterAllParticipantsReplied([&receivedReplies_p2]() { - receivedReplies_p2.set_value(); - }); + participantReplies_p2->CallAfterAllParticipantsReplied([&receivedReplies_p2]() { receivedReplies_p2.set_value(); }); std::promise receivedReplies_p3{}; - participantReplies_p3->CallAfterAllParticipantsReplied([&receivedReplies_p3]() { - receivedReplies_p3.set_value(); - }); + participantReplies_p3->CallAfterAllParticipantsReplied([&receivedReplies_p3]() { receivedReplies_p3.set_value(); }); receivedReplies_p1.get_future().wait(); receivedReplies_p2.get_future().wait(); receivedReplies_p3.get_future().wait(); - } } // anonymous namespace diff --git a/SilKit/IntegrationTests/ITest_Internals_Rpc.cpp b/SilKit/IntegrationTests/ITest_Internals_Rpc.cpp index a9d11c861..ea567fb11 100644 --- a/SilKit/IntegrationTests/ITest_Internals_Rpc.cpp +++ b/SilKit/IntegrationTests/ITest_Internals_Rpc.cpp @@ -37,7 +37,10 @@ TEST_F(ITest_Internals_Rpc, test_1client_1server_sync) const uint32_t numCallsToReturn = defaultNumCalls; std::vector rpcs; - rpcs.push_back({"Client1", {}, {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, {"TestFuncA"} }); + rpcs.push_back({"Client1", + {}, + {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, + {"TestFuncA"}}); rpcs.push_back({"Server1", {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive}}, {}, {}}); RunSyncTest(rpcs); @@ -51,13 +54,15 @@ TEST_F(ITest_Internals_Rpc, test_2_mixed_participants) const uint32_t numCallsToReturn = defaultNumCalls; std::vector rpcs; - rpcs.push_back({"Mixed1", - {{"ServerCtrl1", "TestFuncB", "A", {}, defaultMsgSize, numCallsToReceive}}, // Server - {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, {"TestFuncA","TestFuncB"}}); // Client + rpcs.push_back({"Mixed1", + {{"ServerCtrl1", "TestFuncB", "A", {}, defaultMsgSize, numCallsToReceive}}, // Server + {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, + {"TestFuncA", "TestFuncB"}}); // Client - rpcs.push_back({"Mixed2", - {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive}}, // Server - {{"ClientCtrl1", "TestFuncB", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, {"TestFuncA","TestFuncB"}}); // Client + rpcs.push_back({"Mixed2", + {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive}}, // Server + {{"ClientCtrl1", "TestFuncB", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, + {"TestFuncA", "TestFuncB"}}); // Client RunSyncTest(rpcs); } @@ -67,10 +72,13 @@ TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_largemsg) { const uint32_t numCallsToReceive = defaultNumCalls; const uint32_t numCallsToReturn = defaultNumCalls; - const size_t messageSize = 250000; + const size_t messageSize = 250000; std::vector rpcs; - rpcs.push_back({"Client1", {}, {{"ClientCtrl1", "TestFuncA", "A", {}, messageSize, defaultNumCalls, numCallsToReturn}}, {"TestFuncA"} }); + rpcs.push_back({"Client1", + {}, + {{"ClientCtrl1", "TestFuncA", "A", {}, messageSize, defaultNumCalls, numCallsToReturn}}, + {"TestFuncA"}}); rpcs.push_back({"Server1", {{"ServerCtrl1", "TestFuncA", "A", {}, messageSize, numCallsToReceive}}, {}, {}}); RunSyncTest(rpcs); @@ -89,14 +97,15 @@ TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_100functions) { expectedFunctionNames.push_back(std::to_string(i)); } - rpcs.push_back({ "Client1", {}, {}, expectedFunctionNames }); - rpcs.push_back({ "Server1", {}, {}, {} }); + rpcs.push_back({"Client1", {}, {}, expectedFunctionNames}); + rpcs.push_back({"Server1", {}, {}, {}}); for (int i = 0; i < numFunctions; i++) { std::string functionName = std::to_string(i); std::string clientControllerName = "ClientCtrl" + std::to_string(i); std::string serverControllerName = "ServerCtrl" + std::to_string(i); - rpcs[0].AddRpcClient({clientControllerName, functionName, "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}); + rpcs[0].AddRpcClient( + {clientControllerName, functionName, "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}); rpcs[1].AddRpcServer({serverControllerName, functionName, "A", {}, defaultMsgSize, numCallsToReceive}); } @@ -117,10 +126,25 @@ TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_samefunctionname) expectedReturnDataUnordered.emplace_back(std::vector(defaultMsgSize, d + rpcFuncIncrement)); } - rpcs.push_back({ "Client1", {}, - {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn, expectedReturnDataUnordered}, - {"ClientCtrl2", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn, expectedReturnDataUnordered}}, - {"TestFuncA"}}); + rpcs.push_back({"Client1", + {}, + {{"ClientCtrl1", + "TestFuncA", + "A", + {}, + defaultMsgSize, + defaultNumCalls, + numCallsToReturn, + expectedReturnDataUnordered}, + {"ClientCtrl2", + "TestFuncA", + "A", + {}, + defaultMsgSize, + defaultNumCalls, + numCallsToReturn, + expectedReturnDataUnordered}}, + {"TestFuncA"}}); std::vector> expectedDataUnordered; for (uint8_t d = 0; d < defaultNumCalls; d++) @@ -130,8 +154,10 @@ TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_samefunctionname) } rpcs.push_back({"Server1", - {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive, expectedDataUnordered}, - {"ServerCtrl2", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive, expectedDataUnordered}}, {}, {} }); + {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive, expectedDataUnordered}, + {"ServerCtrl2", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive, expectedDataUnordered}}, + {}, + {}}); RunSyncTest(rpcs); } @@ -141,7 +167,7 @@ TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_samefunctionname) TEST_F(ITest_Internals_Rpc, test_1client_2server_sync) { const uint32_t numCallsToReceive = defaultNumCalls; - const uint32_t numCallsToReturn = defaultNumCalls*2; + const uint32_t numCallsToReturn = defaultNumCalls * 2; std::vector> expectedReturnDataUnordered; for (uint8_t d = 0; d < defaultNumCalls; d++) @@ -151,7 +177,17 @@ TEST_F(ITest_Internals_Rpc, test_1client_2server_sync) } std::vector rpcs; - rpcs.push_back({"Client1", {}, {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn, expectedReturnDataUnordered}}, {"TestFuncA"} }); + rpcs.push_back({"Client1", + {}, + {{"ClientCtrl1", + "TestFuncA", + "A", + {}, + defaultMsgSize, + defaultNumCalls, + numCallsToReturn, + expectedReturnDataUnordered}}, + {"TestFuncA"}}); rpcs.push_back({"Server1", {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive}}, {}, {}}); rpcs.push_back({"Server2", {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive}}, {}, {}}); @@ -168,13 +204,13 @@ TEST_F(ITest_Internals_Rpc, test_Nclient_1server_sync) std::vector rpcs; for (uint32_t i = 0; i < numClients; i++) { - std::string participantName = "Client" + std::to_string(i+1); + std::string participantName = "Client" + std::to_string(i + 1); rpcs.push_back({participantName, {}, {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, {"TestFuncA"}}); } - + std::vector> expectedDataUnordered; for (uint8_t d = 0; d < defaultNumCalls; d++) { @@ -212,7 +248,7 @@ TEST_F(ITest_Internals_Rpc, test_1client_2server_sync_wrongFunctionName) TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_wrongDataMediaType) { const uint32_t numCallsToReceive = defaultNumCalls; - const uint32_t numCallsToReturn = defaultNumCalls; + const uint32_t numCallsToReturn = defaultNumCalls; std::vector rpcs; rpcs.push_back({"Client1", @@ -225,7 +261,7 @@ TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_wrongDataMediaType) RunSyncTest(rpcs); } -// Matching mandatory and optional labels on both sides +// Matching mandatory and optional labels on both sides TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_labels) { const uint32_t numCallsToReceive = defaultNumCalls; @@ -307,17 +343,18 @@ TEST_F(ITest_Internals_Rpc, test_1client_2server_sync_wrong_optional_label_value const uint32_t numCallsToReturn = defaultNumCalls; std::vector rpcs; - rpcs.push_back({"Client1", - {}, - {{"ClientCtrl1", - "TestFuncA", - "A", - {{"KeyA", "ValWrong", SilKit::Services::MatchingLabel::Kind::Optional}, // Won't match Server1, but Server2 - {"KeyB", "ValB", SilKit::Services::MatchingLabel::Kind::Optional}}, - defaultMsgSize, - defaultNumCalls, - numCallsToReturn}}, - {"TestFuncA", "TestFuncA"}}); + rpcs.push_back( + {"Client1", + {}, + {{"ClientCtrl1", + "TestFuncA", + "A", + {{"KeyA", "ValWrong", SilKit::Services::MatchingLabel::Kind::Optional}, // Won't match Server1, but Server2 + {"KeyB", "ValB", SilKit::Services::MatchingLabel::Kind::Optional}}, + defaultMsgSize, + defaultNumCalls, + numCallsToReturn}}, + {"TestFuncA", "TestFuncA"}}); rpcs.push_back({"Server1", {{"ServerCtrl1", "TestFuncA", @@ -348,7 +385,10 @@ TEST_F(ITest_Internals_Rpc, test_1client_1server_sync_wildcardDxf) const uint32_t numCallsToReturn = defaultNumCalls; std::vector rpcs; - rpcs.push_back({"Client1", {}, {{"ClientCtrl1", "TestFuncA", "", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, {"TestFuncA"} }); + rpcs.push_back({"Client1", + {}, + {{"ClientCtrl1", "TestFuncA", "", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, + {"TestFuncA"}}); rpcs.push_back({"Server1", {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive}}, {}, {}}); RunSyncTest(rpcs); @@ -365,9 +405,10 @@ TEST_F(ITest_Internals_Rpc, test_1_participant_selfdelivery) const uint32_t numCallsToReturn = defaultNumCalls; std::vector rpcs; - rpcs.push_back({"Mixed1", - {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive}}, - {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, {"TestFuncA"}}); + rpcs.push_back({"Mixed1", + {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive}}, + {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn}}, + {"TestFuncA"}}); RunSyncTest(rpcs); } @@ -394,8 +435,22 @@ TEST_F(ITest_Internals_Rpc, test_1_participant_selfdelivery_same_functionname) rpcs.push_back({"Mixed1", {{"ServerCtrl1", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive, expectedDataUnordered}, {"ServerCtrl2", "TestFuncA", "A", {}, defaultMsgSize, numCallsToReceive, expectedDataUnordered}}, - {{"ClientCtrl1", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn, expectedReturnDataUnordered}, - {"ClientCtrl2", "TestFuncA", "A", {}, defaultMsgSize, defaultNumCalls, numCallsToReturn, expectedReturnDataUnordered}}, + {{"ClientCtrl1", + "TestFuncA", + "A", + {}, + defaultMsgSize, + defaultNumCalls, + numCallsToReturn, + expectedReturnDataUnordered}, + {"ClientCtrl2", + "TestFuncA", + "A", + {}, + defaultMsgSize, + defaultNumCalls, + numCallsToReturn, + expectedReturnDataUnordered}}, {"TestFuncA", "TestFuncA"}}); RunSyncTest(rpcs); diff --git a/SilKit/IntegrationTests/ITest_Internals_Rpc.hpp b/SilKit/IntegrationTests/ITest_Internals_Rpc.hpp index d47e4e3be..b0ed842ea 100644 --- a/SilKit/IntegrationTests/ITest_Internals_Rpc.hpp +++ b/SilKit/IntegrationTests/ITest_Internals_Rpc.hpp @@ -119,7 +119,8 @@ class ITest_Internals_Rpc : public testing::Test auto argumentData = std::vector(info.messageSizeInBytes, static_cast(callCounter)); if (info.numCallsToTimeout > 0) { - rpcClient->CallWithTimeout(argumentData, info.timeout, reinterpret_cast(uintptr_t(callCounter))); + rpcClient->CallWithTimeout(argumentData, info.timeout, + reinterpret_cast(uintptr_t(callCounter))); } else { @@ -210,7 +211,7 @@ class ITest_Internals_Rpc : public testing::Test bool expectIncreasingData; std::vector> expectedDataUnordered; IRpcServer* rpcServer = nullptr; - bool doNotReply {false}; + bool doNotReply{false}; }; struct RpcServerState @@ -271,13 +272,9 @@ class ITest_Internals_Rpc : public testing::Test { name = newName; - std::for_each(newRpcServers.begin(), newRpcServers.end(), [this](const auto& info) { - AddRpcServer(info); - }); + std::for_each(newRpcServers.begin(), newRpcServers.end(), [this](const auto& info) { AddRpcServer(info); }); - std::for_each(newRpcClients.begin(), newRpcClients.end(), [this](const auto& info) { - AddRpcClient(info); - }); + std::for_each(newRpcClients.begin(), newRpcClients.end(), [this](const auto& info) { AddRpcClient(info); }); } std::string name; @@ -311,9 +308,8 @@ class ITest_Internals_Rpc : public testing::Test void PrepareAllReceivedPromise() { - if (std::all_of(rpcServers.begin(), rpcServers.end(), [](const auto& s) -> bool { - return s->info.numCallsToReceive == 0; - })) + if (std::all_of(rpcServers.begin(), rpcServers.end(), + [](const auto& s) -> bool { return s->info.numCallsToReceive == 0; })) { allReceived = true; allReceivedPromise.set_value(); @@ -323,8 +319,8 @@ class ITest_Internals_Rpc : public testing::Test void CheckAllCalledPromise() { if (!allCalled && std::all_of(rpcClients.begin(), rpcClients.end(), [](const auto& c) -> bool { - return c->allCalled; - })) + return c->allCalled; + })) { allCalled = true; allCalledPromise.set_value(); @@ -334,8 +330,8 @@ class ITest_Internals_Rpc : public testing::Test void CheckAllCallsReceivedPromise() { if (!allReceived && std::all_of(rpcServers.begin(), rpcServers.end(), [](const auto& s) -> bool { - return s->allReceived; - })) + return s->allReceived; + })) { allReceived = true; allReceivedPromise.set_value(); @@ -345,9 +341,8 @@ class ITest_Internals_Rpc : public testing::Test void CheckAllCallsReturnedPromise() { if (!allCallsReturned - && std::all_of(rpcClients.begin(), rpcClients.end(), [](const auto& clientInfo) -> bool { - return clientInfo->allCallsReturned; - })) + && std::all_of(rpcClients.begin(), rpcClients.end(), + [](const auto& clientInfo) -> bool { return clientInfo->allCallsReturned; })) { allCallsReturned = true; allCallsReturnedPromise.set_value(); @@ -397,87 +392,87 @@ class ITest_Internals_Rpc : public testing::Test } }; - void ParticipantThread(RpcParticipant& participant, const std::string& registryUri, bool sync) + void ParticipantThread(RpcParticipant& participant, const std::string& registryUri, bool sync) + { + try { - try - { - participant.participant = SilKit::CreateParticipantImpl( - SilKit::Config::MakeParticipantConfigurationWithLoggingImpl(SilKit::Services::Logging::Level::Warn), - participant.name, registryUri); - participant.participantImpl = - dynamic_cast(participant.participant.get()); - - participant.participantImpl->GetServiceDiscovery()->RegisterServiceDiscoveryHandler( - [&participant](auto type, auto&& serviceDescr) { - if (type == SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated) - { - if (serviceDescr.GetNetworkType() == SilKit::Config::NetworkType::RPC) - { - participant.OnNewServiceDiscovery(serviceDescr); - } - } - }); - - - // Create Clients - for (const auto& c : participant.rpcClients) + participant.participant = SilKit::CreateParticipantImpl( + SilKit::Config::MakeParticipantConfigurationWithLoggingImpl(SilKit::Services::Logging::Level::Warn), + participant.name, registryUri); + participant.participantImpl = + dynamic_cast(participant.participant.get()); + + participant.participantImpl->GetServiceDiscovery()->RegisterServiceDiscoveryHandler( + [&participant](auto type, auto&& serviceDescr) { + if (type == SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated) { - auto callReturnHandler = [&participant, &c](IRpcClient* /*client*/, RpcCallResultEvent event) { - if (!c->allCallsReturned) - { - if (event.callStatus == RpcCallStatus::Success) - { - c->OnCallReturned(SilKit::Util::ToStdVector(event.resultData)); - } - if (event.callStatus == RpcCallStatus::Timeout) - { - c->OnCallTimeout(); - } - } - participant.CheckAllCallsReturnedPromise(); - }; - - SilKit::Services::Rpc::RpcSpec dataSpec{c->info.functionName, c->info.mediaType}; - for (const auto& label : c->info.labels) + if (serviceDescr.GetNetworkType() == SilKit::Config::NetworkType::RPC) { - dataSpec.AddLabel(label); + participant.OnNewServiceDiscovery(serviceDescr); } - - c->rpcClient = - participant.participant->CreateRpcClient(c->info.controllerName, dataSpec, callReturnHandler); } + }); - // Create Servers - for (const auto& s : participant.rpcServers) - { - participant.PrepareAllReceivedPromise(); - auto processCalls = [&participant, &s](IRpcServer* server, RpcCallEvent event) { - // Increment data - auto returnData = SilKit::Util::ToStdVector(event.argumentData); - for (auto& d : returnData) + // Create Clients + for (const auto& c : participant.rpcClients) + { + auto callReturnHandler = [&participant, &c](IRpcClient* /*client*/, RpcCallResultEvent event) { + if (!c->allCallsReturned) + { + if (event.callStatus == RpcCallStatus::Success) { - d += rpcFuncIncrement; + c->OnCallReturned(SilKit::Util::ToStdVector(event.resultData)); } - if (!s->info.doNotReply) + if (event.callStatus == RpcCallStatus::Timeout) { - server->SubmitResult(event.callHandle, returnData); + c->OnCallTimeout(); } + } + participant.CheckAllCallsReturnedPromise(); + }; + + SilKit::Services::Rpc::RpcSpec dataSpec{c->info.functionName, c->info.mediaType}; + for (const auto& label : c->info.labels) + { + dataSpec.AddLabel(label); + } + + c->rpcClient = + participant.participant->CreateRpcClient(c->info.controllerName, dataSpec, callReturnHandler); + } - // Evaluate data and reception count - s->ReceiveCall(SilKit::Util::ToStdVector(event.argumentData)); - participant.CheckAllCallsReceivedPromise(); - }; + // Create Servers + for (const auto& s : participant.rpcServers) + { + participant.PrepareAllReceivedPromise(); - SilKit::Services::Rpc::RpcSpec dataSpec{s->info.functionName, s->info.mediaType}; - for (const auto& label : s->info.labels) + auto processCalls = [&participant, &s](IRpcServer* server, RpcCallEvent event) { + // Increment data + auto returnData = SilKit::Util::ToStdVector(event.argumentData); + for (auto& d : returnData) + { + d += rpcFuncIncrement; + } + if (!s->info.doNotReply) { - dataSpec.AddLabel(label); + server->SubmitResult(event.callHandle, returnData); } - s->rpcServer = participant.participant->CreateRpcServer(s->info.controllerName, dataSpec, processCalls); + // Evaluate data and reception count + s->ReceiveCall(SilKit::Util::ToStdVector(event.argumentData)); + participant.CheckAllCallsReceivedPromise(); + }; + + SilKit::Services::Rpc::RpcSpec dataSpec{s->info.functionName, s->info.mediaType}; + for (const auto& label : s->info.labels) + { + dataSpec.AddLabel(label); } + s->rpcServer = participant.participant->CreateRpcServer(s->info.controllerName, dataSpec, processCalls); + } + if (sync) { auto* lifecycleService = participant.participant->CreateLifecycleService( @@ -486,13 +481,12 @@ class ITest_Internals_Rpc : public testing::Test timeSyncService->SetSimulationStepHandler( [&participant](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) { - for (const auto& client : participant.rpcClients) - { - client->Call(); - } - participant.CheckAllCalledPromise(); - }, - 1s); + for (const auto& client : participant.rpcClients) + { + client->Call(); + } + participant.CheckAllCalledPromise(); + }, 1s); auto finalStateFuture = lifecycleService->StartLifecycle(); finalStateFuture.get(); } @@ -502,9 +496,7 @@ class ITest_Internals_Rpc : public testing::Test if (!participant.rpcClients.empty()) { while (std::none_of(participant.rpcClients.begin(), participant.rpcClients.end(), - [](const auto& c) -> bool { - return c->allCalled; - })) + [](const auto& c) -> bool { return c->allCalled; })) { std::this_thread::sleep_for(50ms); for (auto& client : participant.rpcClients) @@ -526,126 +518,125 @@ class ITest_Internals_Rpc : public testing::Test } } - for (const auto& c : participant.rpcClients) - { - EXPECT_EQ(c->callCounter, c->info.numCalls); - EXPECT_EQ(c->callReturnedSuccessCounter, c->info.numCallsToReturn); - EXPECT_EQ(c->callReturnedTimeoutCounter, c->info.numCallsToTimeout); - } - for (const auto& s : participant.rpcServers) - { - EXPECT_EQ(s->receiveCallCounter, s->info.numCallsToReceive); - } + for (const auto& c : participant.rpcClients) + { + EXPECT_EQ(c->callCounter, c->info.numCalls); + EXPECT_EQ(c->callReturnedSuccessCounter, c->info.numCallsToReturn); + EXPECT_EQ(c->callReturnedTimeoutCounter, c->info.numCallsToTimeout); } - catch (const std::exception& error) + for (const auto& s : participant.rpcServers) { - _testSystem.ShutdownOnException(error); + EXPECT_EQ(s->receiveCallCounter, s->info.numCallsToReceive); } } + catch (const std::exception& error) + { + _testSystem.ShutdownOnException(error); + } + } - void RunParticipants(std::vector& rpcs, const std::string& registryUri, bool sync) + void RunParticipants(std::vector& rpcs, const std::string& registryUri, bool sync) + { + try { - try + for (auto& participant : rpcs) { - for (auto& participant : rpcs) - { - _rpcThreads.emplace_back([this, &participant, registryUri, sync] { - ParticipantThread(participant, registryUri, sync); - }); - } - } - catch (const std::exception& error) - { - _testSystem.ShutdownOnException(error); + _rpcThreads.emplace_back( + [this, &participant, registryUri, sync] { ParticipantThread(participant, registryUri, sync); }); } } + catch (const std::exception& error) + { + _testSystem.ShutdownOnException(error); + } + } - void JoinRpcThreads() + void JoinRpcThreads() + { + for (auto&& thread : _rpcThreads) { - for (auto&& thread : _rpcThreads) + thread.join(); + } + } + + void WaitForAllServersDiscovered(std::vector& rpcs) + { + for (auto& r : rpcs) + { + if (!r.rpcClients.empty()) { - thread.join(); + r.WaitForAllDiscovered(); } } + } - void WaitForAllServersDiscovered(std::vector& rpcs) + void StopSimOnallCalledAndReceived(std::vector& rpcs, bool sync) + { + if (sync) { for (auto& r : rpcs) { if (!r.rpcClients.empty()) { - r.WaitForAllDiscovered(); + r.WaitForAllCalled(); } } - } - - void StopSimOnallCalledAndReceived(std::vector& rpcs, bool sync) - { - if (sync) + for (auto& r : rpcs) { - for (auto& r : rpcs) + if (!r.rpcServers.empty()) { - if (!r.rpcClients.empty()) - { - r.WaitForAllCalled(); - } + r.WaitForAllCallsReceived(); } - for (auto& r : rpcs) - { - if (!r.rpcServers.empty()) - { - r.WaitForAllCallsReceived(); - } - } - for (auto& r : rpcs) + } + for (auto& r : rpcs) + { + if (!r.rpcClients.empty()) { - if (!r.rpcClients.empty()) - { - r.WaitForAllCallsReturned(); - } + r.WaitForAllCallsReturned(); } - _testSystem.SystemMasterStop(); } + _testSystem.SystemMasterStop(); } + } - void ShutdownSystem() - { - _rpcThreads.clear(); - _testSystem.ShutdownInfrastructure(); - } - - void RunSyncTest(std::vector& rpcs) - { - auto registryUri = MakeTestRegistryUri(); + void ShutdownSystem() + { + _rpcThreads.clear(); + _testSystem.ShutdownInfrastructure(); + } - std::vector requiredParticipantNames; - for (const auto& p : rpcs) - { - requiredParticipantNames.push_back(p.name); - } + void RunSyncTest(std::vector& rpcs) + { + auto registryUri = MakeTestRegistryUri(); - _testSystem.SetupRegistryAndSystemMaster(registryUri, true, std::move(requiredParticipantNames)); - RunParticipants(rpcs, registryUri, true); - WaitForAllServersDiscovered(rpcs); - StopSimOnallCalledAndReceived(rpcs, true); - JoinRpcThreads(); - ShutdownSystem(); + std::vector requiredParticipantNames; + for (const auto& p : rpcs) + { + requiredParticipantNames.push_back(p.name); } - void RunAsyncTest(std::vector& rpcs) - { - auto registryUri = MakeTestRegistryUri(); + _testSystem.SetupRegistryAndSystemMaster(registryUri, true, std::move(requiredParticipantNames)); + RunParticipants(rpcs, registryUri, true); + WaitForAllServersDiscovered(rpcs); + StopSimOnallCalledAndReceived(rpcs, true); + JoinRpcThreads(); + ShutdownSystem(); + } + + void RunAsyncTest(std::vector& rpcs) + { + auto registryUri = MakeTestRegistryUri(); - _testSystem.SetupRegistryAndSystemMaster(registryUri, false, {}); - RunParticipants(rpcs, registryUri, false); - WaitForAllServersDiscovered(rpcs); - JoinRpcThreads(); - ShutdownSystem(); - } + _testSystem.SetupRegistryAndSystemMaster(registryUri, false, {}); + RunParticipants(rpcs, registryUri, false); + WaitForAllServersDiscovered(rpcs); + JoinRpcThreads(); + ShutdownSystem(); + } - protected: - std::vector _rpcThreads; +protected: + std::vector _rpcThreads; - private: - TestInfrastructure _testSystem; - }; +private: + TestInfrastructure _testSystem; +}; diff --git a/SilKit/IntegrationTests/ITest_Internals_ServiceDiscovery.cpp b/SilKit/IntegrationTests/ITest_Internals_ServiceDiscovery.cpp index 9a87acd1a..e4374facb 100644 --- a/SilKit/IntegrationTests/ITest_Internals_ServiceDiscovery.cpp +++ b/SilKit/IntegrationTests/ITest_Internals_ServiceDiscovery.cpp @@ -47,10 +47,7 @@ using namespace SilKit::Core; class ITest_Internals_ServiceDiscovery : public testing::Test { protected: - ITest_Internals_ServiceDiscovery() - { - } - + ITest_Internals_ServiceDiscovery() {} }; // Tests that the service discovery handler fires for created services @@ -67,11 +64,12 @@ TEST_F(ITest_Internals_ServiceDiscovery, discover_services) registry->StartListening(registryUri); // Publisher that will leave the simulation and trigger service removal - auto&& publisher = SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), publisherName, registryUri); + auto&& publisher = SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), + publisherName, registryUri); // Subscriber that monitors the services - auto&& subscriber = - SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), subscriberName, registryUri); + auto&& subscriber = SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), + subscriberName, registryUri); // Services for (auto i = 0u; i < numberOfServices; i++) @@ -90,42 +88,41 @@ TEST_F(ITest_Internals_ServiceDiscovery, discover_services) // Cast to internal participant for access to service discovery auto subscriberServiceDiscovery = dynamic_cast(subscriber.get())->GetServiceDiscovery(); - + auto allCreated = std::promise(); auto allRemoved = std::promise(); - // Participants are already there, so the registration will trigger the provided handler immediately + // Participants are already there, so the registration will trigger the provided handler immediately subscriberServiceDiscovery->RegisterServiceDiscoveryHandler( [numberOfServices, &allRemoved, &allCreated, &createdServiceNames, &removedServiceNames, publisherName]( - auto discoveryType, const auto& service) + auto discoveryType, const auto& service) { + switch (discoveryType) { - switch (discoveryType) + case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::Invalid: + break; + case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated: + if (service.GetParticipantName() == publisherName) { - case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::Invalid: - break; - case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated: - if (service.GetParticipantName() == publisherName) + createdServiceNames.push_back(service.GetServiceName()); + if (createdServiceNames.size() == numberOfServices) { - createdServiceNames.push_back(service.GetServiceName()); - if (createdServiceNames.size() == numberOfServices) - { - allCreated.set_value(); - } + allCreated.set_value(); } - break; - case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved: - if (service.GetParticipantName() == publisherName) + } + break; + case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved: + if (service.GetParticipantName() == publisherName) + { + removedServiceNames.push_back(service.GetServiceName()); + if (removedServiceNames.size() == createdServiceNames.size()) { - removedServiceNames.push_back(service.GetServiceName()); - if (removedServiceNames.size() == createdServiceNames.size()) - { - allRemoved.set_value(); - } + allRemoved.set_value(); } - break; - default: - break; } - }); + break; + default: + break; + } + }); // Await the creation allCreated.get_future().wait_for(10s); @@ -159,10 +156,12 @@ TEST_F(ITest_Internals_ServiceDiscovery, discover_specific_services) registry->StartListening(registryUri); // Publisher that will leave the simulation and trigger service removal - auto&& publisher = SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), publisherName, registryUri); + auto&& publisher = SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), + publisherName, registryUri); // Subscriber that monitors the services - auto&& subscriber = SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), subscriberName, registryUri); + auto&& subscriber = SilKit::CreateParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), + subscriberName, registryUri); // Services const std::string topic = "Topic"; @@ -183,46 +182,48 @@ TEST_F(ITest_Internals_ServiceDiscovery, discover_specific_services) auto allRemoved = std::promise(); const auto discoveryLookupKey = SilKit::Core::Discovery::controllerTypeDataPublisher + "/" - + SilKit::Core::Discovery::supplKeyDataPublisherTopic + "/" + topic + "/" - + SilKit::Core::Discovery::supplKeyDataPublisherPubLabels + "/"; + + SilKit::Core::Discovery::supplKeyDataPublisherTopic + "/" + topic + "/" + + SilKit::Core::Discovery::supplKeyDataPublisherPubLabels + "/"; std::string controllerType = SilKit::Core::Discovery::controllerTypeDataPublisher; std::string mediaType = ""; std::string topicCopy = topic; - std::vector labels; + std::vector labels; // Participants are already there, so the registration will trigger the provided handler immediately subscriberServiceDiscovery->RegisterSpecificServiceDiscoveryHandler( [numberOfServices, &allRemoved, &allCreated, &createdServiceNames, &removedServiceNames, publisherName]( auto discoveryType, const auto& service) { - switch (discoveryType) + switch (discoveryType) + { + case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::Invalid: + break; + case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated: + if (service.GetParticipantName() == publisherName) { - case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::Invalid: break; - case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated: - if (service.GetParticipantName() == publisherName) + createdServiceNames.push_back(service.GetServiceName()); + if (createdServiceNames.size() == numberOfServices) { - createdServiceNames.push_back(service.GetServiceName()); - if (createdServiceNames.size() == numberOfServices) - { - allCreated.set_value(); - } + allCreated.set_value(); } - break; - case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved: - if (service.GetParticipantName() == publisherName) + } + break; + case SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved: + if (service.GetParticipantName() == publisherName) + { + removedServiceNames.push_back(service.GetServiceName()); + if (removedServiceNames.size() == createdServiceNames.size()) { - removedServiceNames.push_back(service.GetServiceName()); - if (removedServiceNames.size() == createdServiceNames.size()) - { - allRemoved.set_value(); - } + allRemoved.set_value(); } - break; - default: break; } - }, controllerType, - topicCopy, labels); + break; + default: + break; + } + }, + controllerType, topicCopy, labels); // Await the creation allCreated.get_future().wait_for(10s); diff --git a/SilKit/IntegrationTests/ITest_Internals_TargetedMessaging.cpp b/SilKit/IntegrationTests/ITest_Internals_TargetedMessaging.cpp index 49bef9135..ab57ea388 100644 --- a/SilKit/IntegrationTests/ITest_Internals_TargetedMessaging.cpp +++ b/SilKit/IntegrationTests/ITest_Internals_TargetedMessaging.cpp @@ -48,7 +48,7 @@ TEST(ITest_Internals_TargetedMessaging, targeted_messaging) { auto registryUri = MakeTestRegistryUri(); - std::vector syncParticipantNames{ "Sender", "TargetReceiver" , "OtherReceiver" }; + std::vector syncParticipantNames{"Sender", "TargetReceiver", "OtherReceiver"}; auto receiveCount = 0; @@ -69,9 +69,9 @@ TEST(ITest_Internals_TargetedMessaging, targeted_messaging) senderTimeSyncService->SetSimulationStepHandler( [&senderLifecycleService, &senderCan, &senderCom](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - auto nowMs = std::chrono::duration_cast(now); - std::cout << "Sender: Current time=" << nowMs.count() << "ms" << std::endl; - if (now == 0ms) + auto nowMs = std::chrono::duration_cast(now); + std::cout << "Sender: Current time=" << nowMs.count() << "ms" << std::endl; + if (now == 0ms) { SilKit::Services::Can::WireCanFrameEvent msg{}; msg.direction = SilKit::Services::TransmitDirection::RX; @@ -83,31 +83,30 @@ TEST(ITest_Internals_TargetedMessaging, targeted_messaging) { senderLifecycleService->Stop("Test"); } - }, 1ms); + }, + 1ms); + - auto* receiverComSimPart = testHarness.GetParticipant("TargetReceiver"); auto* receiverCom = &SilKit::Tests::ToParticipantInternal(*receiverComSimPart->Participant()); auto* receiverTimeSyncService = receiverComSimPart->GetOrCreateTimeSyncService(); receiverTimeSyncService->SetSimulationStepHandler( - [](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) { - }, 1ms); + [](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) {}, 1ms); auto* receiverCan = receiverCom->CreateCanController("CAN1", "CAN1"); - receiverCan->AddFrameHandler( - [&receiveCount](SilKit::Services::Can::ICanController* controller, auto msg) { - std::cout << "'TargetReceiver' received a message from controller '" << controller - << "' with canId=" << msg.frame.canId << std::endl; - ASSERT_TRUE(msg.frame.canId == 42) << "The received canId is wrong. expected=42; received=" << msg.frame.canId; - receiveCount++; - }); + receiverCan->AddFrameHandler([&receiveCount](SilKit::Services::Can::ICanController* controller, auto msg) { + std::cout << "'TargetReceiver' received a message from controller '" << controller + << "' with canId=" << msg.frame.canId << std::endl; + ASSERT_TRUE(msg.frame.canId == 42) << "The received canId is wrong. expected=42; received=" << msg.frame.canId; + receiveCount++; + }); auto* otherReceiverComSimPart = testHarness.GetParticipant("OtherReceiver"); auto* otherReceiverCom = &SilKit::Tests::ToParticipantInternal(*otherReceiverComSimPart->Participant()); auto* otherTimeSyncService = otherReceiverComSimPart->GetOrCreateTimeSyncService(); - + otherTimeSyncService->SetSimulationStepHandler( [](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) {}, 1ms); diff --git a/SilKit/IntegrationTests/ITest_Lin.cpp b/SilKit/IntegrationTests/ITest_Lin.cpp old mode 100755 new mode 100644 index 5e149dd6e..3ed54b176 --- a/SilKit/IntegrationTests/ITest_Lin.cpp +++ b/SilKit/IntegrationTests/ITest_Lin.cpp @@ -78,7 +78,8 @@ class Schedule { public: Schedule() = default; - Schedule(std::initializer_list>> tasks) + Schedule( + std::initializer_list>> tasks) { for (auto&& task : tasks) { @@ -100,7 +101,7 @@ class Schedule void ScheduleNextTask() { - if(_nextTask == _schedule.end()) + if (_nextTask == _schedule.end()) { return; } @@ -119,8 +120,13 @@ class Schedule } private: - struct Task { - Task(std::chrono::nanoseconds delay, std::function action) : delay{delay}, action{action} {} + struct Task + { + Task(std::chrono::nanoseconds delay, std::function action) + : delay{delay} + , action{action} + { + } std::chrono::nanoseconds delay; std::function action; @@ -158,8 +164,8 @@ struct LinNode virtual ~LinNode() = default; - void Stop() - { + void Stop() + { _lifecycleService->Stop("Stop"); } @@ -205,14 +211,14 @@ class LinMaster : public LinNode _result.sendTimes.push_back(now); controller->SendFrame(frame, LinFrameResponseType::MasterResponse); } - + void SendFrame_17(std::chrono::nanoseconds now) { LinFrame frame; frame.id = 17; frame.checksumModel = LinChecksumModel::Classic; frame.dataLength = 6; - frame.data = std::array{1,7,1,7,1,7,1,7}; + frame.data = std::array{1, 7, 1, 7, 1, 7, 1, 7}; _result.sendTimes.push_back(now); controller->SendFrame(frame, LinFrameResponseType::MasterResponse); @@ -280,12 +286,10 @@ class LinMaster : public LinNode }; - class LinSlave : public LinNode { public: - LinSlave(IParticipant* participant, ILinController* controller, - Orchestration::ILifecycleService* lifecycleService) + LinSlave(IParticipant* participant, ILinController* controller, Orchestration::ILifecycleService* lifecycleService) : LinNode(participant, controller, "LinSlave", lifecycleService) { } @@ -313,11 +317,10 @@ class LinSlave : public LinNode void GoToSleepHandler(ILinController* linController, const LinGoToSleepEvent& /*goToSleepEvent*/) { // wakeup in 10 ms - timer.Set(now + 10ms, - [linController](std::chrono::nanoseconds /*now*/) { - linController->Wakeup(); - // The LinSlave doesn't receive the wakeup pulse sent by himself in a trivial simulation (without netsim) - }); + timer.Set(now + 10ms, [linController](std::chrono::nanoseconds /*now*/) { + linController->Wakeup(); + // The LinSlave doesn't receive the wakeup pulse sent by himself in a trivial simulation (without netsim) + }); linController->GoToSleepInternal(); _result.gotoSleepReceived = true; } @@ -401,7 +404,7 @@ class ITest_Lin : public testing::Test TEST_F(ITest_Lin, sync_lin_simulation) { auto registryUri = MakeTestRegistryUri(); - std::vector participantNames = { "LinMaster", "LinSlave" }; + std::vector participantNames = {"LinMaster", "LinSlave"}; _simTestHarness = std::make_unique(participantNames, registryUri, false); std::vector> linNodes; @@ -409,62 +412,57 @@ TEST_F(ITest_Lin, sync_lin_simulation) { const std::string participantName = "LinMaster"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); lifecycleService->SetCommunicationReadyHandler([participantName, linController]() { auto config = MakeControllerConfig(participantName); linController->Init(config); - }); + }); auto master = std::make_unique(participant, linController, lifecycleService); linController->AddFrameStatusHandler( [master = master.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master->ReceiveFrameStatus(linController, frameStatusEvent); - }); + master->ReceiveFrameStatus(linController, frameStatusEvent); + }); linController->AddWakeupHandler( [master = master.get()](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - master->WakeupHandler(linController, wakeupEvent); - }); + master->WakeupHandler(linController, wakeupEvent); + }); timeSyncService->SetSimulationStepHandler( [master = master.get(), participantName](auto now, std::chrono::nanoseconds /*duration*/) { - master->doAction(now); - }, 1ms); + master->doAction(now); + }, 1ms); linNodes.emplace_back(std::move(master)); } { const std::string participantName = "LinSlave"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); auto config = MakeControllerConfig(participantName); - lifecycleService->SetCommunicationReadyHandler([config, participantName, linController]() { - linController->Init(config); - }); + lifecycleService->SetCommunicationReadyHandler( + [config, participantName, linController]() { linController->Init(config); }); auto slave = std::make_unique(participant, linController, lifecycleService); linController->AddFrameStatusHandler( [slave = slave.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - slave->FrameStatusHandler(linController, frameStatusEvent); - }); + slave->FrameStatusHandler(linController, frameStatusEvent); + }); linController->AddGoToSleepHandler( [slave = slave.get()](ILinController* linController, const LinGoToSleepEvent& goToSleepEvent) { - slave->GoToSleepHandler(linController, goToSleepEvent); - }); + slave->GoToSleepHandler(linController, goToSleepEvent); + }); timeSyncService->SetSimulationStepHandler( - [slave = slave.get()](auto now, std::chrono::nanoseconds /*duration*/) { - slave->DoAction(now); - }, 1ms); + [slave = slave.get()](auto now, std::chrono::nanoseconds /*duration*/) { slave->DoAction(now); }, 1ms); linNodes.emplace_back(std::move(slave)); } @@ -475,7 +473,7 @@ TEST_F(ITest_Lin, sync_lin_simulation) // Sim is stopped when master received the wakeup pulse - for (auto& node: linNodes) + for (auto& node : linNodes) { if (node->_name == "LinSlave") { @@ -487,8 +485,7 @@ TEST_F(ITest_Lin, sync_lin_simulation) } else { - EXPECT_TRUE(node->_result.gotoSleepSent) - << "Assuming node " << node->_name << " has received a GoToSleep"; + EXPECT_TRUE(node->_result.gotoSleepSent) << "Assuming node " << node->_name << " has received a GoToSleep"; EXPECT_TRUE(node->_result.wakeupReceived) << "Assuming node " << node->_name << " has received a Wakeup"; } } @@ -500,7 +497,7 @@ TEST_F(ITest_Lin, sync_lin_simulation) EXPECT_GT(masterRecvTimes.size(), 0u); ASSERT_EQ(masterSendTimes.size(), masterRecvTimes.size()) << "The master send times and receive times should have equal size."; - for(auto i = 0u; i< masterRecvTimes.size(); i++) + for (auto i = 0u; i < masterRecvTimes.size(); i++) { const auto& sendT = masterSendTimes.at(i); const auto& recvT = masterRecvTimes.at(i); @@ -522,7 +519,7 @@ TEST_F(ITest_Lin, sync_lin_simulation) auto&& slaveRecvFrames = linNodes.at(1)->_result.receivedFrames; // 5x acks with TX_OK for id 16,17,18,19,60 on master - EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK].size(), 5); + EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK].size(), 5); // LIN_RX_OK for Id 16 and GoToSleep-Frame EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK].size(), 2); diff --git a/SilKit/IntegrationTests/ITest_LinDemo.cpp b/SilKit/IntegrationTests/ITest_LinDemo.cpp old mode 100755 new mode 100644 index a30b1aa76..3cb35ed8e --- a/SilKit/IntegrationTests/ITest_LinDemo.cpp +++ b/SilKit/IntegrationTests/ITest_LinDemo.cpp @@ -81,7 +81,8 @@ class Schedule { public: Schedule() = default; - Schedule(std::initializer_list>> tasks) + Schedule( + std::initializer_list>> tasks) { for (auto&& task : tasks) { @@ -114,8 +115,13 @@ class Schedule } private: - struct Task { - Task(std::chrono::nanoseconds delay, std::function action) : delay{delay}, action{action} {} + struct Task + { + Task(std::chrono::nanoseconds delay, std::function action) + : delay{delay} + , action{action} + { + } std::chrono::nanoseconds delay; std::function action; @@ -151,7 +157,10 @@ struct LinNode virtual ~LinNode() = default; - void Stop() { _lifecycleService->Stop("Stop"); } + void Stop() + { + _lifecycleService->Stop("Stop"); + } ILinController* _controller{nullptr}; IParticipant* _participant{nullptr}; @@ -164,18 +173,15 @@ struct LinNode class LinMaster : public LinNode { public: - LinMaster(IParticipant* participant, ILinController* controller, - Orchestration::ILifecycleService* lifecycleService) + LinMaster(IParticipant* participant, ILinController* controller, Orchestration::ILifecycleService* lifecycleService) : LinNode(participant, controller, "LinMaster", lifecycleService) { - schedule = { - {0ns, [this](std::chrono::nanoseconds now) { SendFrame_16(now); }}, - {0ns, [this](std::chrono::nanoseconds now) { SendFrame_17(now); }}, - {0ns, [this](std::chrono::nanoseconds now) { SendFrame_18(now); }}, - {0ns, [this](std::chrono::nanoseconds now) { SendFrame_19(now); }}, - {0ns, [this](std::chrono::nanoseconds now) { SendFrame_34(now); }}, - {5ms, [this](std::chrono::nanoseconds now) { GoToSleep(now); }} - }; + schedule = {{0ns, [this](std::chrono::nanoseconds now) { SendFrame_16(now); }}, + {0ns, [this](std::chrono::nanoseconds now) { SendFrame_17(now); }}, + {0ns, [this](std::chrono::nanoseconds now) { SendFrame_18(now); }}, + {0ns, [this](std::chrono::nanoseconds now) { SendFrame_19(now); }}, + {0ns, [this](std::chrono::nanoseconds now) { SendFrame_34(now); }}, + {5ms, [this](std::chrono::nanoseconds now) { GoToSleep(now); }}}; } void doAction(std::chrono::nanoseconds now) @@ -198,14 +204,14 @@ class LinMaster : public LinNode _controller->SendFrame(frame, LinFrameResponseType::MasterResponse); Log() << "<< LIN LinFrame sent with ID=" << static_cast(frame.id) << " now=" << now; } - + void SendFrame_17(std::chrono::nanoseconds now) { LinFrame frame; frame.id = 17; frame.checksumModel = Lin::LinChecksumModel::Classic; frame.dataLength = 6; - frame.data = std::array{1,7,1,7,1,7,1,7}; + frame.data = std::array{1, 7, 1, 7, 1, 7, 1, 7}; _result.sendTimes.push_back(now); _controller->SendFrame(frame, LinFrameResponseType::MasterResponse); @@ -256,22 +262,24 @@ class LinMaster : public LinNode _controller->GoToSleep(); _result.gotoSleepSent = true; _result.sendTimes.push_back(now); - } - void ReceiveFrameStatus(ILinController* , const LinFrameStatusEvent& frameStatusEvent) + void ReceiveFrameStatus(ILinController*, const LinFrameStatusEvent& frameStatusEvent) { switch (frameStatusEvent.status) { - case LinFrameStatus::LIN_RX_OK: break; // good case, no need to warn - case LinFrameStatus::LIN_TX_OK: break; // good case, no need to warn + case LinFrameStatus::LIN_RX_OK: + break; // good case, no need to warn + case LinFrameStatus::LIN_TX_OK: + break; // good case, no need to warn default: Log() << "WARNING: LIN transmission failed!"; } _result.receiveTimes.push_back(frameStatusEvent.timestamp); - Log() << ">> " << frameStatusEvent.frame << " status=" << frameStatusEvent.status << " timestamp=" << frameStatusEvent.timestamp; + Log() << ">> " << frameStatusEvent.frame << " status=" << frameStatusEvent.status + << " timestamp=" << frameStatusEvent.timestamp; schedule.ScheduleNextTask(); } @@ -291,12 +299,10 @@ class LinMaster : public LinNode }; - class LinSlave : public LinNode { public: - LinSlave(IParticipant* participant, ILinController* controller, - Orchestration::ILifecycleService* lifecycleService) + LinSlave(IParticipant* participant, ILinController* controller, Orchestration::ILifecycleService* lifecycleService) : LinNode(participant, controller, "LinSlave", lifecycleService) { } @@ -309,44 +315,42 @@ class LinSlave : public LinNode void FrameStatusHandler(ILinController* controller, const LinFrameStatusEvent& frameStatusEvent) { - Log() << ">> " << frameStatusEvent.frame - << " status=" << frameStatusEvent.status - << " timestamp=" << frameStatusEvent.timestamp - ; - for (const auto& response: _controllerConfig.frameResponses) + Log() << ">> " << frameStatusEvent.frame << " status=" << frameStatusEvent.status + << " timestamp=" << frameStatusEvent.timestamp; + for (const auto& response : _controllerConfig.frameResponses) { if (controller->Status() == LinControllerStatus::Sleep) { - _result.numberReceivedInSleep++; + _result.numberReceivedInSleep++; } - if (response.frame.id == frameStatusEvent.frame.id && response.frame.checksumModel == frameStatusEvent.frame.checksumModel) + if (response.frame.id == frameStatusEvent.frame.id + && response.frame.checksumModel == frameStatusEvent.frame.checksumModel) { _result.numberReceived++; if (_result.numberReceived == _controllerConfig.frameResponses.size()) { - //Test finished + //Test finished Stop(); } } } } - void GoToSleepHandler(ILinController* controller, const LinGoToSleepEvent& ) + void GoToSleepHandler(ILinController* controller, const LinGoToSleepEvent&) { - Log() << "LIN Slave received go-to-sleep command; entering sleep mode." ; + Log() << "LIN Slave received go-to-sleep command; entering sleep mode."; // wakeup in 10 ms - timer.Set(now + 10ms, - [controller](std::chrono::nanoseconds now) { - Log() << "<< Wakeup pulse now=" << now ; - controller->Wakeup(); - }); + timer.Set(now + 10ms, [controller](std::chrono::nanoseconds now) { + Log() << "<< Wakeup pulse now=" << now; + controller->Wakeup(); + }); controller->GoToSleepInternal(); _result.gotoSleepReceived = true; } - void WakeupHandler(ILinController* controller, const LinWakeupEvent& ) + void WakeupHandler(ILinController* controller, const LinWakeupEvent&) { - Log() << "LIN Slave received wakeup pulse; entering normal operation mode." ; + Log() << "LIN Slave received wakeup pulse; entering normal operation mode."; controller->WakeupInternal(); _result.wakeupReceived = true; } @@ -358,7 +362,7 @@ class LinSlave : public LinNode auto MakeControllerConfig(const std::string& participantName) { - LinControllerConfig config; + LinControllerConfig config; config.controllerMode = Lin::LinControllerMode::Master; config.baudRate = 20'000; @@ -424,84 +428,75 @@ TEST_F(ITest_LinDemo, DISABLED_lin_demo) { const std::string participantName = "LinMaster"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN1"); lifecycleService->SetCommunicationReadyHandler([participantName, linController]() { - Log() << "Initializing " << participantName; auto config = MakeControllerConfig(participantName); linController->Init(config); - - }); + }); auto master = std::make_unique(participant, linController, lifecycleService); linController->AddFrameStatusHandler( [master = master.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master->ReceiveFrameStatus(linController, frameStatusEvent); - }); + master->ReceiveFrameStatus(linController, frameStatusEvent); + }); linController->AddWakeupHandler( [master = master.get()](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - master->WakeupHandler(linController, wakeupEvent); - }); + master->WakeupHandler(linController, wakeupEvent); + }); timeSyncService->SetSimulationStepHandler( [master = master.get(), participantName](auto now, std::chrono::nanoseconds /*duration*/) { + auto nowMs = std::chrono::duration_cast(now); + Log() << participantName << " now=" << nowMs.count() << "ms"; - auto nowMs = std::chrono::duration_cast(now); - Log() << participantName << " now=" << nowMs.count() << "ms"; - - master->doAction(now); - - }, 1ms); + master->doAction(now); + }, 1ms); linNodes.emplace_back(std::move(master)); } { const std::string participantName = "LinSlave"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN1"); auto config = MakeControllerConfig(participantName); lifecycleService->SetCommunicationReadyHandler([config, participantName, linController]() { - Log() << " Initializing " << participantName; linController->Init(config); - - }); + }); auto slave = std::make_unique(participant, linController, lifecycleService); linController->AddFrameStatusHandler( [slave = slave.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - slave->FrameStatusHandler(linController, frameStatusEvent); - }); + slave->FrameStatusHandler(linController, frameStatusEvent); + }); linController->AddGoToSleepHandler( [slave = slave.get()](ILinController* linController, const LinGoToSleepEvent& goToSleepEvent) { - slave->GoToSleepHandler(linController, goToSleepEvent); - }); + slave->GoToSleepHandler(linController, goToSleepEvent); + }); linController->AddWakeupHandler( [slave = slave.get()](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - slave->WakeupHandler(linController, wakeupEvent); - }); + slave->WakeupHandler(linController, wakeupEvent); + }); //to validate the inputs slave->_controllerConfig = config; timeSyncService->SetSimulationStepHandler( [slave = slave.get()](auto now, std::chrono::nanoseconds /*duration*/) { - - Log() << "now=" << std::chrono::duration_cast(now).count() << "ms"; - slave->DoAction(now); - }, 1ms); + Log() << "now=" << std::chrono::duration_cast(now).count() << "ms"; + slave->DoAction(now); + }, 1ms); linNodes.emplace_back(std::move(slave)); } @@ -510,7 +505,7 @@ TEST_F(ITest_LinDemo, DISABLED_lin_demo) auto ok = _simTestHarness->Run(5s); ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; - for (auto& node: linNodes) + for (auto& node : linNodes) { if (node->_name == "LinSlave") { @@ -521,8 +516,7 @@ TEST_F(ITest_LinDemo, DISABLED_lin_demo) } else { - EXPECT_TRUE(node->_result.gotoSleepSent) - << "Assuming node " << node->_name << " has received a GoToSleep"; + EXPECT_TRUE(node->_result.gotoSleepSent) << "Assuming node " << node->_name << " has received a GoToSleep"; } EXPECT_TRUE(node->_result.wakeupReceived) << "Assuming node " << node->_name << " has received a Wakeup"; } @@ -548,14 +542,14 @@ TEST_F(ITest_LinDemo, DISABLED_lin_demo) } // Ensure that the receive times have no least significant digits (i.e., are rounded to 1ms) - for (auto ts: masterRecvTimes) + for (auto ts : masterRecvTimes) { - using namespace std::chrono; - //Round nanoseconds to milliseconds - auto tMs = duration_cast(ts); - const auto diffTs = ts - duration_cast(tMs); - EXPECT_EQ(diffTs.count(), (0ns).count()) - << "The simulated timestamps should have millisecond resolution in trivial simulation."; + using namespace std::chrono; + //Round nanoseconds to milliseconds + auto tMs = duration_cast(ts); + const auto diffTs = ts - duration_cast(tMs); + EXPECT_EQ(diffTs.count(), (0ns).count()) + << "The simulated timestamps should have millisecond resolution in trivial simulation."; } } diff --git a/SilKit/IntegrationTests/ITest_LinDynamicResponse.cpp b/SilKit/IntegrationTests/ITest_LinDynamicResponse.cpp index e1ba75db3..0bb3bfce1 100644 --- a/SilKit/IntegrationTests/ITest_LinDynamicResponse.cpp +++ b/SilKit/IntegrationTests/ITest_LinDynamicResponse.cpp @@ -83,7 +83,8 @@ class Schedule { public: Schedule() = default; - Schedule(std::initializer_list>> tasks) + Schedule( + std::initializer_list>> tasks) { for (auto&& task : tasks) { @@ -105,7 +106,7 @@ class Schedule void ScheduleNextTask() { - if(_nextTask == _schedule.end()) + if (_nextTask == _schedule.end()) { return; } @@ -124,8 +125,13 @@ class Schedule } private: - struct Task { - Task(std::chrono::nanoseconds delay, std::function action) : delay{delay}, action{action} {} + struct Task + { + Task(std::chrono::nanoseconds delay, std::function action) + : delay{delay} + , action{action} + { + } std::chrono::nanoseconds delay; std::function action; @@ -163,8 +169,8 @@ struct LinNode virtual ~LinNode() = default; - void Stop() - { + void Stop() + { _lifecycleService->Stop("Stop"); } @@ -178,7 +184,8 @@ struct LinNode class LinDynamicMaster : public LinNode { public: - LinDynamicMaster(IParticipant* participant, ILinController* controller, Orchestration::ILifecycleService* lifecycleService) + LinDynamicMaster(IParticipant* participant, ILinController* controller, + Orchestration::ILifecycleService* lifecycleService) : LinNode(participant, controller, "LinMaster", lifecycleService) { schedule = { @@ -201,7 +208,7 @@ class LinDynamicMaster : public LinNode f17.id = 17; f17.checksumModel = LinChecksumModel::Classic; f17.dataLength = 6; - f17.data = std::array{1,7,1,7,1,7,1,7}; + f17.data = std::array{1, 7, 1, 7, 1, 7, 1, 7}; _masterResponses[f17.id] = f17; LinFrame f18{}; @@ -266,7 +273,8 @@ class LinDynamicMaster : public LinNode void ReceiveFrameStatus(ILinController* /*controller*/, const LinFrameStatusEvent& frameStatusEvent) { - Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status << " timestamp=" << frameStatusEvent.timestamp; + Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status + << " timestamp=" << frameStatusEvent.timestamp; _result.receivedFrames[frameStatusEvent.status].push_back(frameStatusEvent.frame); _result.receiveTimes.push_back(frameStatusEvent.timestamp); @@ -283,7 +291,8 @@ class LinDynamicMaster : public LinNode Stop(); } - void OnFrameHeader(ILinController* linController, const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& header) + void OnFrameHeader(ILinController* linController, + const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& header) { Log() << ">> " << _name << " received frame header: id=" << (int)header.id << "@" << header.timestamp; @@ -348,7 +357,7 @@ class LinMaster : public LinNode frame.id = 17; frame.checksumModel = LinChecksumModel::Classic; frame.dataLength = 6; - frame.data = std::array{1,7,1,7,1,7,1,7}; + frame.data = std::array{1, 7, 1, 7, 1, 7, 1, 7}; _result.sendTimes.push_back(now); controller->SendFrame(frame, LinFrameResponseType::MasterResponse); @@ -400,7 +409,8 @@ class LinMaster : public LinNode void ReceiveFrameStatus(ILinController* /*controller*/, const LinFrameStatusEvent& frameStatusEvent) { - Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status << " timestamp=" << frameStatusEvent.timestamp; + Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status + << " timestamp=" << frameStatusEvent.timestamp; _result.receivedFrames[frameStatusEvent.status].push_back(frameStatusEvent.frame); _result.receiveTimes.push_back(frameStatusEvent.timestamp); @@ -439,7 +449,7 @@ class LinDynamicSlave : public LinNode { public: LinDynamicSlave(std::string participantName, IParticipant* participant, ILinController* controller, - Orchestration::ILifecycleService* lifecycleService) + Orchestration::ILifecycleService* lifecycleService) : LinNode(participant, controller, participantName, lifecycleService) , _slaveResponses{MakeSlaveResponses()} { @@ -453,7 +463,8 @@ class LinDynamicSlave : public LinNode void FrameStatusHandler(ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status << " timestamp=" << frameStatusEvent.timestamp; + Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status + << " timestamp=" << frameStatusEvent.timestamp; _result.receivedFrames[frameStatusEvent.status].push_back(frameStatusEvent.frame); @@ -472,16 +483,16 @@ class LinDynamicSlave : public LinNode Log() << ">> " << _name << " received goto sleep command"; // wakeup in 10 ms - timer.Set(now + 10ms, - [linController](std::chrono::nanoseconds /*now*/) { - linController->Wakeup(); - // The LIN slave doesn't receive the wakeup pulse sent by himself in a trivial simulation (without netsim) - }); + timer.Set(now + 10ms, [linController](std::chrono::nanoseconds /*now*/) { + linController->Wakeup(); + // The LIN slave doesn't receive the wakeup pulse sent by himself in a trivial simulation (without netsim) + }); linController->GoToSleepInternal(); _result.gotoSleepReceived = true; } - void OnFrameHeader(ILinController* linController, const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& header) + void OnFrameHeader(ILinController* linController, + const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& header) { Log() << ">> " << _name << " received frame header: id=" << (int)header.id << "@" << header.timestamp; @@ -509,7 +520,7 @@ class LinSlave : public LinNode { public: LinSlave(std::string participantName, IParticipant* participant, ILinController* controller, - Orchestration::ILifecycleService* lifecycleService) + Orchestration::ILifecycleService* lifecycleService) : LinNode(participant, controller, participantName, lifecycleService) { } @@ -522,7 +533,8 @@ class LinSlave : public LinNode void FrameStatusHandler(ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status << " timestamp=" << frameStatusEvent.timestamp; + Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status + << " timestamp=" << frameStatusEvent.timestamp; _result.receivedFrames[frameStatusEvent.status].push_back(frameStatusEvent.frame); @@ -652,7 +664,7 @@ class ITest_LinDynamicResponse : public testing::Test TEST_F(ITest_LinDynamicResponse, deferred_simstep_response) { auto registryUri = MakeTestRegistryUri(); - auto participantNames = std::vector{ "LinMaster", "LinSlave1" }; + auto participantNames = std::vector{"LinMaster", "LinSlave1"}; _simTestHarness = std::make_unique(participantNames, registryUri, false); @@ -675,10 +687,11 @@ TEST_F(ITest_LinDynamicResponse, deferred_simstep_response) // LinMaster ////////////////////////////////////////////////////////////////////// - enum class State { + enum class State + { Sending, WaitingForResponse, - } state{ State::Sending }; + } state{State::Sending}; { auto&& participant = _simTestHarness->GetParticipant("LinMaster")->Participant(); @@ -690,27 +703,25 @@ TEST_F(ITest_LinDynamicResponse, deferred_simstep_response) auto config = MakeDynamicSlaveConfig(); config.controllerMode = LinControllerMode::Master; SilKit::Experimental::Services::Lin::InitDynamic(linController, config); - }); + }); - linController->AddFrameStatusHandler( - [&](auto /*linController*/, auto frameStatusEvent) { - Log() << "Received frameStatusEvent @" << frameStatusEvent.timestamp; - if (frameStatusEvent.frame == slaveResponseFrame) - { - state = State::Sending; - } - }); + linController->AddFrameStatusHandler([&](auto /*linController*/, auto frameStatusEvent) { + Log() << "Received frameStatusEvent @" << frameStatusEvent.timestamp; + if (frameStatusEvent.frame == slaveResponseFrame) + { + state = State::Sending; + } + }); - timeSyncService->SetSimulationStepHandler( - [&, linController](auto now, auto /*duration*/) { - if(state == State::Sending) - { - Log() << "Sending master frame request @" << now; - linController->SendFrameHeader(masterFrame.id); - sentTimes.push_back(now); - state = State::WaitingForResponse; - } - }, 1ms); + timeSyncService->SetSimulationStepHandler([&, linController](auto now, auto /*duration*/) { + if (state == State::Sending) + { + Log() << "Sending master frame request @" << now; + linController->SendFrameHeader(masterFrame.id); + sentTimes.push_back(now); + state = State::WaitingForResponse; + } + }, 1ms); } ////////////////////////////////////////////////////////////////////// @@ -727,29 +738,30 @@ TEST_F(ITest_LinDynamicResponse, deferred_simstep_response) lifecycleService->SetCommunicationReadyHandler([linController]() { auto config = MakeDynamicSlaveConfig(); SilKit::Experimental::Services::Lin::InitDynamic(linController, config); - }); + }); timeSyncService->SetSimulationStepHandler( - [lifecycleService, linController, &headerReceived, &slaveResponseFrame, &responseTimes]( - auto now, auto /*duration*/) { - //Send response delayed by 2ms - if (now == ( headerReceived + 2ms)) + [lifecycleService, linController, &headerReceived, &slaveResponseFrame, &responseTimes](auto now, + auto /*duration*/) { + //Send response delayed by 2ms + if (now == (headerReceived + 2ms)) + { + SilKit::Experimental::Services::Lin::SendDynamicResponse(linController, slaveResponseFrame); + responseTimes.push_back(now); + if (responseTimes.size() == MAX_RESPONSES) { - SilKit::Experimental::Services::Lin::SendDynamicResponse(linController, slaveResponseFrame); - responseTimes.push_back(now); - if (responseTimes.size() == MAX_RESPONSES) - { - lifecycleService->Stop("Test done"); - } - headerReceived = 0ms; //reset + lifecycleService->Stop("Test done"); } - }, 1ms); + headerReceived = 0ms; //reset + } + }, + 1ms); - SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( - linController, [&](auto&& /*controller*/, auto&& event) { - Log() << "LinSlave1: Got Frame Header @" << event.timestamp; - headerReceived = event.timestamp; - }); + SilKit::Experimental::Services::Lin::AddFrameHeaderHandler(linController, + [&](auto&& /*controller*/, auto&& event) { + Log() << "LinSlave1: Got Frame Header @" << event.timestamp; + headerReceived = event.timestamp; + }); } //Run the test @@ -760,7 +772,7 @@ TEST_F(ITest_LinDynamicResponse, deferred_simstep_response) TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) { auto registryUri = MakeTestRegistryUri(); - std::vector participantNames = { "LinMaster", "LinSlave" }; + std::vector participantNames = {"LinMaster", "LinSlave"}; _simTestHarness = std::make_unique(participantNames, registryUri, false); std::vector> linNodes; @@ -772,8 +784,7 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) { const std::string participantName = "LinMaster"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); lifecycleService->SetCommunicationReadyHandler([participantName, linController]() { @@ -785,17 +796,17 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) linController->AddFrameStatusHandler( [master = master.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master->ReceiveFrameStatus(linController, frameStatusEvent); - }); + master->ReceiveFrameStatus(linController, frameStatusEvent); + }); linController->AddWakeupHandler( [master = master.get()](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - master->WakeupHandler(linController, wakeupEvent); - }); + master->WakeupHandler(linController, wakeupEvent); + }); timeSyncService->SetSimulationStepHandler( [master = master.get(), participantName](auto now, std::chrono::nanoseconds /*duration*/) { - master->doAction(now); - }, 1ms); + master->doAction(now); + }, 1ms); linNodes.emplace_back(std::move(master)); } @@ -805,8 +816,7 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) { const std::string participantName = "LinSlave"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); @@ -826,15 +836,12 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) }); timeSyncService->SetSimulationStepHandler( - [slave = slave.get()](auto now, auto /*duration*/) { - slave->DoAction(now); - }, 1ms); + [slave = slave.get()](auto now, auto /*duration*/) { slave->DoAction(now); }, 1ms); // Dynamic Response API starts here SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( - linController, [slave = slave.get()](auto&& controller, auto&& event) { - slave->OnFrameHeader(controller, event); - }); + linController, + [slave = slave.get()](auto&& controller, auto&& event) { slave->OnFrameHeader(controller, event); }); linNodes.emplace_back(std::move(slave)); } @@ -844,20 +851,19 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) // Sim is stopped when master received the wakeup pulse - for (auto& node: linNodes) + for (auto& node : linNodes) { if (node->_name == "LinSlave") { EXPECT_EQ(node->_result.numberReceivedInSleep, 0u); EXPECT_TRUE(node->_result.gotoSleepReceived) - << "Assuming node " << node->_name << " has received a GoToSleep"; + << "Assuming node " << node->_name << " has received a GoToSleep"; // The LIN slave doesn't receive the wakeup pulse sent by himself in a trivial simulation (without netsim), // so don't expect a wakeup } else { - EXPECT_TRUE(node->_result.gotoSleepSent) - << "Assuming node " << node->_name << " has received a GoToSleep"; + EXPECT_TRUE(node->_result.gotoSleepSent) << "Assuming node " << node->_name << " has received a GoToSleep"; EXPECT_TRUE(node->_result.wakeupReceived) << "Assuming node " << node->_name << " has received a Wakeup"; } } @@ -869,8 +875,8 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) EXPECT_GT(masterSendTimes.size(), 0u); EXPECT_GT(masterRecvTimes.size(), 0u); ASSERT_EQ(masterSendTimes.size(), masterRecvTimes.size()) - << "The master send times and receive times should have equal size."; - for(auto i = 0u; i< masterRecvTimes.size(); i++) + << "The master send times and receive times should have equal size."; + for (auto i = 0u; i < masterRecvTimes.size(); i++) { const auto& sendT = masterSendTimes.at(i); const auto& recvT = masterRecvTimes.at(i); @@ -915,7 +921,8 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].id, 60); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].dataLength, 8); - EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 2 frame states on dynamic slave ASSERT_EQ(slaveRecvFrames.size(), 2); @@ -941,7 +948,8 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].id, 60); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].dataLength, 8); - EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 1x TX_OK for id 34 on dynamic slave ASSERT_EQ(slaveRecvFrames[LinFrameStatus::LIN_TX_OK].size(), 1); @@ -954,7 +962,7 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave) TEST_F(ITest_LinDynamicResponse, normal_master_two_dynamic_slave_collision) { auto registryUri = MakeTestRegistryUri(); - std::vector participantNames = { "LinMaster", "LinSlave1", "LinSlave2" }; + std::vector participantNames = {"LinMaster", "LinSlave1", "LinSlave2"}; _simTestHarness = std::make_unique(participantNames, registryUri, false); std::vector> linNodes; @@ -975,21 +983,21 @@ TEST_F(ITest_LinDynamicResponse, normal_master_two_dynamic_slave_collision) linController->Init(config); }); - auto master = std::make_unique( participant, linController, lifecycleService); + auto master = std::make_unique(participant, linController, lifecycleService); linController->AddFrameStatusHandler( [master = master.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master->ReceiveFrameStatus(linController, frameStatusEvent); - }); + master->ReceiveFrameStatus(linController, frameStatusEvent); + }); linController->AddWakeupHandler( [master = master.get()](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - master->WakeupHandler(linController, wakeupEvent); - }); + master->WakeupHandler(linController, wakeupEvent); + }); timeSyncService->SetSimulationStepHandler( [master = master.get(), participantName](auto now, std::chrono::nanoseconds /*duration*/) { - master->doAction(now); - }, 1ms); + master->doAction(now); + }, 1ms); linNodes.emplace_back(std::move(master)); } @@ -1020,15 +1028,12 @@ TEST_F(ITest_LinDynamicResponse, normal_master_two_dynamic_slave_collision) }); timeSyncService->SetSimulationStepHandler( - [slave = slave.get()](auto now, auto /*duration*/) { - slave->DoAction(now); - }, 1ms); + [slave = slave.get()](auto now, auto /*duration*/) { slave->DoAction(now); }, 1ms); // Dynamic Response API starts here SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( - linController, [slave = slave.get()](auto&& controller, auto&& event) { - slave->OnFrameHeader(controller, event); - }); + linController, + [slave = slave.get()](auto&& controller, auto&& event) { slave->OnFrameHeader(controller, event); }); linNodes.emplace_back(std::move(slave)); } @@ -1059,15 +1064,12 @@ TEST_F(ITest_LinDynamicResponse, normal_master_two_dynamic_slave_collision) }); timeSyncService->SetSimulationStepHandler( - [slave = slave.get()](auto now, auto /*duration*/) { - slave->DoAction(now); - }, 1ms); + [slave = slave.get()](auto now, auto /*duration*/) { slave->DoAction(now); }, 1ms); // Dynamic Response API starts here SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( - linController, [slave = slave.get()](auto&& controller, auto&& event) { - slave->OnFrameHeader(controller, event); - }); + linController, + [slave = slave.get()](auto&& controller, auto&& event) { slave->OnFrameHeader(controller, event); }); linNodes.emplace_back(std::move(slave)); } @@ -1117,7 +1119,8 @@ TEST_F(ITest_LinDynamicResponse, normal_master_two_dynamic_slave_collision) EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].id, 60); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].dataLength, 8); - EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 2 frame states on dynamic slave 1 ASSERT_EQ(slave1RecvFrames.size(), 2); @@ -1147,7 +1150,8 @@ TEST_F(ITest_LinDynamicResponse, normal_master_two_dynamic_slave_collision) EXPECT_EQ(slave1RecvFrames[LinFrameStatus::LIN_RX_OK][5].id, 60); EXPECT_EQ(slave1RecvFrames[LinFrameStatus::LIN_RX_OK][5].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(slave1RecvFrames[LinFrameStatus::LIN_RX_OK][5].dataLength, 8); - EXPECT_EQ(slave1RecvFrames[LinFrameStatus::LIN_RX_OK][5].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(slave1RecvFrames[LinFrameStatus::LIN_RX_OK][5].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 1x TX_OK for id 34 on dynamic slave 1 ASSERT_EQ(slave1RecvFrames[LinFrameStatus::LIN_TX_OK].size(), 1); @@ -1184,7 +1188,8 @@ TEST_F(ITest_LinDynamicResponse, normal_master_two_dynamic_slave_collision) EXPECT_EQ(slave2RecvFrames[LinFrameStatus::LIN_RX_OK][5].id, 60); EXPECT_EQ(slave2RecvFrames[LinFrameStatus::LIN_RX_OK][5].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(slave2RecvFrames[LinFrameStatus::LIN_RX_OK][5].dataLength, 8); - EXPECT_EQ(slave2RecvFrames[LinFrameStatus::LIN_RX_OK][5].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(slave2RecvFrames[LinFrameStatus::LIN_RX_OK][5].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 1x TX_OK for id 34 on dynamic slave 2 ASSERT_EQ(slave2RecvFrames[LinFrameStatus::LIN_TX_OK].size(), 1); @@ -1201,7 +1206,7 @@ TEST_F(ITest_LinDynamicResponse, normal_master_two_dynamic_slave_collision) TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) { auto registryUri = MakeTestRegistryUri(); - std::vector participantNames = { "LinMaster", "LinSlave" }; + std::vector participantNames = {"LinMaster", "LinSlave"}; _simTestHarness = std::make_unique(participantNames, registryUri, false); std::vector> linNodes; @@ -1213,8 +1218,7 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) { const std::string participantName = "LinMaster"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); @@ -1227,23 +1231,22 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) linController->AddFrameStatusHandler( [master = master.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master->ReceiveFrameStatus(linController, frameStatusEvent); - }); + master->ReceiveFrameStatus(linController, frameStatusEvent); + }); linController->AddWakeupHandler( [master = master.get()](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - master->WakeupHandler(linController, wakeupEvent); - }); + master->WakeupHandler(linController, wakeupEvent); + }); timeSyncService->SetSimulationStepHandler( [master = master.get(), participantName](auto now, std::chrono::nanoseconds /*duration*/) { - master->doAction(now); - }, 1ms); + master->doAction(now); + }, 1ms); // Dynamic Response API starts here SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( - linController, [master = master.get()](auto&& controller, auto&& event) { - master->OnFrameHeader(controller, event); - }); + linController, + [master = master.get()](auto&& controller, auto&& event) { master->OnFrameHeader(controller, event); }); linNodes.emplace_back(std::move(master)); } @@ -1254,8 +1257,7 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) { const std::string participantName = "LinSlave"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); @@ -1266,19 +1268,15 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) auto slave = std::make_unique(participantName, participant, linController, lifecycleService); - linController->AddFrameStatusHandler( - [slave = slave.get()](auto&& linController, auto&& frameStatusEvent) { - slave->FrameStatusHandler(linController, frameStatusEvent); - }); - linController->AddGoToSleepHandler( - [slave = slave.get()](auto&& linController, auto&& goToSleepEvent) { - slave->GoToSleepHandler(linController, goToSleepEvent); - }); + linController->AddFrameStatusHandler([slave = slave.get()](auto&& linController, auto&& frameStatusEvent) { + slave->FrameStatusHandler(linController, frameStatusEvent); + }); + linController->AddGoToSleepHandler([slave = slave.get()](auto&& linController, auto&& goToSleepEvent) { + slave->GoToSleepHandler(linController, goToSleepEvent); + }); timeSyncService->SetSimulationStepHandler( - [slave = slave.get()](auto now, auto /*duration*/) { - slave->DoAction(now); - }, 1ms); + [slave = slave.get()](auto now, auto /*duration*/) { slave->DoAction(now); }, 1ms); linNodes.emplace_back(std::move(slave)); } @@ -1289,20 +1287,19 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) // Sim is stopped when master received the wakeup pulse - for (auto& node: linNodes) + for (auto& node : linNodes) { if (node->_name == "LinSlave") { EXPECT_EQ(node->_result.numberReceivedInSleep, 0u); EXPECT_TRUE(node->_result.gotoSleepReceived) - << "Assuming node " << node->_name << " has received a GoToSleep"; + << "Assuming node " << node->_name << " has received a GoToSleep"; // The LIN slave doesn't receive the wakeup pulse sent by himself in a trivial simulation (without netsim), // so don't expect a wakeup } else { - EXPECT_TRUE(node->_result.gotoSleepSent) - << "Assuming node " << node->_name << " has received a GoToSleep"; + EXPECT_TRUE(node->_result.gotoSleepSent) << "Assuming node " << node->_name << " has received a GoToSleep"; EXPECT_TRUE(node->_result.wakeupReceived) << "Assuming node " << node->_name << " has received a Wakeup"; } } @@ -1314,8 +1311,8 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) EXPECT_GT(masterSendTimes.size(), 0u); EXPECT_GT(masterRecvTimes.size(), 0u); ASSERT_EQ(masterSendTimes.size(), masterRecvTimes.size()) - << "The master send times and receive times should have equal size."; - for(auto i = 0u; i< masterRecvTimes.size(); i++) + << "The master send times and receive times should have equal size."; + for (auto i = 0u; i < masterRecvTimes.size(); i++) { const auto& sendT = masterSendTimes.at(i); const auto& recvT = masterRecvTimes.at(i); @@ -1360,7 +1357,8 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].id, 60); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].dataLength, 8); - EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 3 frame states on slave RX_OK,RX_ERROR,TX_OK ASSERT_EQ(slaveRecvFrames.size(), 3); @@ -1374,7 +1372,8 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][1].id, 60); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][1].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][1].dataLength, 8); - EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][1].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][1].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 2x RX_ERROR for id 18,19 on slave ASSERT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_ERROR].size(), 2); @@ -1400,7 +1399,7 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_normal_slave) TEST_F(ITest_LinDynamicResponse, dynamic_master_dynamic_slave) { auto registryUri = MakeTestRegistryUri(); - std::vector participantNames = { "LinMaster", "LinSlave" }; + std::vector participantNames = {"LinMaster", "LinSlave"}; _simTestHarness = std::make_unique(participantNames, registryUri, false); std::vector> linNodes; @@ -1412,37 +1411,35 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_dynamic_slave) { const std::string participantName = "LinMaster"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); lifecycleService->SetCommunicationReadyHandler([participantName, linController]() { - auto config = MakeDynamicMasterConfig(); - SilKit::Experimental::Services::Lin::InitDynamic(linController, config); + auto config = MakeDynamicMasterConfig(); + SilKit::Experimental::Services::Lin::InitDynamic(linController, config); }); auto master = std::make_unique(participant, linController, lifecycleService); linController->AddFrameStatusHandler( [master = master.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master->ReceiveFrameStatus(linController, frameStatusEvent); - }); + master->ReceiveFrameStatus(linController, frameStatusEvent); + }); linController->AddWakeupHandler( [master = master.get()](ILinController* linController, const LinWakeupEvent& wakeupEvent) { - master->WakeupHandler(linController, wakeupEvent); - }); + master->WakeupHandler(linController, wakeupEvent); + }); timeSyncService->SetSimulationStepHandler( [master = master.get(), participantName](auto now, std::chrono::nanoseconds /*duration*/) { - master->doAction(now); - }, 1ms); + master->doAction(now); + }, 1ms); // Dynamic Response API starts here SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( - linController, [master = master.get()](auto&& controller, auto&& event) { - master->OnFrameHeader(controller, event); - }); + linController, + [master = master.get()](auto&& controller, auto&& event) { master->OnFrameHeader(controller, event); }); linNodes.emplace_back(std::move(master)); } @@ -1453,37 +1450,31 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_dynamic_slave) { const std::string participantName = "LinSlave"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); lifecycleService->SetCommunicationReadyHandler([linController]() { - auto config = MakeDynamicSlaveConfig(); - SilKit::Experimental::Services::Lin::InitDynamic(linController, config); + auto config = MakeDynamicSlaveConfig(); + SilKit::Experimental::Services::Lin::InitDynamic(linController, config); }); auto slave = std::make_unique(participantName, participant, linController, lifecycleService); - linController->AddFrameStatusHandler( - [slave = slave.get()](auto&& linController, auto&& frameStatusEvent) { - slave->FrameStatusHandler(linController, frameStatusEvent); - }); - linController->AddGoToSleepHandler( - [slave = slave.get()](auto&& linController, auto&& goToSleepEvent) { - slave->GoToSleepHandler(linController, goToSleepEvent); - }); + linController->AddFrameStatusHandler([slave = slave.get()](auto&& linController, auto&& frameStatusEvent) { + slave->FrameStatusHandler(linController, frameStatusEvent); + }); + linController->AddGoToSleepHandler([slave = slave.get()](auto&& linController, auto&& goToSleepEvent) { + slave->GoToSleepHandler(linController, goToSleepEvent); + }); timeSyncService->SetSimulationStepHandler( - [slave = slave.get()](auto now, auto /*duration*/) { - slave->DoAction(now); - }, 1ms); + [slave = slave.get()](auto now, auto /*duration*/) { slave->DoAction(now); }, 1ms); // Dynamic Response API starts here SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( - linController, [slave = slave.get()](auto&& controller, auto&& event) { - slave->OnFrameHeader(controller, event); - }); + linController, + [slave = slave.get()](auto&& controller, auto&& event) { slave->OnFrameHeader(controller, event); }); linNodes.emplace_back(std::move(slave)); } @@ -1493,20 +1484,19 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_dynamic_slave) // Sim is stopped when master received the wakeup pulse - for (auto& node: linNodes) + for (auto& node : linNodes) { if (node->_name == "LinSlave") { EXPECT_EQ(node->_result.numberReceivedInSleep, 0u); EXPECT_TRUE(node->_result.gotoSleepReceived) - << "Assuming node " << node->_name << " has received a GoToSleep"; + << "Assuming node " << node->_name << " has received a GoToSleep"; // The LIN slave doesn't receive the wakeup pulse sent by himself in a trivial simulation (without netsim), // so don't expect a wakeup } else { - EXPECT_TRUE(node->_result.gotoSleepSent) - << "Assuming node " << node->_name << " has received a GoToSleep"; + EXPECT_TRUE(node->_result.gotoSleepSent) << "Assuming node " << node->_name << " has received a GoToSleep"; EXPECT_TRUE(node->_result.wakeupReceived) << "Assuming node " << node->_name << " has received a Wakeup"; } } @@ -1518,8 +1508,8 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_dynamic_slave) EXPECT_GT(masterSendTimes.size(), 0u); EXPECT_GT(masterRecvTimes.size(), 0u); ASSERT_EQ(masterSendTimes.size(), masterRecvTimes.size()) - << "The master send times and receive times should have equal size."; - for(auto i = 0u; i< masterRecvTimes.size(); i++) + << "The master send times and receive times should have equal size."; + for (auto i = 0u; i < masterRecvTimes.size(); i++) { const auto& sendT = masterSendTimes.at(i); const auto& recvT = masterRecvTimes.at(i); @@ -1564,7 +1554,8 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_dynamic_slave) EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].id, 60); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].dataLength, 8); - EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_TX_OK][4].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 2 frame states on dynamic slave ASSERT_EQ(slaveRecvFrames.size(), 2); @@ -1590,7 +1581,8 @@ TEST_F(ITest_LinDynamicResponse, dynamic_master_dynamic_slave) EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].id, 60); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].checksumModel, LinChecksumModel::Classic); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].dataLength, 8); - EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].data, (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); + EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_RX_OK][4].data, + (std::array{0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF})); // 1x TX_OK for id 34 on dynamic slave ASSERT_EQ(slaveRecvFrames[LinFrameStatus::LIN_TX_OK].size(), 1); @@ -1649,9 +1641,12 @@ class LinMasterCheckResponseResets : public LinNode { switch (frameStatusEvent.status) { - case LinFrameStatus::LIN_RX_OK: break; // good case, no need to warn - case LinFrameStatus::LIN_TX_OK: break; // good case, no need to warn - default: Log() << "WARNING: LIN transmission failed!"; + case LinFrameStatus::LIN_RX_OK: + break; // good case, no need to warn + case LinFrameStatus::LIN_TX_OK: + break; // good case, no need to warn + default: + Log() << "WARNING: LIN transmission failed!"; } Log() << ">> " << _name << " " << frameStatusEvent.frame << " status=" << frameStatusEvent.status @@ -1668,8 +1663,8 @@ class LinMasterCheckResponseResets : public LinNode class LinDynamicSlaveCheckResponseResets : public LinNode { public: - LinDynamicSlaveCheckResponseResets(std::string participantName, IParticipant* participant, ILinController* controller, - Orchestration::ILifecycleService* lifecycleService) + LinDynamicSlaveCheckResponseResets(std::string participantName, IParticipant* participant, + ILinController* controller, Orchestration::ILifecycleService* lifecycleService) : LinNode(participant, controller, participantName, lifecycleService) , _slaveResponses{MakeSlaveResponses()} { @@ -1762,15 +1757,14 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_response_resets) linController->AddFrameStatusHandler( [master = master.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master->ReceiveFrameStatus(linController, frameStatusEvent); - }); + master->ReceiveFrameStatus(linController, frameStatusEvent); + }); timeSyncService->SetSimulationStepHandler( [master = master.get(), participantName](auto now, std::chrono::nanoseconds /*duration*/) { - Log() << participantName << " now=" << now.count() << "ns"; - master->doAction(now); - }, - 1ms); + Log() << participantName << " now=" << now.count() << "ns"; + master->doAction(now); + }, 1ms); linNodes.emplace_back(std::move(master)); } @@ -1792,24 +1786,22 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_response_resets) SilKit::Experimental::Services::Lin::InitDynamic(linController, config); }); - auto slave = std::make_unique(participantName, participant, linController, lifecycleService); + auto slave = std::make_unique(participantName, participant, linController, + lifecycleService); linController->AddFrameStatusHandler([slave = slave.get()](auto&& linController, auto&& frameStatusEvent) { slave->FrameStatusHandler(linController, frameStatusEvent); }); - timeSyncService->SetSimulationStepHandler( - [slave = slave.get()](auto now, auto /*duration*/) { - Log() << "now=" << std::chrono::duration_cast(now).count() << "ms"; - slave->DoAction(now); - }, - 1ms); + timeSyncService->SetSimulationStepHandler([slave = slave.get()](auto now, auto /*duration*/) { + Log() << "now=" << std::chrono::duration_cast(now).count() << "ms"; + slave->DoAction(now); + }, 1ms); // Dynamic Response API starts here SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( - linController, [slave = slave.get()](auto&& controller, auto&& event) { - slave->OnFrameHeader(controller, event); - }); + linController, + [slave = slave.get()](auto&& controller, auto&& event) { slave->OnFrameHeader(controller, event); }); linNodes.emplace_back(std::move(slave)); } @@ -1830,7 +1822,8 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_response_resets) // 1x RX_OK for id 34 on master ASSERT_EQ(masterRecvFrames[LinFrameStatus::LIN_RX_OK].size(), 1); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_RX_OK][0].id, 34); - EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_RX_OK][0].checksumModel, SilKit::Services::Lin::LinChecksumModel::Enhanced); + EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_RX_OK][0].checksumModel, + SilKit::Services::Lin::LinChecksumModel::Enhanced); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_RX_OK][0].dataLength, 6); EXPECT_EQ(masterRecvFrames[LinFrameStatus::LIN_RX_OK][0].data, (std::array{3, 4, 3, 4, 3, 4, 3, 4})); @@ -1844,7 +1837,8 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_response_resets) // 1x TX_OK for id 34 on dynamic slave ASSERT_EQ(slaveRecvFrames[LinFrameStatus::LIN_TX_OK].size(), 1); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_TX_OK][0].id, 34); - EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_TX_OK][0].checksumModel, SilKit::Services::Lin::LinChecksumModel::Enhanced); + EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_TX_OK][0].checksumModel, + SilKit::Services::Lin::LinChecksumModel::Enhanced); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_TX_OK][0].dataLength, 6); EXPECT_EQ(slaveRecvFrames[LinFrameStatus::LIN_TX_OK][0].data, (std::array{3, 4, 3, 4, 3, 4, 3, 4})); @@ -1856,7 +1850,7 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_response_resets) TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_out_of_band_response_does_nothing) { auto registryUri = MakeTestRegistryUri(); - std::vector participantNames = { "LinMaster", "LinSlave", "LinSlaveDynamic" }; + std::vector participantNames = {"LinMaster", "LinSlave", "LinSlaveDynamic"}; _simTestHarness = std::make_unique(participantNames, registryUri, false); std::vector> linNodes; @@ -1868,29 +1862,28 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_out_of_band_respons { const std::string participantName = "LinMaster"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); lifecycleService->SetCommunicationReadyHandler([participantName, linController]() { - auto config = MakeMasterConfig(); - linController->Init(config); + auto config = MakeMasterConfig(); + linController->Init(config); }); auto master = std::make_unique(participant, linController, lifecycleService); linController->AddFrameStatusHandler( [master = master.get()](ILinController* linController, const LinFrameStatusEvent& frameStatusEvent) { - master->ReceiveFrameStatus(linController, frameStatusEvent); - }); + master->ReceiveFrameStatus(linController, frameStatusEvent); + }); timeSyncService->SetSimulationStepHandler( [lifecycleService, participantName](auto now, std::chrono::nanoseconds /*duration*/) { - if (now == 30ms) - { - lifecycleService->Stop("done"); - } - }, 1ms); + if (now == 30ms) + { + lifecycleService->Stop("done"); + } + }, 1ms); linNodes.emplace_back(std::move(master)); } @@ -1901,8 +1894,7 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_out_of_band_respons { const std::string participantName = "LinSlave"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); @@ -1917,21 +1909,20 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_out_of_band_respons slave->FrameStatusHandler(linController, frameStatusEvent); }); - timeSyncService->SetSimulationStepHandler( - [linController](auto now, auto /*duration*/) { - Log() << "now=" << std::chrono::duration_cast(now).count() << "ms"; + timeSyncService->SetSimulationStepHandler([linController](auto now, auto /*duration*/) { + Log() << "now=" << std::chrono::duration_cast(now).count() << "ms"; - LinFrame frame{}; - frame.id = 34; - frame.checksumModel = SilKit::Services::Lin::LinChecksumModel::Enhanced; - frame.dataLength = 6; - frame.data = std::array{1, 2, 3, 4, 5, 6, 0, 0}; + LinFrame frame{}; + frame.id = 34; + frame.checksumModel = SilKit::Services::Lin::LinChecksumModel::Enhanced; + frame.dataLength = 6; + frame.data = std::array{1, 2, 3, 4, 5, 6, 0, 0}; - if (now == 10ms || now == 20ms) - { - SilKit::Experimental::Services::Lin::SendDynamicResponse(linController, frame); - } - }, 1ms); + if (now == 10ms || now == 20ms) + { + SilKit::Experimental::Services::Lin::SendDynamicResponse(linController, frame); + } + }, 1ms); linNodes.emplace_back(std::move(slave)); } @@ -1942,8 +1933,7 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_out_of_band_respons { const std::string participantName = "LinSlaveDynamic"; auto&& participant = _simTestHarness->GetParticipant(participantName)->Participant(); - auto&& lifecycleService = - _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); + auto&& lifecycleService = _simTestHarness->GetParticipant(participantName)->GetOrCreateLifecycleService(); auto&& timeSyncService = _simTestHarness->GetParticipant(participantName)->GetOrCreateTimeSyncService(); auto&& linController = participant->CreateLinController("LinController1", "LIN_1"); @@ -1958,10 +1948,9 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_out_of_band_respons slave->FrameStatusHandler(linController, frameStatusEvent); }); - timeSyncService->SetSimulationStepHandler( - [](auto now, auto /*duration*/) { - Log() << "now=" << std::chrono::duration_cast(now).count() << "ms"; - }, 1ms); + timeSyncService->SetSimulationStepHandler([](auto now, auto /*duration*/) { + Log() << "now=" << std::chrono::duration_cast(now).count() << "ms"; + }, 1ms); linNodes.emplace_back(std::move(slave)); } @@ -2001,11 +1990,13 @@ TEST_F(ITest_LinDynamicResponse, normal_master_dynamic_slave_out_of_band_respons EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][0].id, 34); EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][0].checksumModel, LinChecksumModel::Enhanced); EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][0].dataLength, 6); - EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][0].data, (std::array{1, 2, 3, 4, 5, 6, 0, 0})); + EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][0].data, + (std::array{1, 2, 3, 4, 5, 6, 0, 0})); EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][1].id, 34); EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][1].checksumModel, LinChecksumModel::Enhanced); EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][1].dataLength, 6); - EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][1].data, (std::array{1, 2, 3, 4, 5, 6, 0, 0})); + EXPECT_EQ(slaveDynamicRecvFrames[LinFrameStatus::LIN_RX_OK][1].data, + (std::array{1, 2, 3, 4, 5, 6, 0, 0})); // Known Issue (Trivial Simulation): // diff --git a/SilKit/IntegrationTests/ITest_MultiSim.cpp b/SilKit/IntegrationTests/ITest_MultiSim.cpp index bcbe337ec..adb2ae1e3 100644 --- a/SilKit/IntegrationTests/ITest_MultiSim.cpp +++ b/SilKit/IntegrationTests/ITest_MultiSim.cpp @@ -128,13 +128,11 @@ struct Simulation SilKit::Services::Orchestration::LifecycleConfiguration{ SilKit::Services::Orchestration::OperationMode::Coordinated}); - systemController.lifecycleService->SetCommunicationReadyHandler([systemController = &systemController] { - systemController->comReadyPromise.set_value(); - }); + systemController.lifecycleService->SetCommunicationReadyHandler( + [systemController = &systemController] { systemController->comReadyPromise.set_value(); }); - systemController.lifecycleService->SetStartingHandler([systemController = &systemController] { - systemController->startingPromise.set_value(); - }); + systemController.lifecycleService->SetStartingHandler( + [systemController = &systemController] { systemController->startingPromise.set_value(); }); systemController.comReadyFuture = systemController.comReadyPromise.get_future(); systemController.startingFuture = systemController.startingPromise.get_future(); @@ -153,13 +151,11 @@ struct Simulation publisher->participant->CreateLifecycleService(SilKit::Services::Orchestration::LifecycleConfiguration{ SilKit::Services::Orchestration::OperationMode::Coordinated}); - publisher->lifecycleService->SetCommunicationReadyHandler([publisher = publisher.get()] { - publisher->comReadyPromise.set_value(); - }); + publisher->lifecycleService->SetCommunicationReadyHandler( + [publisher = publisher.get()] { publisher->comReadyPromise.set_value(); }); - publisher->lifecycleService->SetStartingHandler([publisher = publisher.get()] { - publisher->startingPromise.set_value(); - }); + publisher->lifecycleService->SetStartingHandler( + [publisher = publisher.get()] { publisher->startingPromise.set_value(); }); publisher->comReadyFuture = publisher->comReadyPromise.get_future(); publisher->startingFuture = publisher->startingPromise.get_future(); @@ -190,13 +186,11 @@ struct Simulation subscriber->participant->CreateLifecycleService(SilKit::Services::Orchestration::LifecycleConfiguration{ SilKit::Services::Orchestration::OperationMode::Coordinated}); - subscriber->lifecycleService->SetCommunicationReadyHandler([subscriber = subscriber.get()] { - subscriber->comReadyPromise.set_value(); - }); + subscriber->lifecycleService->SetCommunicationReadyHandler( + [subscriber = subscriber.get()] { subscriber->comReadyPromise.set_value(); }); - subscriber->lifecycleService->SetStartingHandler([subscriber = subscriber.get()] { - subscriber->startingPromise.set_value(); - }); + subscriber->lifecycleService->SetStartingHandler( + [subscriber = subscriber.get()] { subscriber->startingPromise.set_value(); }); subscriber->comReadyFuture = subscriber->comReadyPromise.get_future(); subscriber->startingFuture = subscriber->startingPromise.get_future(); @@ -208,20 +202,20 @@ struct Simulation "Subscriber", spec, [subscriber = subscriber.get()](SilKit::Services::PubSub::IDataSubscriber*, const SilKit::Services::PubSub::DataMessageEvent& event) { - if (event.data.size() != subscriber->message.size()) - { - subscriber->receivedDataPromise.set_exception( - std::make_exception_ptr(std::runtime_error{"invalid message size"})); - } - - if (!ItemsAreEqual(event.data, SilKit::Util::ToSpan(subscriber->message))) - { - subscriber->receivedDataPromise.set_exception( - std::make_exception_ptr(std::runtime_error{"invalid message data"})); - } - - subscriber->receivedDataPromise.set_value(); - }); + if (event.data.size() != subscriber->message.size()) + { + subscriber->receivedDataPromise.set_exception( + std::make_exception_ptr(std::runtime_error{"invalid message size"})); + } + + if (!ItemsAreEqual(event.data, SilKit::Util::ToSpan(subscriber->message))) + { + subscriber->receivedDataPromise.set_exception( + std::make_exception_ptr(std::runtime_error{"invalid message data"})); + } + + subscriber->receivedDataPromise.set_value(); + }); subscriber->receivedDataFuture = subscriber->receivedDataPromise.get_future(); @@ -291,14 +285,14 @@ struct Simulation { const auto& publisher = pair.second; ASSERT_EQ(publisher->startingFuture.wait_for(timeout), std::future_status::ready) - << registryUri << " " << publisher->participantName; + << registryUri << " " << publisher->participantName; } for (const auto& pair : subscribers) { const auto& subscriber = pair.second; ASSERT_EQ(subscriber->startingFuture.wait_for(timeout), std::future_status::ready) - << registryUri << " " << subscriber->participantName; + << registryUri << " " << subscriber->participantName; } systemController.startingFuture.get(); diff --git a/SilKit/IntegrationTests/ITest_MultiThreadedParticipants.hpp b/SilKit/IntegrationTests/ITest_MultiThreadedParticipants.hpp index dea15db9d..f683df4d6 100644 --- a/SilKit/IntegrationTests/ITest_MultiThreadedParticipants.hpp +++ b/SilKit/IntegrationTests/ITest_MultiThreadedParticipants.hpp @@ -320,10 +320,10 @@ class ITest_MultiThreadedParticipants : public testing::Test } else if (verbose) { - std::cout << ">> AwaitCommunicationInitialized of " << systemControllerParticipantName << " done" << std ::endl; + std::cout << ">> AwaitCommunicationInitialized of " << systemControllerParticipantName << " done" + << std ::endl; } } - }; void SystemStateHandler(SystemState newState) @@ -338,9 +338,11 @@ class ITest_MultiThreadedParticipants : public testing::Test systemControllerParticipant.systemController->AbortSimulation(); break; - case SystemState::Running: break; + case SystemState::Running: + break; - default: break; + default: + break; } } @@ -364,15 +366,13 @@ class ITest_MultiThreadedParticipants : public testing::Test auto systemMonitor = testParticipant.participant->CreateSystemMonitor(); systemMonitor->AddParticipantStatusHandler([&testParticipant](ParticipantStatus status) { - if (status.participantName == testParticipant.name - && status.state == ParticipantState::Paused - && !testParticipant.i.pausedStateReached) + if (status.participantName == testParticipant.name && status.state == ParticipantState::Paused + && !testParticipant.i.pausedStateReached) { testParticipant.i.pausedStateReached = true; testParticipant.pausedStatePromise.set_value(); } - if (status.participantName == testParticipant.name - && status.state == ParticipantState::Running + if (status.participantName == testParticipant.name && status.state == ParticipantState::Running && !testParticipant.i.runningStateReached) { testParticipant.i.runningStateReached = true; @@ -389,45 +389,44 @@ class ITest_MultiThreadedParticipants : public testing::Test "TestSubscriber", matchingDataSpec, [timeSyncService, &testParticipant](IDataSubscriber* /*subscriber*/, const DataMessageEvent& dataMessageEvent) { - auto participantId = dataMessageEvent.data[0]; + auto participantId = dataMessageEvent.data[0]; - if (testParticipant.i.allReceived || participantId == testParticipant.id) - return; + if (testParticipant.i.allReceived || participantId == testParticipant.id) + return; - auto now = timeSyncService->Now(); - if (participantIsSync[participantId] && now >= 0ns) + auto now = timeSyncService->Now(); + if (participantIsSync[participantId] && now >= 0ns) + { + auto delta = now - dataMessageEvent.timestamp; + if (delta > simStepSize) { - auto delta = now - dataMessageEvent.timestamp; - if (delta > simStepSize) - { - testParticipant.lifecycleService->Stop("Fail with chronology error"); + testParticipant.lifecycleService->Stop("Fail with chronology error"); - FAIL() << "Chronology error: Participant " << testParticipant.name << " received message from " - << participantNames[participantId] << " with timestamp " - << dataMessageEvent.timestamp.count() << " while this participant's time is " << now.count(); - } + FAIL() << "Chronology error: Participant " << testParticipant.name << " received message from " + << participantNames[participantId] << " with timestamp " + << dataMessageEvent.timestamp.count() << " while this participant's time is " << now.count(); } + } - testParticipant.receivedIds.insert(dataMessageEvent.data[0]); - // No self delivery: Expect expectedReceptions-1 receptions - if (testParticipant.receivedIds.size() == expectedReceptions - 1) - { - testParticipant.i.allReceived = true; - testParticipant.allReceivedPromise.set_value(); - } - }); + testParticipant.receivedIds.insert(dataMessageEvent.data[0]); + // No self delivery: Expect expectedReceptions-1 receptions + if (testParticipant.receivedIds.size() == expectedReceptions - 1) + { + testParticipant.i.allReceived = true; + testParticipant.allReceivedPromise.set_value(); + } + }); timeSyncService->SetSimulationStepHandler( - [&testParticipant,this](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { - testParticipant.now = now; - testParticipant.publisher->Publish(std::vector{testParticipant.id}); - if (!testParticipant.simtimePassed && now > simtimeToPass) - { - testParticipant.simtimePassed = true; - testParticipant.simtimePassedPromise.set_value(); - } - }, - simStepSize); + [&testParticipant, this](std::chrono::nanoseconds now, std::chrono::nanoseconds /*duration*/) { + testParticipant.now = now; + testParticipant.publisher->Publish(std::vector{testParticipant.id}); + if (!testParticipant.simtimePassed && now > simtimeToPass) + { + testParticipant.simtimePassed = true; + testParticipant.simtimePassedPromise.set_value(); + } + }, simStepSize); auto finalStateFuture = testParticipant.lifecycleService->StartLifecycle(); finalStateFuture.get(); @@ -474,21 +473,21 @@ class ITest_MultiThreadedParticipants : public testing::Test testParticipant.subscriber = testParticipant.participant->CreateDataSubscriber( "TestSubscriber", matchingDataSpec, [&testParticipant](IDataSubscriber* /*subscriber*/, const DataMessageEvent& dataMessageEvent) { - if (!testParticipant.i.allReceived) + if (!testParticipant.i.allReceived) + { + auto participantId = dataMessageEvent.data[0]; + if (participantId != testParticipant.id) { - auto participantId = dataMessageEvent.data[0]; - if (participantId != testParticipant.id) + testParticipant.receivedIds.insert(dataMessageEvent.data[0]); + // No self delivery: Expect expectedReceptions-1 receptions + if (testParticipant.receivedIds.size() == expectedReceptions - 1) { - testParticipant.receivedIds.insert(dataMessageEvent.data[0]); - // No self delivery: Expect expectedReceptions-1 receptions - if (testParticipant.receivedIds.size() == expectedReceptions - 1) - { - testParticipant.i.allReceived = true; - testParticipant.allReceivedPromise.set_value(); - } + testParticipant.i.allReceived = true; + testParticipant.allReceivedPromise.set_value(); } } - }); + } + }); auto runTask = [&testParticipant]() { while (testParticipant.i.runAsync) @@ -548,30 +547,29 @@ class ITest_MultiThreadedParticipants : public testing::Test systemControllerParticipant.systemMonitor = systemControllerParticipant.participant->CreateSystemMonitor(); systemControllerParticipant.systemMonitor->AddParticipantStatusHandler( [this](const Services::Orchestration::ParticipantStatus& status) { + { + if (status.participantName == systemControllerParticipantName + && status.state == ParticipantState::Running && !systemControllerParticipant.i.runningStateReached) { - if (status.participantName == systemControllerParticipantName - && status.state == ParticipantState::Running - && !systemControllerParticipant.i.runningStateReached) - { - systemControllerParticipant.i.runningStateReached = true; - systemControllerParticipant.runningStatePromise.set_value(); - } - else if (status.participantName == systemControllerParticipantName - && status.state == ParticipantState::Paused - && !systemControllerParticipant.i.pausedStateReached) - { - systemControllerParticipant.i.pausedStateReached = true; - systemControllerParticipant.pausedStatePromise.set_value(); - } - else if (status.participantName == systemControllerParticipantName - && status.state == ParticipantState::CommunicationInitialized - && !systemControllerParticipant.i.communicationInitializedStateReached) - { - systemControllerParticipant.i.communicationInitializedStateReached = true; - systemControllerParticipant.communicationInitializedStatePromise.set_value(); - } + systemControllerParticipant.i.runningStateReached = true; + systemControllerParticipant.runningStatePromise.set_value(); } - }); + else if (status.participantName == systemControllerParticipantName + && status.state == ParticipantState::Paused + && !systemControllerParticipant.i.pausedStateReached) + { + systemControllerParticipant.i.pausedStateReached = true; + systemControllerParticipant.pausedStatePromise.set_value(); + } + else if (status.participantName == systemControllerParticipantName + && status.state == ParticipantState::CommunicationInitialized + && !systemControllerParticipant.i.communicationInitializedStateReached) + { + systemControllerParticipant.i.communicationInitializedStateReached = true; + systemControllerParticipant.communicationInitializedStatePromise.set_value(); + } + } + }); systemControllerParticipant.lifecycleService = systemControllerParticipant.participant->CreateLifecycleService( {SilKit::Services::Orchestration::OperationMode::Coordinated}); @@ -579,9 +577,8 @@ class ITest_MultiThreadedParticipants : public testing::Test SilKit::Util::bind_method(&callbacks, &Callbacks::AbortHandler)); systemControllerParticipant.systemController->SetWorkflowConfiguration({required}); - systemControllerParticipant.systemMonitor->AddSystemStateHandler([this](SystemState newState) { - SystemStateHandler(newState); - }); + systemControllerParticipant.systemMonitor->AddSystemStateHandler( + [this](SystemState newState) { SystemStateHandler(newState); }); if (verbose) { @@ -656,7 +653,10 @@ class ITest_MultiThreadedParticipants : public testing::Test registry->StartListening(registryUri); } - void StopRegistry() { registry.reset(); } + void StopRegistry() + { + registry.reset(); + } void RunParticipants(std::list& participants, std::string set = "A") { @@ -668,51 +668,37 @@ class ITest_MultiThreadedParticipants : public testing::Test if (p.lifeCycleOperationMode == OperationMode::Invalid) { - participantThreads_Async_Invalid.emplace_back([this, &p] { - AsyncParticipantThread(p); - }); + participantThreads_Async_Invalid.emplace_back([this, &p] { AsyncParticipantThread(p); }); } else if (p.lifeCycleOperationMode == OperationMode::Autonomous) { - participantThreads_Async_Autonomous.emplace_back([this, &p] { - AsyncParticipantThread(p); - }); + participantThreads_Async_Autonomous.emplace_back([this, &p] { AsyncParticipantThread(p); }); } else if (p.lifeCycleOperationMode == OperationMode::Coordinated) { - participantThreads_Async_Coordinated.emplace_back([this, &p] { - AsyncParticipantThread(p); - }); + participantThreads_Async_Coordinated.emplace_back([this, &p] { AsyncParticipantThread(p); }); } } else if (p.timeMode == TimeMode::Sync) { if (p.lifeCycleOperationMode == OperationMode::Invalid) { - participantThreads_Sync_Invalid.emplace_back([this, &p] { - SyncParticipantThread(p); - }); + participantThreads_Sync_Invalid.emplace_back([this, &p] { SyncParticipantThread(p); }); } else if (p.lifeCycleOperationMode == OperationMode::Autonomous) { if (set == "A") { - participantThreads_Sync_AutonomousA.emplace_back([this, &p] { - SyncParticipantThread(p); - }); + participantThreads_Sync_AutonomousA.emplace_back([this, &p] { SyncParticipantThread(p); }); } else if (set == "B") { - participantThreads_Sync_AutonomousB.emplace_back([this, &p] { - SyncParticipantThread(p); - }); + participantThreads_Sync_AutonomousB.emplace_back([this, &p] { SyncParticipantThread(p); }); } } else if (p.lifeCycleOperationMode == OperationMode::Coordinated) { - participantThreads_Sync_Coordinated.emplace_back([this, &p] { - SyncParticipantThread(p); - }); + participantThreads_Sync_Coordinated.emplace_back([this, &p] { SyncParticipantThread(p); }); } } } @@ -830,11 +816,12 @@ class ITest_MultiThreadedParticipants : public testing::Test threads.clear(); } - void SetUp() override { + void SetUp() override + { globalParticipantIndex = 0; participantNames.clear(); participantIsSync.clear(); - registryUri = MakeTestRegistryUri(); + registryUri = MakeTestRegistryUri(); } protected: diff --git a/SilKit/IntegrationTests/ITest_NetSim.hpp b/SilKit/IntegrationTests/ITest_NetSim.hpp new file mode 100644 index 000000000..f9ce6897a --- /dev/null +++ b/SilKit/IntegrationTests/ITest_NetSim.hpp @@ -0,0 +1,441 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "gtest/gtest.h" + +#include "ITestFixture.hpp" +#include "ConfigurationTestUtils.hpp" + +#include "silkit/SilKit.hpp" +#include "silkit/experimental/netsim/all.hpp" + +namespace { + + +// ---------------------------------- +// CAN +// ---------------------------------- + +struct CallCountsNetSimCan +{ + std::atomic_uint OnSetControllerMode{0}; + std::atomic_uint OnSetBaudrate{0}; + std::atomic_uint OnFrameRequest{0}; + + void Reset() + { + OnSetControllerMode = 0; + OnSetBaudrate = 0; + OnFrameRequest = 0; + } +}; + +struct CallCountsSilKitHandlersCan +{ + std::atomic_uint FrameHandler{0}; + std::atomic_uint FrameTransmitHandler{0}; + std::atomic_uint StateChangeHandler{0}; + std::atomic_uint ErrorStateChangeHandler{0}; + + void Reset() + { + FrameHandler = 0; + FrameTransmitHandler = 0; + StateChangeHandler = 0; + ErrorStateChangeHandler = 0; + } +}; + +struct CallCountsSilKitSentMsgCan +{ + std::atomic_uint SentFramesSimulated{0}; + std::atomic_uint SentFramesTrivial{0}; + + void Reset() + { + SentFramesSimulated = 0; + SentFramesTrivial = 0; + } +}; + +// ---------------------------------- +// Ethernet +// ---------------------------------- + +struct CallCountsNetSimEthernet +{ + std::atomic_uint OnSetControllerMode{0}; + std::atomic_uint OnFrameRequest{0}; + + void Reset() + { + OnSetControllerMode = 0; + OnFrameRequest = 0; + } +}; + +struct CallCountsSilKitHandlersEthernet +{ + std::atomic_uint FrameHandler{0}; + std::atomic_uint FrameTransmitHandler{0}; + std::atomic_uint StateChangeHandler{0}; + std::atomic_uint BitrateChangeHandler{0}; + + void Reset() + { + FrameHandler = 0; + FrameTransmitHandler = 0; + StateChangeHandler = 0; + BitrateChangeHandler = 0; + } +}; + +struct CallCountsSilKitSentMsgEthernet +{ + std::atomic_uint SentFramesSimulated{0}; + std::atomic_uint SentFramesTrivial{0}; + + void Reset() + { + SentFramesSimulated = 0; + SentFramesTrivial = 0; + } +}; + +// ---------------------------------- +// Lin +// ---------------------------------- + +struct CallCountsNetSimLin +{ + std::atomic_uint OnFrameRequest{0}; + std::atomic_uint OnFrameHeaderRequest{0}; + std::atomic_uint OnWakeupPulse{0}; + std::atomic_uint OnControllerConfig{0}; + std::atomic_uint OnFrameResponseUpdate{0}; + std::atomic_uint OnControllerStatusUpdate{0}; + + void Reset() + { + OnFrameRequest = 0; + OnFrameHeaderRequest = 0; + OnWakeupPulse = 0; + OnControllerConfig = 0; + OnFrameResponseUpdate = 0; + OnControllerStatusUpdate = 0; + } +}; + +struct CallCountsSilKitHandlersLin +{ + std::atomic_uint FrameStatusHandler{0}; + std::atomic_uint FrameHeaderHandler{0}; + std::atomic_uint GoToSleepHandler{0}; + std::atomic_uint WakeupHandler{0}; + + void Reset() + { + FrameStatusHandler = 0; + FrameHeaderHandler = 0; + GoToSleepHandler = 0; + WakeupHandler = 0; + } +}; + +struct CallCountsSilKitSentMsgLin +{ + std::atomic_uint SentFramesSimulated{0}; + std::atomic_uint SentFramesTrivial{0}; + std::atomic_uint SentFrameHeadersSimulated{0}; + std::atomic_uint SentFrameHeadersTrivial{0}; + + void Reset() + { + SentFramesSimulated = 0; + SentFramesTrivial = 0; + SentFrameHeadersSimulated = 0; + SentFrameHeadersTrivial = 0; + } +}; + + +// ---------------------------------- +// FlexRay +// ---------------------------------- + + +struct CallCountsNetSimFlexray +{ + std::atomic_uint OnHostCommand{0}; + std::atomic_uint OnControllerConfig{0}; + std::atomic_uint OnTxBufferConfigUpdate{0}; + std::atomic_uint OnTxBufferUpdate{0}; + + void Reset() + { + OnHostCommand = 0; + OnControllerConfig = 0; + OnTxBufferConfigUpdate = 0; + OnTxBufferUpdate = 0; + } +}; + +struct CallCountsSilKitHandlersFlexray +{ + std::atomic_uint FrameHandler{0}; + std::atomic_uint FrameTransmitHandler{0}; + std::atomic_uint WakeupHandler{0}; + std::atomic_uint PocStatusHandler{0}; + std::atomic_uint SymbolHandler{0}; + std::atomic_uint SymbolTransmitHandler{0}; + std::atomic_uint CycleStartHandler{0}; + + void Reset() + { + FrameHandler = 0; + FrameTransmitHandler = 0; + WakeupHandler = 0; + PocStatusHandler = 0; + SymbolHandler = 0; + SymbolTransmitHandler = 0; + CycleStartHandler = 0; + } +}; + +struct CallCountsSilKitSentMsgFlexray +{ + std::atomic_uint SentFrames{0}; + + void Reset() + { + SentFrames = 0; + } +}; + +// ---------------------------------- +// Common +// ---------------------------------- + +struct CallCountsSimulatedNetwork +{ + std::atomic_uint ProvideSimulatedController{0}; + std::atomic_uint EventProducer{0}; + std::atomic_uint SimulatedControllerRemoved{0}; + + void Reset() + { + ProvideSimulatedController = 0; + EventProducer = 0; + SimulatedControllerRemoved = 0; + } +}; + +struct CallCounts +{ + CallCountsSimulatedNetwork simulatedNetwork{}; + + // CAN + CallCountsNetSimCan netSimCan{}; + CallCountsSilKitSentMsgCan silKitSentMsgCan{}; + CallCountsSilKitHandlersCan silKitHandlersCanSimulated{}; + CallCountsSilKitHandlersCan silKitHandlersCanTrivial{}; + + // Ethernet + CallCountsNetSimEthernet netSimEthernet{}; + CallCountsSilKitSentMsgEthernet silKitSentMsgEthernet{}; + CallCountsSilKitHandlersEthernet silKitHandlersEthernetSimulated{}; + CallCountsSilKitHandlersEthernet silKitHandlersEthernetTrivial{}; + + // Lin + CallCountsNetSimLin netSimLin{}; + CallCountsSilKitSentMsgLin silKitSentMsgLin{}; + CallCountsSilKitHandlersLin silKitHandlersLinSimulated{}; + CallCountsSilKitHandlersLin silKitHandlersLinTrivial{}; + + // FlexRay + CallCountsNetSimFlexray netSimFlexray{}; + CallCountsSilKitSentMsgFlexray silKitSentMsgFlexray{}; + CallCountsSilKitHandlersFlexray silKitHandlersFlexray{}; + + void Reset() + { + simulatedNetwork.Reset(); + + netSimCan.Reset(); + silKitHandlersCanSimulated.Reset(); + silKitHandlersCanTrivial.Reset(); + silKitSentMsgCan.Reset(); + + netSimEthernet.Reset(); + silKitHandlersEthernetSimulated.Reset(); + silKitHandlersEthernetTrivial.Reset(); + silKitSentMsgEthernet.Reset(); + + netSimLin.Reset(); + silKitHandlersLinSimulated.Reset(); + silKitHandlersLinTrivial.Reset(); + silKitSentMsgLin.Reset(); + + netSimFlexray.Reset(); + silKitSentMsgFlexray.Reset(); + silKitHandlersFlexray.Reset(); + } +}; + +CallCounts callCounts{}; + +using namespace SilKit::Experimental::NetworkSimulation; +using namespace SilKit::Experimental::NetworkSimulation::Can; +using namespace SilKit::Experimental::NetworkSimulation::Ethernet; +using namespace SilKit::Experimental::NetworkSimulation::Lin; +using namespace SilKit::Experimental::NetworkSimulation::Flexray; +using namespace SilKit::Tests; + +auto suffixedStrings(std::string body, size_t num) -> std::vector +{ + std::vector res{}; + auto firstLetter = 'A'; + auto lastLetter = static_cast(firstLetter + num - 1); + for (char suffix = firstLetter; suffix <= lastLetter; ++suffix) + { + res.emplace_back(body + suffix); + } + return res; +} + +struct ITest_NetSim : ITest_SimTestHarness +{ + using ITest_SimTestHarness::ITest_SimTestHarness; + + void SetUp() override + { + callCounts.Reset(); + + _participantNamesSimulated = suffixedStrings("ParticipantSimulated", _numParticipantsSimulated); + _participantNamesTrivial = suffixedStrings("ParticipantTrivial", _numParticipantsTrivial); + _emptyNetworks = suffixedStrings("EmtpyNetwork", _numEmptyNetworks); + + _sendUntilMs = std::chrono::milliseconds{_numSimSteps}; + _stopAtMs = std::chrono::milliseconds{_numSimSteps + 1}; // Stop in NetSim one step later to receive all + + // System controller setup + { + auto syncParticipantNames = _participantNamesSimulated; + syncParticipantNames.insert(syncParticipantNames.end(), _participantNamesTrivial.begin(), + _participantNamesTrivial.end()); + syncParticipantNames.emplace_back(_participantNameNetSim); + SetupFromParticipantList(syncParticipantNames); + } + } + + const size_t _numParticipantsSimulated = 3; + const size_t _numParticipantsTrivial = 4; + const size_t _numEmptyNetworks = 3; + + const std::string _participantNameNetSim = "NetworkSimulator"; + const std::string _simulatedNetworkName = "SIMULATED"; + const std::string _trivialNetworkName = "TRIVIAL"; + + // Deterministic send/receive setup + const size_t _numSimulatedNetworks = 1; + const size_t _numSimSteps = 5; + const std::chrono::milliseconds _stepSize{1}; + const size_t _numFramesPerSimStep = 5; + + std::chrono::milliseconds _sendUntilMs; + std::chrono::milliseconds _stopAtMs; + + std::vector _participantNamesSimulated; + std::vector _participantNamesTrivial; + std::vector _emptyNetworks; +}; + + +class MySimulatedNetwork; + +class MySimulatedController +{ +protected: + ControllerDescriptor _controllerDescriptor; + MySimulatedNetwork* _mySimulatedNetwork; + +public: + MySimulatedController(MySimulatedNetwork* mySimulatedNetwork, ControllerDescriptor controllerDescriptor) + : _controllerDescriptor{controllerDescriptor} + , _mySimulatedNetwork{mySimulatedNetwork} + { + } +}; + +class MySimulatedNetwork : public ISimulatedNetwork +{ + SimulatedNetworkType _networkType; + std::string _networkName; + bool _isLinDynamic; + + std::unique_ptr _eventProducer; + std::vector _controllerDescriptors; + std::vector> _mySimulatedControllers; + +public: + MySimulatedNetwork(SimulatedNetworkType networkType, std::string networkName, bool isLinDynamic = false) + : _networkType{networkType} + , _networkName{networkName} + , _isLinDynamic{isLinDynamic} + { + (void)_isLinDynamic; + } + + // ISimulatedNetwork + void SetEventProducer(std::unique_ptr eventProducer) override; + auto ProvideSimulatedController(ControllerDescriptor controllerDescriptor) -> ISimulatedController* override; + void SimulatedControllerRemoved(ControllerDescriptor controllerDescriptor) override; + + auto GetCanEventProducer() + { + return static_cast(_eventProducer.get()); + } + auto GetEthernetEventProducer() + { + return static_cast(_eventProducer.get()); + } + auto GetLinEventProducer() + { + return static_cast(_eventProducer.get()); + } + auto GetFlexRayEventProducer() + { + return static_cast(_eventProducer.get()); + } + + auto GetAllControllerDescriptors() + { + return SilKit::Util::ToSpan(_controllerDescriptors); + } +}; + +// ISimulatedNetwork + +void MySimulatedNetwork::SetEventProducer(std::unique_ptr eventProducer) +{ + callCounts.simulatedNetwork.EventProducer++; + + _eventProducer = std::move(eventProducer); +} + +void MySimulatedNetwork::SimulatedControllerRemoved(ControllerDescriptor /*controllerDescriptor*/) +{ + callCounts.simulatedNetwork.SimulatedControllerRemoved++; +} + +} //end namespace diff --git a/SilKit/IntegrationTests/ITest_NetSimCan.cpp b/SilKit/IntegrationTests/ITest_NetSimCan.cpp new file mode 100644 index 000000000..b3f511ca7 --- /dev/null +++ b/SilKit/IntegrationTests/ITest_NetSimCan.cpp @@ -0,0 +1,276 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "ITest_NetSim.hpp" +#include "silkit/services/can/all.hpp" + +namespace { + +using namespace std::chrono_literals; + +using namespace SilKit::Tests; +using namespace SilKit::Config; +using namespace SilKit::Services; +using namespace SilKit::Experimental::NetworkSimulation; + +using namespace SilKit::Services::Can; +using namespace SilKit::Experimental::NetworkSimulation::Can; + + +struct ITest_NetSimCan : ITest_NetSim +{ + void SendCanFrames(std::chrono::nanoseconds now, ICanController* controller, std::atomic_uint& sendCount) + { + std::array dataBytes{78}; + + CanFrame frame{}; + frame.flags = {}; + frame.canId = 0x12; + frame.dlc = 1; + frame.dataField = SilKit::Util::MakeSpan(dataBytes); + + if (now < _sendUntilMs) + { + for (size_t i = 0; i < _numFramesPerSimStep; ++i) + { + controller->SendFrame(frame); + sendCount++; + } + } + } + + void SetupCanController(Orchestration::ILifecycleService* lifecycleService, ICanController* controller, + CallCountsSilKitHandlersCan& callCountsSilKitHandlersCan) + { + controller->AddFrameHandler([&callCountsSilKitHandlersCan](ICanController*, const CanFrameEvent& /*msg*/) { + callCountsSilKitHandlersCan.FrameHandler++; + }); + controller->AddFrameTransmitHandler( + [&callCountsSilKitHandlersCan](ICanController*, const CanFrameTransmitEvent& /*msg*/) { + callCountsSilKitHandlersCan.FrameTransmitHandler++; + }); + controller->AddStateChangeHandler( + [&callCountsSilKitHandlersCan](ICanController*, const CanStateChangeEvent& /*msg*/) { + callCountsSilKitHandlersCan.StateChangeHandler++; + }); + controller->AddErrorStateChangeHandler( + [&callCountsSilKitHandlersCan](ICanController*, const CanErrorStateChangeEvent& /*msg*/) { + callCountsSilKitHandlersCan.ErrorStateChangeHandler++; + }); + + lifecycleService->SetCommunicationReadyHandler([controller] { + controller->SetBaudRate(10'000, 1'000'000, 2'000'000); + controller->Start(); + }); + } +}; + +class MySimulatedCanController + : public MySimulatedController + , public ISimulatedCanController +{ +public: + MySimulatedCanController(MySimulatedNetwork* mySimulatedNetwork, ControllerDescriptor controllerDescriptor) + : MySimulatedController(mySimulatedNetwork, controllerDescriptor) + { + } + + void OnSetControllerMode(const CanControllerMode& controllerMode) override; + void OnSetBaudrate(const CanConfigureBaudrate& configureBaudrate) override; + void OnFrameRequest(const CanFrameRequest& frameRequest) override; +}; + + +auto MySimulatedNetwork::ProvideSimulatedController(ControllerDescriptor controllerDescriptor) -> ISimulatedController* +{ + callCounts.simulatedNetwork.ProvideSimulatedController++; + _controllerDescriptors.push_back(controllerDescriptor); + + switch (_networkType) + { + case SimulatedNetworkType::CAN: + { + _mySimulatedControllers.emplace_back(std::make_unique(this, controllerDescriptor)); + return _mySimulatedControllers.back().get(); + } + default: + break; + } + + return {}; +} + +// ISimulatedCanController + +void MySimulatedCanController::OnSetControllerMode(const CanControllerMode& /*controllerMode*/) +{ + callCounts.netSimCan.OnSetControllerMode++; + + std::array receiverArray{_controllerDescriptor}; + auto receiver = SilKit::Util::MakeSpan(receiverArray); + + CanStateChangeEvent stateChangeEvent{}; + stateChangeEvent.state = CanControllerState::Started; + _mySimulatedNetwork->GetCanEventProducer()->Produce(std::move(stateChangeEvent), receiver); + + CanErrorStateChangeEvent errorStateChangeEvent{}; + errorStateChangeEvent.errorState = CanErrorState::BusOff; + _mySimulatedNetwork->GetCanEventProducer()->Produce(std::move(errorStateChangeEvent), receiver); +} + +void MySimulatedCanController::OnSetBaudrate(const CanConfigureBaudrate& /*configureBaudrate*/) +{ + callCounts.netSimCan.OnSetBaudrate++; +} + +void MySimulatedCanController::OnFrameRequest(const CanFrameRequest& frameRequest) +{ + callCounts.netSimCan.OnFrameRequest++; + + // Send acknowledge back to the sending controller + CanFrameTransmitEvent ack; + ack.canId = frameRequest.frame.canId; + ack.status = CanTransmitStatus::Transmitted; + ack.userContext = frameRequest.userContext; + + std::array receiverArray{_controllerDescriptor}; + auto receiver = SilKit::Util::MakeSpan(receiverArray); + _mySimulatedNetwork->GetCanEventProducer()->Produce(std::move(ack), receiver); + + // Distribute the frame to all controllers in the network + CanFrameEvent frameEvent; + frameEvent.direction = TransmitDirection::RX; + frameEvent.frame = frameRequest.frame; + frameEvent.userContext = frameRequest.userContext; + std::vector payloadBytes{frameRequest.frame.dataField.begin(), frameRequest.frame.dataField.end()}; + + frameEvent.frame.dataField = SilKit::Util::ToSpan(payloadBytes); + _mySimulatedNetwork->GetCanEventProducer()->Produce(frameEvent, _mySimulatedNetwork->GetAllControllerDescriptors()); +} + +// Testing NetSim API with CAN +// Covers: +// - Trivial and simulated CanControllers in one simulation +// - Correct routing of simulated CAN messages +// - Network Simulator participant has CanControllers itself + +TEST_F(ITest_NetSimCan, basic_networksimulation_can) +{ + { + // ---------------------------- + // NetworkSimulator + // ---------------------------- + + //auto configWithLogging = MakeParticipantConfigurationStringWithLogging(SilKit::Services::Logging::Level::Info); + auto&& simParticipant = _simTestHarness->GetParticipant(_participantNameNetSim); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& networkSimulator = simParticipant->GetOrCreateNetworkSimulator(); + + auto simulatedNetwork = std::make_unique(SimulatedNetworkType::CAN, _simulatedNetworkName); + networkSimulator->SimulateNetwork(_simulatedNetworkName, SimulatedNetworkType::CAN, + std::move(simulatedNetwork)); + + for (const auto& emptyNetworkName : _emptyNetworks) + { + auto emptyCanNetwork = + std::make_unique(SimulatedNetworkType::FlexRay, emptyNetworkName); + networkSimulator->SimulateNetwork(emptyNetworkName, SimulatedNetworkType::FlexRay, + std::move(emptyCanNetwork)); + } + + // The network simulator has a simulated controller as well + auto&& participant = simParticipant->Participant(); + auto&& canController = participant->CreateCanController("CAN1", _simulatedNetworkName); + SetupCanController(lifecycleService, canController, callCounts.silKitHandlersCanSimulated); + + networkSimulator->Start(); + + timeSyncService->SetSimulationStepHandler( + [this, lifecycleService, canController](auto now, const std::chrono::nanoseconds /*duration*/) { + if (now == _stopAtMs) + { + lifecycleService->Stop("stopping the simulation"); + } + else + { + SendCanFrames(now, canController, callCounts.silKitSentMsgCan.SentFramesSimulated); + } + }, _stepSize); + } + + { + // ---------------------------- + // Simulated Participants + // ---------------------------- + + for (const auto& participantName : _participantNamesSimulated) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& canController = participant->CreateCanController("CAN1", _simulatedNetworkName); + SetupCanController(lifecycleService, canController, callCounts.silKitHandlersCanSimulated); + + timeSyncService->SetSimulationStepHandler( + [this, canController](auto now, const std::chrono::nanoseconds /*duration*/) { + SendCanFrames(now, canController, callCounts.silKitSentMsgCan.SentFramesSimulated); + }, _stepSize); + } + } + + { + // ---------------------------- + // Trivial Participants + // ---------------------------- + + for (const auto& participantName : _participantNamesTrivial) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& canController = participant->CreateCanController("CAN1", _trivialNetworkName); + SetupCanController(lifecycleService, canController, callCounts.silKitHandlersCanTrivial); + + timeSyncService->SetSimulationStepHandler( + [this, canController](auto now, const std::chrono::nanoseconds /*duration*/) { + SendCanFrames(now, canController, callCounts.silKitSentMsgCan.SentFramesTrivial); + }, _stepSize); + } + } + + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + + const size_t numSimulatedCanControllers = + _numParticipantsSimulated + 1; // +1 for the CAN controller on the Netsim participant + const size_t numSentFramesSimulated = numSimulatedCanControllers * _numFramesPerSimStep * _numSimSteps; + const size_t numSentFramesTrivial = _numParticipantsTrivial * _numFramesPerSimStep * _numSimSteps; + + EXPECT_EQ(callCounts.simulatedNetwork.EventProducer, _numSimulatedNetworks); + EXPECT_EQ(callCounts.simulatedNetwork.ProvideSimulatedController, numSimulatedCanControllers); + + EXPECT_EQ(callCounts.silKitHandlersCanSimulated.FrameHandler, numSentFramesSimulated * numSimulatedCanControllers); + EXPECT_EQ(callCounts.silKitHandlersCanTrivial.FrameHandler, + numSentFramesTrivial * (_numParticipantsTrivial - 1)); // FrameHandler filters messages from sender + EXPECT_EQ(callCounts.silKitHandlersCanSimulated.FrameTransmitHandler, numSentFramesSimulated); + EXPECT_EQ(callCounts.silKitHandlersCanTrivial.FrameTransmitHandler, numSentFramesTrivial); + EXPECT_EQ(callCounts.silKitHandlersCanSimulated.StateChangeHandler, numSimulatedCanControllers); + EXPECT_EQ(callCounts.silKitHandlersCanTrivial.StateChangeHandler, _numParticipantsTrivial); + EXPECT_EQ(callCounts.silKitHandlersCanSimulated.ErrorStateChangeHandler, numSimulatedCanControllers); + EXPECT_EQ(callCounts.silKitHandlersCanTrivial.ErrorStateChangeHandler, 0); + + EXPECT_EQ(callCounts.netSimCan.OnFrameRequest, numSentFramesSimulated); + EXPECT_EQ(callCounts.netSimCan.OnSetBaudrate, numSimulatedCanControllers); + EXPECT_EQ(callCounts.netSimCan.OnSetControllerMode, numSimulatedCanControllers); + + EXPECT_EQ(callCounts.silKitSentMsgCan.SentFramesSimulated, numSentFramesSimulated); + EXPECT_EQ(callCounts.silKitSentMsgCan.SentFramesTrivial, numSentFramesTrivial); +} + +} //end namespace diff --git a/SilKit/IntegrationTests/ITest_NetSimEthernet.cpp b/SilKit/IntegrationTests/ITest_NetSimEthernet.cpp new file mode 100644 index 000000000..bbac8ab74 --- /dev/null +++ b/SilKit/IntegrationTests/ITest_NetSimEthernet.cpp @@ -0,0 +1,267 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "ITest_NetSim.hpp" +#include "silkit/services/ethernet/all.hpp" + +namespace { + +using namespace std::chrono_literals; + +using namespace SilKit::Config; +using namespace SilKit::Services; +using namespace SilKit::Experimental::NetworkSimulation; + +using namespace SilKit::Services::Ethernet; +using namespace SilKit::Experimental::NetworkSimulation::Ethernet; + +struct ITest_NetSimEthernet : ITest_NetSim +{ + void SendEthernetFrames(std::chrono::nanoseconds now, IEthernetController* controller, std::atomic_uint& sendCount) + { + std::array dataBytes{78}; + + EthernetFrame frame{}; + frame.raw = SilKit::Util::MakeSpan(dataBytes); + + if (now < _sendUntilMs) + { + for (size_t i = 0; i < _numFramesPerSimStep; ++i) + { + controller->SendFrame(frame); + sendCount++; + } + } + } + + void SetupEthernetController(Orchestration::ILifecycleService* lifecycleService, IEthernetController* controller, + CallCountsSilKitHandlersEthernet& callCountsSilKitHandlerEthernet) + { + controller->AddFrameHandler( + [&callCountsSilKitHandlerEthernet](IEthernetController*, const EthernetFrameEvent& /*msg*/) { + callCountsSilKitHandlerEthernet.FrameHandler++; + }); + controller->AddFrameTransmitHandler( + [&callCountsSilKitHandlerEthernet](IEthernetController*, const EthernetFrameTransmitEvent& /*msg*/) { + callCountsSilKitHandlerEthernet.FrameTransmitHandler++; + }); + controller->AddStateChangeHandler( + [&callCountsSilKitHandlerEthernet](IEthernetController*, const EthernetStateChangeEvent& /*msg*/) { + callCountsSilKitHandlerEthernet.StateChangeHandler++; + }); + + controller->AddBitrateChangeHandler( + [&callCountsSilKitHandlerEthernet](IEthernetController*, const EthernetBitrateChangeEvent& /*msg*/) { + callCountsSilKitHandlerEthernet.BitrateChangeHandler++; + }); + + lifecycleService->SetCommunicationReadyHandler([controller] { controller->Activate(); }); + } +}; + +class MySimulatedEthernetController + : public MySimulatedController + , public ISimulatedEthernetController +{ +public: + MySimulatedEthernetController(MySimulatedNetwork* mySimulatedNetwork, ControllerDescriptor controllerDescriptor) + : MySimulatedController(mySimulatedNetwork, controllerDescriptor) + { + } + + void OnFrameRequest(const EthernetFrameRequest& ethernetFrameRequest) override; + void OnSetControllerMode(const EthernetControllerMode& ethernetControllerMode) override; +}; + + +auto MySimulatedNetwork::ProvideSimulatedController(ControllerDescriptor controllerDescriptor) -> ISimulatedController* +{ + callCounts.simulatedNetwork.ProvideSimulatedController++; + _controllerDescriptors.push_back(controllerDescriptor); + + switch (_networkType) + { + case SimulatedNetworkType::Ethernet: + { + _mySimulatedControllers.emplace_back( + std::make_unique(this, controllerDescriptor)); + return _mySimulatedControllers.back().get(); + } + default: + break; + } + + return {}; +} + +// ISimulatedEthernetController + +void MySimulatedEthernetController::OnSetControllerMode(const EthernetControllerMode& /*controllerMode*/) +{ + callCounts.netSimEthernet.OnSetControllerMode++; + + std::array receiverArray{_controllerDescriptor}; + auto receiver = SilKit::Util::MakeSpan(receiverArray); + + EthernetStateChangeEvent stateChangeEvent{}; + stateChangeEvent.state = EthernetState::LinkUp; + _mySimulatedNetwork->GetEthernetEventProducer()->Produce(std::move(stateChangeEvent), receiver); + + EthernetBitrateChangeEvent bitrateChangeEvent{}; + bitrateChangeEvent.bitrate = 223; + _mySimulatedNetwork->GetEthernetEventProducer()->Produce(std::move(bitrateChangeEvent), receiver); +} + +void MySimulatedEthernetController::OnFrameRequest(const EthernetFrameRequest& frameRequest) +{ + callCounts.netSimEthernet.OnFrameRequest++; + + // Send acknowledge back to the sending controller + EthernetFrameTransmitEvent ack; + ack.status = EthernetTransmitStatus::Transmitted; + ack.userContext = frameRequest.userContext; + + std::array receiverArray{_controllerDescriptor}; + auto receiver = SilKit::Util::MakeSpan(receiverArray); + _mySimulatedNetwork->GetEthernetEventProducer()->Produce(std::move(ack), receiver); + + // Distribute the frame to all controllers in the network + EthernetFrameEvent frameEvent; + frameEvent.direction = TransmitDirection::RX; + frameEvent.frame = frameRequest.ethernetFrame; + frameEvent.userContext = frameRequest.userContext; + std::vector payloadBytes{frameRequest.ethernetFrame.raw.begin(), frameRequest.ethernetFrame.raw.end()}; + + frameEvent.frame.raw = SilKit::Util::ToSpan(payloadBytes); + _mySimulatedNetwork->GetEthernetEventProducer()->Produce(frameEvent, + _mySimulatedNetwork->GetAllControllerDescriptors()); +} + +// Testing NetSim API with Ethernet +// Covers: +// - Trivial and simulated EthernetControllers in one simulation +// - Correct routing of simulated Ethernet messages +// - Network Simulator participant has EthernetControllers itself + +TEST_F(ITest_NetSimEthernet, basic_networksimulation_ethernet) +{ + { + // ---------------------------- + // NetworkSimulator + // ---------------------------- + + //auto configWithLogging = MakeParticipantConfigurationStringWithLogging(SilKit::Services::Logging::Level::Info); + auto&& simParticipant = _simTestHarness->GetParticipant(_participantNameNetSim); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& networkSimulator = simParticipant->GetOrCreateNetworkSimulator(); + + auto simulatedNetwork = + std::make_unique(SimulatedNetworkType::Ethernet, _simulatedNetworkName); + networkSimulator->SimulateNetwork(_simulatedNetworkName, SimulatedNetworkType::Ethernet, + std::move(simulatedNetwork)); + + for (const auto& emptyNetworkName : _emptyNetworks) + { + auto emptyEthernetNetwork = + std::make_unique(SimulatedNetworkType::FlexRay, emptyNetworkName); + networkSimulator->SimulateNetwork(emptyNetworkName, SimulatedNetworkType::FlexRay, + std::move(emptyEthernetNetwork)); + } + + // The network simulator has a simulated controller as well + auto&& participant = simParticipant->Participant(); + auto&& ethernetController = participant->CreateEthernetController("Ethernet1", _simulatedNetworkName); + SetupEthernetController(lifecycleService, ethernetController, callCounts.silKitHandlersEthernetSimulated); + + networkSimulator->Start(); + + timeSyncService->SetSimulationStepHandler( + [this, lifecycleService, ethernetController](auto now, const std::chrono::nanoseconds /*duration*/) { + if (now == _stopAtMs) + { + lifecycleService->Stop("stopping the simulation"); + } + else + { + SendEthernetFrames(now, ethernetController, callCounts.silKitSentMsgEthernet.SentFramesSimulated); + } + }, _stepSize); + } + + { + // ---------------------------- + // Simulated Participants + // ---------------------------- + + for (const auto& participantName : _participantNamesSimulated) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& ethernetController = participant->CreateEthernetController("Ethernet1", _simulatedNetworkName); + SetupEthernetController(lifecycleService, ethernetController, callCounts.silKitHandlersEthernetSimulated); + + timeSyncService->SetSimulationStepHandler( + [this, ethernetController](auto now, const std::chrono::nanoseconds /*duration*/) { + SendEthernetFrames(now, ethernetController, callCounts.silKitSentMsgEthernet.SentFramesSimulated); + }, _stepSize); + } + } + + { + // ---------------------------- + // Trivial Participants + // ---------------------------- + + for (const auto& participantName : _participantNamesTrivial) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& ethernetController = participant->CreateEthernetController("Ethernet1", _trivialNetworkName); + SetupEthernetController(lifecycleService, ethernetController, callCounts.silKitHandlersEthernetTrivial); + + timeSyncService->SetSimulationStepHandler( + [this, ethernetController](auto now, const std::chrono::nanoseconds /*duration*/) { + SendEthernetFrames(now, ethernetController, callCounts.silKitSentMsgEthernet.SentFramesTrivial); + }, _stepSize); + } + } + + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + + const size_t numSimulatedEthernetControllers = + _numParticipantsSimulated + 1; // +1 for the Ethernet controller on the Netsim participant + const size_t numSentFramesSimulated = numSimulatedEthernetControllers * _numFramesPerSimStep * _numSimSteps; + const size_t numSentFramesTrivial = _numParticipantsTrivial * _numFramesPerSimStep * _numSimSteps; + + EXPECT_EQ(callCounts.simulatedNetwork.EventProducer, _numSimulatedNetworks); + EXPECT_EQ(callCounts.simulatedNetwork.ProvideSimulatedController, numSimulatedEthernetControllers); + + EXPECT_EQ(callCounts.silKitHandlersEthernetSimulated.FrameHandler, + numSentFramesSimulated * numSimulatedEthernetControllers); + EXPECT_EQ(callCounts.silKitHandlersEthernetTrivial.FrameHandler, + numSentFramesTrivial * (_numParticipantsTrivial - 1)); // FrameHandler filters messages from sender + EXPECT_EQ(callCounts.silKitHandlersEthernetSimulated.FrameTransmitHandler, numSentFramesSimulated); + EXPECT_EQ(callCounts.silKitHandlersEthernetTrivial.FrameTransmitHandler, numSentFramesTrivial); + EXPECT_EQ(callCounts.silKitHandlersEthernetSimulated.StateChangeHandler, numSimulatedEthernetControllers); + EXPECT_EQ(callCounts.silKitHandlersEthernetTrivial.StateChangeHandler, _numParticipantsTrivial); + EXPECT_EQ(callCounts.silKitHandlersEthernetSimulated.BitrateChangeHandler, numSimulatedEthernetControllers); + EXPECT_EQ(callCounts.silKitHandlersEthernetTrivial.BitrateChangeHandler, 0); + + EXPECT_EQ(callCounts.netSimEthernet.OnFrameRequest, numSentFramesSimulated); + EXPECT_EQ(callCounts.netSimEthernet.OnSetControllerMode, numSimulatedEthernetControllers); + + EXPECT_EQ(callCounts.silKitSentMsgEthernet.SentFramesSimulated, numSentFramesSimulated); + EXPECT_EQ(callCounts.silKitSentMsgEthernet.SentFramesTrivial, numSentFramesTrivial); +} + + +} //end namespace diff --git a/SilKit/IntegrationTests/ITest_NetSimFlexRay.cpp b/SilKit/IntegrationTests/ITest_NetSimFlexRay.cpp new file mode 100644 index 000000000..c96f39bf4 --- /dev/null +++ b/SilKit/IntegrationTests/ITest_NetSimFlexRay.cpp @@ -0,0 +1,393 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "ITest_NetSim.hpp" +#include "silkit/services/flexray/all.hpp" + +namespace { + +using namespace std::chrono_literals; + +using namespace SilKit::Tests; +using namespace SilKit::Config; +using namespace SilKit::Services; +using namespace SilKit::Experimental::NetworkSimulation; + +using namespace SilKit::Services::Flexray; +using namespace SilKit::Experimental::NetworkSimulation::Flexray; + +struct ITest_NetSimFlexray : ITest_NetSim +{ + void SetupFlexrayController(Orchestration::ILifecycleService* lifecycleService, IFlexrayController* controller, + CallCountsSilKitHandlersFlexray& callCountsSilKitHandlersFlexray) + { + controller->AddCycleStartHandler( + [&callCountsSilKitHandlersFlexray](IFlexrayController*, const FlexrayCycleStartEvent& /*msg*/) { + callCountsSilKitHandlersFlexray.CycleStartHandler++; + }); + controller->AddFrameHandler( + [&callCountsSilKitHandlersFlexray](IFlexrayController*, const FlexrayFrameEvent& /*msg*/) { + callCountsSilKitHandlersFlexray.FrameHandler++; + }); + controller->AddFrameTransmitHandler( + [&callCountsSilKitHandlersFlexray](IFlexrayController*, const FlexrayFrameTransmitEvent& /*msg*/) { + callCountsSilKitHandlersFlexray.FrameTransmitHandler++; + }); + controller->AddPocStatusHandler( + [&callCountsSilKitHandlersFlexray](IFlexrayController*, const FlexrayPocStatusEvent& /*msg*/) { + callCountsSilKitHandlersFlexray.PocStatusHandler++; + }); + controller->AddSymbolHandler( + [&callCountsSilKitHandlersFlexray](IFlexrayController*, const FlexraySymbolEvent& /*msg*/) { + callCountsSilKitHandlersFlexray.SymbolHandler++; + }); + controller->AddSymbolTransmitHandler( + [&callCountsSilKitHandlersFlexray](IFlexrayController*, const FlexraySymbolTransmitEvent& /*msg*/) { + callCountsSilKitHandlersFlexray.SymbolTransmitHandler++; + }); + controller->AddWakeupHandler( + [&callCountsSilKitHandlersFlexray](IFlexrayController*, const FlexrayWakeupEvent& /*msg*/) { + callCountsSilKitHandlersFlexray.WakeupHandler++; + }); + + lifecycleService->SetCommunicationReadyHandler([controller] { + FlexrayClusterParameters clusterParams; + clusterParams.gColdstartAttempts = 8; + clusterParams.gCycleCountMax = 63; + clusterParams.gdActionPointOffset = 2; + clusterParams.gdDynamicSlotIdlePhase = 1; + clusterParams.gdMiniSlot = 5; + clusterParams.gdMiniSlotActionPointOffset = 2; + clusterParams.gdStaticSlot = 31; + clusterParams.gdSymbolWindow = 0; + clusterParams.gdSymbolWindowActionPointOffset = 1; + clusterParams.gdTSSTransmitter = 9; + clusterParams.gdWakeupTxActive = 60; + clusterParams.gdWakeupTxIdle = 180; + clusterParams.gListenNoise = 2; + clusterParams.gMacroPerCycle = 3636; + clusterParams.gMaxWithoutClockCorrectionFatal = 2; + clusterParams.gMaxWithoutClockCorrectionPassive = 2; + clusterParams.gNumberOfMiniSlots = 291; + clusterParams.gNumberOfStaticSlots = 70; + clusterParams.gPayloadLengthStatic = 13; + clusterParams.gSyncFrameIDCountMax = 15; + + FlexrayNodeParameters nodeParams; + nodeParams.pAllowHaltDueToClock = 1; + nodeParams.pAllowPassiveToActive = 0; + nodeParams.pChannels = FlexrayChannel::AB; + nodeParams.pClusterDriftDamping = 2; + nodeParams.pdAcceptedStartupRange = 212; + nodeParams.pdListenTimeout = 400162; + nodeParams.pKeySlotOnlyEnabled = 0; + nodeParams.pKeySlotUsedForStartup = 1; + nodeParams.pKeySlotUsedForSync = 0; + nodeParams.pLatestTx = 249; + nodeParams.pMacroInitialOffsetA = 3; + nodeParams.pMacroInitialOffsetB = 3; + nodeParams.pMicroInitialOffsetA = 6; + nodeParams.pMicroInitialOffsetB = 6; + nodeParams.pMicroPerCycle = 200000; + nodeParams.pOffsetCorrectionOut = 127; + nodeParams.pOffsetCorrectionStart = 3632; + nodeParams.pRateCorrectionOut = 81; + nodeParams.pWakeupChannel = FlexrayChannel::A; + nodeParams.pWakeupPattern = 33; + nodeParams.pdMicrotick = FlexrayClockPeriod::T25NS; + nodeParams.pSamplesPerMicrotick = 2; + nodeParams.pKeySlotId = 40; + + std::vector bufferConfigs; + + FlexrayTxBufferConfig bufferCfg; + bufferCfg.channels = FlexrayChannel::AB; + bufferCfg.slotId = 40; + bufferCfg.offset = 0; + bufferCfg.repetition = 1; + bufferCfg.hasPayloadPreambleIndicator = false; + bufferCfg.headerCrc = 5; + bufferCfg.transmissionMode = FlexrayTransmissionMode::SingleShot; + bufferConfigs.push_back(bufferCfg); + + bufferCfg.channels = FlexrayChannel::A; + bufferCfg.slotId = 41; + bufferConfigs.push_back(bufferCfg); + + bufferCfg.channels = FlexrayChannel::B; + bufferCfg.slotId = 42; + bufferConfigs.push_back(bufferCfg); + + SilKit::Services::Flexray::FlexrayControllerConfig config; + config.bufferConfigs = bufferConfigs; + config.clusterParams = clusterParams; + config.nodeParams = nodeParams; + + controller->Configure(config); + }); + } + + void OnetimeActions(std::chrono::nanoseconds now, IFlexrayController* controller) + { + if (now == 0ns) + { + // Trigger OnHostCommand + controller->Wakeup(); + + // Trigger OnTxBufferConfigUpdate + FlexrayTxBufferConfig bufferCfg{}; + bufferCfg.channels = FlexrayChannel::AB; + controller->ReconfigureTxBuffer(0, bufferCfg); // idx 0 -> slotId 40 + + // Trigger OnTxBufferUpdate + SilKit::Services::Flexray::FlexrayTxBufferUpdate txBufferUpdate{}; + txBufferUpdate.txBufferIndex = 0; + txBufferUpdate.payloadDataValid = true; + std::vector payloadBytes{1, 2, 3}; + txBufferUpdate.payload = payloadBytes; + controller->UpdateTxBuffer(txBufferUpdate); + } + } + + void SendFlexrayFrames(MySimulatedNetwork* mySimulatedNetwork, std::chrono::nanoseconds now, + std::atomic_uint& sendCount) + { + // Called by the netsim, not by controllers + + if (now < _sendUntilMs) + { + for (size_t i = 0; i < _numFramesPerSimStep; ++i) + { + FlexrayFrameEvent frameEvent{}; + std::vector payloadBytes{1, 2, 3}; + FlexrayFrame frame{}; + frame.payload = payloadBytes; + frameEvent.frame = frame; + mySimulatedNetwork->GetFlexRayEventProducer()->Produce( + frameEvent, mySimulatedNetwork->GetAllControllerDescriptors()); + + FlexrayFrameTransmitEvent frameTransmitEvent{}; + frameTransmitEvent.txBufferIndex = 0; + frameTransmitEvent.frame = frame; + mySimulatedNetwork->GetFlexRayEventProducer()->Produce( + frameTransmitEvent, mySimulatedNetwork->GetAllControllerDescriptors()); + + sendCount++; + } + } + } +}; + +class MySimulatedFlexrayController + : public MySimulatedController + , public ISimulatedFlexRayController +{ +public: + MySimulatedFlexrayController(MySimulatedNetwork* mySimulatedNetwork, ControllerDescriptor controllerDescriptor) + : MySimulatedController(mySimulatedNetwork, controllerDescriptor) + { + } + + void OnHostCommand(const FlexrayHostCommand& msg) override; + void OnControllerConfig( + const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig& msg) override; + void OnTxBufferConfigUpdate(const FlexrayTxBufferConfigUpdate& msg) override; + void OnTxBufferUpdate(const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate& msg) override; +}; + + +auto MySimulatedNetwork::ProvideSimulatedController(ControllerDescriptor controllerDescriptor) -> ISimulatedController* +{ + callCounts.simulatedNetwork.ProvideSimulatedController++; + _controllerDescriptors.push_back(controllerDescriptor); + + switch (_networkType) + { + case SimulatedNetworkType::FlexRay: + { + _mySimulatedControllers.emplace_back( + std::make_unique(this, controllerDescriptor)); + return _mySimulatedControllers.back().get(); + } + default: + break; + } + + return {}; +} + +// ISimulatedFlexrayController + +void MySimulatedFlexrayController::OnHostCommand(const FlexrayHostCommand& msg) +{ + callCounts.netSimFlexray.OnHostCommand++; + + if (msg.command == FlexrayChiCommand::WAKEUP) + { + FlexrayPocStatusEvent pocStatusEvent{}; + pocStatusEvent.wakeupStatus = FlexrayWakeupStatusType::Transmitted; + _mySimulatedNetwork->GetFlexRayEventProducer()->Produce(pocStatusEvent, + _mySimulatedNetwork->GetAllControllerDescriptors()); + + FlexrayCycleStartEvent cycleStartEvent{}; + cycleStartEvent.cycleCounter = 1; + _mySimulatedNetwork->GetFlexRayEventProducer()->Produce(cycleStartEvent, + _mySimulatedNetwork->GetAllControllerDescriptors()); + + FlexraySymbolEvent symbolEvent{}; + symbolEvent.pattern = FlexraySymbolPattern::Wus; // Triggers Wakeup handler + Symbol handler + _mySimulatedNetwork->GetFlexRayEventProducer()->Produce(symbolEvent, + _mySimulatedNetwork->GetAllControllerDescriptors()); + + FlexraySymbolTransmitEvent symbolTransmitEvent{}; + symbolTransmitEvent.pattern = FlexraySymbolPattern::Wus; // SymbolTransmit handler + std::array receiverArray{_controllerDescriptor}; + auto receiver = SilKit::Util::MakeSpan(receiverArray); + _mySimulatedNetwork->GetFlexRayEventProducer()->Produce(symbolTransmitEvent, receiver); + } +} + +void MySimulatedFlexrayController::OnControllerConfig( + const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig& /*msg*/) +{ + callCounts.netSimFlexray.OnControllerConfig++; +} + +void MySimulatedFlexrayController::OnTxBufferConfigUpdate(const FlexrayTxBufferConfigUpdate& /*msg*/) +{ + callCounts.netSimFlexray.OnTxBufferConfigUpdate++; +} + +void MySimulatedFlexrayController::OnTxBufferUpdate( + const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate& /*msg*/) +{ + callCounts.netSimFlexray.OnTxBufferUpdate++; +} + +// Testing NetSim API with FlexRay +// Covers: +// - Trivial and simulated FlexrayControllers in one simulation +// - Correct routing of simulated FlexRay messages +// - Network Simulator participant has FlexrayControllers itself + +TEST_F(ITest_NetSimFlexray, basic_networksimulation_flexray) +{ + { + // ---------------------------- + // NetworkSimulator + // ---------------------------- + + //auto configWithLogging = MakeParticipantConfigurationStringWithLogging(SilKit::Services::Logging::Level::Info); + auto&& simParticipant = _simTestHarness->GetParticipant(_participantNameNetSim); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& networkSimulator = simParticipant->GetOrCreateNetworkSimulator(); + + auto simulatedNetwork = + std::make_unique(SimulatedNetworkType::FlexRay, _simulatedNetworkName); + auto simulatedNetworkPtr = simulatedNetwork.get(); + networkSimulator->SimulateNetwork(_simulatedNetworkName, SimulatedNetworkType::FlexRay, + std::move(simulatedNetwork)); + + for (const auto& emptyNetworkName : _emptyNetworks) + { + auto emptyFlexrayNetwork = + std::make_unique(SimulatedNetworkType::FlexRay, emptyNetworkName); + networkSimulator->SimulateNetwork(emptyNetworkName, SimulatedNetworkType::FlexRay, + std::move(emptyFlexrayNetwork)); + } + + // The network simulator has a simulated controller as well + auto&& participant = simParticipant->Participant(); + auto&& flexrayController = participant->CreateFlexrayController("FlexRay1", _simulatedNetworkName); + SetupFlexrayController(lifecycleService, flexrayController, callCounts.silKitHandlersFlexray); + + networkSimulator->Start(); + + timeSyncService->SetSimulationStepHandler( + [this, simulatedNetworkPtr, lifecycleService, flexrayController]( + auto now, const std::chrono::nanoseconds /*duration*/) { + if (now == _stopAtMs) + { + lifecycleService->Stop("stopping the simulation"); + } + else + { + OnetimeActions(now, flexrayController); + SendFlexrayFrames(simulatedNetworkPtr, now, callCounts.silKitSentMsgFlexray.SentFrames); + } + }, + _stepSize); + } + + { + // ---------------------------- + // Simulated Participants + // ---------------------------- + + for (const auto& participantName : _participantNamesSimulated) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& flexrayController = participant->CreateFlexrayController("FlexRay1", _simulatedNetworkName); + SetupFlexrayController(lifecycleService, flexrayController, callCounts.silKitHandlersFlexray); + + timeSyncService->SetSimulationStepHandler( + [this, flexrayController](auto now, const std::chrono::nanoseconds /*duration*/) { + OnetimeActions(now, flexrayController); + }, _stepSize); + } + } + + { + // ---------------------------- + // Dummy Trivial Participants + // ---------------------------- + + for (const auto& participantName : _participantNamesTrivial) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + timeSyncService->SetSimulationStepHandler([](auto /*now*/, const std::chrono::nanoseconds /*duration*/) {}, + _stepSize); + } + } + + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + + const size_t numSimulatedFlexrayControllers = + _numParticipantsSimulated + 1; // +1 for the FlexRay controller on the Netsim participant + const size_t numSentFramesSimulated = _numFramesPerSimStep * _numSimSteps; + const size_t numReceivedFramesSimulated = numSimulatedFlexrayControllers * numSentFramesSimulated; + + EXPECT_EQ(callCounts.simulatedNetwork.EventProducer, _numSimulatedNetworks); + EXPECT_EQ(callCounts.simulatedNetwork.ProvideSimulatedController, numSimulatedFlexrayControllers); + + EXPECT_EQ(callCounts.silKitSentMsgFlexray.SentFrames, numSentFramesSimulated); + EXPECT_EQ(callCounts.silKitHandlersFlexray.FrameHandler, numReceivedFramesSimulated); + EXPECT_EQ(callCounts.silKitHandlersFlexray.FrameTransmitHandler, numReceivedFramesSimulated); + + // Every controller calls Wakeup(), netsim broadcasts back to all controllers: n*n + const size_t numSimulatedFlexrayControllersSq = numSimulatedFlexrayControllers * numSimulatedFlexrayControllers; + EXPECT_EQ(callCounts.silKitHandlersFlexray.PocStatusHandler, numSimulatedFlexrayControllersSq); + EXPECT_EQ(callCounts.silKitHandlersFlexray.CycleStartHandler, numSimulatedFlexrayControllersSq); + EXPECT_EQ(callCounts.silKitHandlersFlexray.SymbolHandler, numSimulatedFlexrayControllersSq); + EXPECT_EQ(callCounts.silKitHandlersFlexray.WakeupHandler, numSimulatedFlexrayControllersSq); + + // Here, SymbolTransmitEvent is sent back only to the triggering controller + EXPECT_EQ(callCounts.silKitHandlersFlexray.SymbolTransmitHandler, numSimulatedFlexrayControllers); + + // Every controller does these actions once + EXPECT_EQ(callCounts.netSimFlexray.OnControllerConfig, numSimulatedFlexrayControllers); + EXPECT_EQ(callCounts.netSimFlexray.OnHostCommand, numSimulatedFlexrayControllers); + EXPECT_EQ(callCounts.netSimFlexray.OnTxBufferConfigUpdate, numSimulatedFlexrayControllers); + EXPECT_EQ(callCounts.netSimFlexray.OnTxBufferUpdate, numSimulatedFlexrayControllers); +} + +} //end namespace diff --git a/SilKit/IntegrationTests/ITest_NetSimLin.cpp b/SilKit/IntegrationTests/ITest_NetSimLin.cpp new file mode 100644 index 000000000..c22c69e94 --- /dev/null +++ b/SilKit/IntegrationTests/ITest_NetSimLin.cpp @@ -0,0 +1,628 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "ITest_NetSim.hpp" +#include "silkit/services/lin/all.hpp" +#include "silkit/experimental/services/lin/LinControllerExtensions.hpp" + +namespace { + +using namespace std::chrono_literals; + +using namespace SilKit::Tests; +using namespace SilKit::Config; +using namespace SilKit::Services; +using namespace SilKit::Experimental::NetworkSimulation; + +using namespace SilKit::Services::Lin; +using namespace SilKit::Experimental::NetworkSimulation::Lin; + + +struct ITest_NetSimLin : ITest_NetSim +{ + void SendLinFrameHeaders(std::chrono::nanoseconds now, ILinController* controller, std::atomic_uint& sendCount) + { + if (now < _sendUntilMs) + { + for (size_t i = 0; i < _numFramesPerSimStep; ++i) + { + controller->SendFrameHeader(34); + sendCount++; + } + } + } + + void SendLinFrames(std::chrono::nanoseconds now, ILinController* controller, std::atomic_uint& sendCount) + { + LinFrame frame{}; + frame.checksumModel = LinChecksumModel::Classic; + frame.id = 16; + frame.dataLength = 8; + frame.data = std::array{3, 4, 3, 4, 3, 4, 3, 4}; + + if (now < _sendUntilMs) + { + for (size_t i = 0; i < _numFramesPerSimStep; ++i) + { + controller->SendFrame(frame, LinFrameResponseType::MasterResponse); + sendCount++; + } + } + } + + void WakeupOnce(std::chrono::nanoseconds now, ILinController* controller) + { + if (now == 0ns) + { + controller->Wakeup(); + } + } + + void GoToSleepOnce(std::chrono::nanoseconds now, ILinController* controller) + { + if (now == 0ns) + { + controller->GoToSleep(); // Sends a GoToSleepFrame + ControllerStatusUpdate + } + } + + void SetupLinController(Orchestration::ILifecycleService* lifecycleService, ILinController* controller, + CallCountsSilKitHandlersLin& callCountsSilKitHandlersLin, bool isMaster, bool isDynamic) + { + controller->AddFrameStatusHandler( + [&callCountsSilKitHandlersLin](ILinController*, const LinFrameStatusEvent& /*msg*/) { + callCountsSilKitHandlersLin.FrameStatusHandler++; + }); + SilKit::Experimental::Services::Lin::AddFrameHeaderHandler( + controller, + [isMaster, isDynamic, &callCountsSilKitHandlersLin]( + ILinController* controller, const SilKit::Experimental::Services::Lin::LinFrameHeaderEvent& /*msg*/) { + callCountsSilKitHandlersLin.FrameHeaderHandler++; + + ASSERT_TRUE(isDynamic); + + LinFrame frame{}; + frame.checksumModel = LinChecksumModel::Classic; + frame.id = 16; + frame.dataLength = 8; + frame.data = std::array{3, 4, 3, 4, 3, 4, 3, 4}; + if (isMaster) + { + // Sends a LinFrameResponseUpdate + SilKit::Experimental::Services::Lin::SendDynamicResponse(controller, frame); + } + }); + controller->AddGoToSleepHandler( + [&callCountsSilKitHandlersLin](ILinController*, const LinGoToSleepEvent& /*msg*/) { + callCountsSilKitHandlersLin.GoToSleepHandler++; + }); + controller->AddWakeupHandler([&callCountsSilKitHandlersLin](ILinController*, const LinWakeupEvent& /*msg*/) { + callCountsSilKitHandlersLin.WakeupHandler++; + }); + + lifecycleService->SetCommunicationReadyHandler([isMaster, isDynamic, controller] { + if (isDynamic) + { + SilKit::Experimental::Services::Lin::LinControllerDynamicConfig config{}; + config.baudRate = 20'000; + config.controllerMode = isMaster ? LinControllerMode::Master : LinControllerMode::Slave; + SilKit::Experimental::Services::Lin::InitDynamic(controller, config); + } + else + { + SilKit::Services::Lin::LinControllerConfig config{}; + config.baudRate = 20'000; + + if (isMaster) + { + LinFrameResponse response_16; + response_16.frame.id = 16; + response_16.frame.checksumModel = LinChecksumModel::Classic; + response_16.frame.dataLength = 8; + response_16.frame.data = std::array{3, 4, 3, 4, 3, 4, 3, 4}; + response_16.responseMode = LinFrameResponseMode::TxUnconditional; + + LinFrameResponse response_34; + response_34.frame.id = 34; + response_34.frame.checksumModel = LinChecksumModel::Enhanced; + response_34.frame.dataLength = 6; + response_34.responseMode = LinFrameResponseMode::Rx; + + config.controllerMode = LinControllerMode::Master; + config.frameResponses.push_back(response_16); + config.frameResponses.push_back(response_34); + } + else + { + LinFrameResponse response_16; + response_16.frame.id = 16; + response_16.frame.checksumModel = LinChecksumModel::Classic; + response_16.frame.dataLength = 8; + response_16.responseMode = LinFrameResponseMode::Rx; + + LinFrameResponse response_34; + response_34.frame.id = 34; + response_34.frame.checksumModel = LinChecksumModel::Enhanced; + response_34.frame.dataLength = 8; + response_34.frame.data = std::array{1, 2, 3, 4, 3, 4, 3, 4}; + response_34.responseMode = LinFrameResponseMode::TxUnconditional; + + config.controllerMode = LinControllerMode::Slave; + config.frameResponses.push_back(response_16); + config.frameResponses.push_back(response_34); + } + + controller->Init(config); + } + }); + } +}; + +class MySimulatedLinController + : public MySimulatedController + , public ISimulatedLinController +{ +public: + MySimulatedLinController(MySimulatedNetwork* mySimulatedNetwork, ControllerDescriptor controllerDescriptor, + bool isDynamic = false) + : MySimulatedController(mySimulatedNetwork, controllerDescriptor) + , _isDynamic{isDynamic} + { + } + void OnFrameRequest(const LinFrameRequest& linFrameRequest) override; + void OnFrameHeaderRequest(const LinFrameHeaderRequest& linFrameHeaderRequest) override; + void OnWakeupPulse(const LinWakeupPulse& linWakeupPulse) override; + void OnControllerConfig( + const SilKit::Experimental::NetworkSimulation::Lin::LinControllerConfig& linControllerConfig) override; + void OnFrameResponseUpdate(const LinFrameResponseUpdate& linFrameResponseUpdate) override; + void OnControllerStatusUpdate(const LinControllerStatusUpdate& linControllerStatusUpdate) override; + + bool _isDynamic; +}; + +auto MySimulatedNetwork::ProvideSimulatedController(ControllerDescriptor controllerDescriptor) -> ISimulatedController* +{ + callCounts.simulatedNetwork.ProvideSimulatedController++; + _controllerDescriptors.push_back(controllerDescriptor); + + switch (_networkType) + { + case SimulatedNetworkType::LIN: + { + _mySimulatedControllers.emplace_back( + std::make_unique(this, controllerDescriptor, _isLinDynamic)); + return _mySimulatedControllers.back().get(); + } + default: + break; + } + + return {}; +} + +// ISimulatedLinController + +void MySimulatedLinController::OnFrameRequest(const LinFrameRequest& linFrameRequest) +{ + callCounts.netSimLin.OnFrameRequest++; + + if (linFrameRequest.frame.id == 60) + { + return; // Don't distribute GoToSleepFrame, done in OnControllerStatusUpdate + } + + LinFrameStatusEvent frameStatusEvent{}; + frameStatusEvent.status = LinFrameStatus::LIN_RX_OK; + + _mySimulatedNetwork->GetLinEventProducer()->Produce(frameStatusEvent, + _mySimulatedNetwork->GetAllControllerDescriptors()); +} + +void MySimulatedLinController::OnFrameHeaderRequest(const LinFrameHeaderRequest& linFrameHeaderRequest) +{ + callCounts.netSimLin.OnFrameHeaderRequest++; + + LinSendFrameHeaderRequest frameHeaderRequest{}; + frameHeaderRequest.id = linFrameHeaderRequest.id; + + _mySimulatedNetwork->GetLinEventProducer()->Produce(frameHeaderRequest, + _mySimulatedNetwork->GetAllControllerDescriptors()); +} + +void MySimulatedLinController::OnWakeupPulse(const LinWakeupPulse& /*linWakeupPulse*/) +{ + callCounts.netSimLin.OnWakeupPulse++; + + LinWakeupEvent wakeupEvent{}; + _mySimulatedNetwork->GetLinEventProducer()->Produce(wakeupEvent, + _mySimulatedNetwork->GetAllControllerDescriptors()); +} + +void MySimulatedLinController::OnControllerConfig( + const SilKit::Experimental::NetworkSimulation::Lin::LinControllerConfig& /*linControllerConfig*/) +{ + callCounts.netSimLin.OnControllerConfig++; +} + +void MySimulatedLinController::OnFrameResponseUpdate(const LinFrameResponseUpdate& /*linFrameResponseUpdate*/) +{ + callCounts.netSimLin.OnFrameResponseUpdate++; + + if (_isDynamic) + { + // In dynamic mode, path is: + // controller->SendFrameHeader(): SendMsg(LinSendFrameHeaderRequest) + // netsim->OnFrameHeaderRequest(): Produce(LinSendFrameHeaderRequest) + // Controller::FrameHeaderHandler(): SendDynamicResponse -> SendMsg(LinFrameResponseUpdate) + // netsim->OnFrameResponseUpdate(): Produce(LinFrameStatusEvent) + // Controller::FrameStatusHandler() + + LinFrameStatusEvent frameStatusEvent{}; + frameStatusEvent.status = LinFrameStatus::LIN_RX_OK; + + _mySimulatedNetwork->GetLinEventProducer()->Produce(frameStatusEvent, + _mySimulatedNetwork->GetAllControllerDescriptors()); + } +} + +void MySimulatedLinController::OnControllerStatusUpdate(const LinControllerStatusUpdate& linControllerStatusUpdate) +{ + callCounts.netSimLin.OnControllerStatusUpdate++; + + if (linControllerStatusUpdate.status == LinControllerStatus::SleepPending) + { + LinFrameStatusEvent goToSleepFrame{}; + goToSleepFrame.status = LinFrameStatus::LIN_RX_OK; + goToSleepFrame.frame.id = 60; + goToSleepFrame.frame.dataLength = 8; + goToSleepFrame.frame.data = {0x0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; + + _mySimulatedNetwork->GetLinEventProducer()->Produce(goToSleepFrame, + _mySimulatedNetwork->GetAllControllerDescriptors()); + } +} + +// Testing NetSim API with LIN +// Covers: +// - Trivial and simulated LinControllers in one simulation +// - Correct routing of simulated LIN messages +// - Network Simulator participant has LinControllers itself + +TEST_F(ITest_NetSimLin, basic_networksimulation_lin) +{ + { + // ---------------------------- + // NetworkSimulator, LIN slave + // ---------------------------- + + //auto configWithLogging = MakeParticipantConfigurationStringWithLogging(SilKit::Services::Logging::Level::Info); + auto&& simParticipant = _simTestHarness->GetParticipant(_participantNameNetSim); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& networkSimulator = simParticipant->GetOrCreateNetworkSimulator(); + + auto simulatedNetwork = std::make_unique(SimulatedNetworkType::LIN, _simulatedNetworkName); + networkSimulator->SimulateNetwork(_simulatedNetworkName, SimulatedNetworkType::LIN, + std::move(simulatedNetwork)); + + for (const auto& emptyNetworkName : _emptyNetworks) + { + auto emptyLinNetwork = + std::make_unique(SimulatedNetworkType::FlexRay, emptyNetworkName); + networkSimulator->SimulateNetwork(emptyNetworkName, SimulatedNetworkType::FlexRay, + std::move(emptyLinNetwork)); + } + + // The network simulator has a simulated controller as well + auto&& participant = simParticipant->Participant(); + auto&& linController = participant->CreateLinController("LIN1", _simulatedNetworkName); + SetupLinController(lifecycleService, linController, callCounts.silKitHandlersLinSimulated, false, false); + + networkSimulator->Start(); + + timeSyncService->SetSimulationStepHandler( + [this, lifecycleService](auto now, const std::chrono::nanoseconds /*duration*/) { + if (now == _stopAtMs) + { + lifecycleService->Stop("stopping the simulation"); + } + }, _stepSize); + } + + { + // ------------------------------------------------------------------ + // Simulated Participants, first one is LIN master, others are slaves + // ------------------------------------------------------------------ + + bool isLinMaster = true; + for (const auto& participantName : _participantNamesSimulated) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& linController = participant->CreateLinController("LIN1", _simulatedNetworkName); + SetupLinController(lifecycleService, linController, callCounts.silKitHandlersLinSimulated, isLinMaster, + false); + + timeSyncService->SetSimulationStepHandler( + [this, linController, isLinMaster](auto now, const std::chrono::nanoseconds /*duration*/) { + if (isLinMaster) + { + SendLinFrames(now, linController, callCounts.silKitSentMsgLin.SentFramesSimulated); + SendLinFrameHeaders(now, linController, callCounts.silKitSentMsgLin.SentFrameHeadersSimulated); + GoToSleepOnce(now, linController); + WakeupOnce(now, linController); + } + }, _stepSize); + + isLinMaster = false; + } + } + + { + // ---------------------------------------------------------------- + // Trivial Participants, first one is LIN master, others are slaves + // ---------------------------------------------------------------- + + bool isLinMaster = true; + for (const auto& participantName : _participantNamesTrivial) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& linController = participant->CreateLinController("LIN1", _trivialNetworkName); + + SetupLinController(lifecycleService, linController, callCounts.silKitHandlersLinTrivial, isLinMaster, + false); + + timeSyncService->SetSimulationStepHandler( + [this, linController, isLinMaster](auto now, const std::chrono::nanoseconds /*duration*/) { + if (isLinMaster) + { + SendLinFrames(now, linController, callCounts.silKitSentMsgLin.SentFramesTrivial); + SendLinFrameHeaders(now, linController, callCounts.silKitSentMsgLin.SentFrameHeadersTrivial); + GoToSleepOnce(now, linController); + WakeupOnce(now, linController); + } + }, _stepSize); + + isLinMaster = false; + } + } + + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + + const size_t numSimulatedLinControllers = + _numParticipantsSimulated + 1; // +1 for the LIN controller on the Netsim participant + const size_t numTrivialLinControllers = _numParticipantsTrivial; + const size_t numSentFramesSimulated = + 1 * _numFramesPerSimStep * _numSimSteps; // Only the single master will send (1 * ...) + const size_t numSentFrameHeadersSimulated = 1 * _numFramesPerSimStep * _numSimSteps; + const size_t numSentFramesTrivial = 1 * _numFramesPerSimStep * _numSimSteps; + const size_t numSentFrameHeadersTrivial = 1 * _numFramesPerSimStep * _numSimSteps; + + EXPECT_EQ(callCounts.simulatedNetwork.EventProducer, _numSimulatedNetworks); + EXPECT_EQ(callCounts.simulatedNetwork.ProvideSimulatedController, numSimulatedLinControllers); + + // + 1 for GoToSleepFrame + EXPECT_EQ(callCounts.silKitHandlersLinSimulated.FrameStatusHandler, + (numSentFramesSimulated + 1) * numSimulatedLinControllers); + + // + 1 for GoToSleepFrame + // Trivial: SendFrameHeader also leads to FrameStatusHandler if ID is configured for TX -> numSentFrameHeadersTrivial included + EXPECT_EQ(callCounts.silKitHandlersLinTrivial.FrameStatusHandler, + (numSentFramesTrivial + numSentFrameHeadersTrivial) * numTrivialLinControllers + 1); + + // Not dynamic: No Handler triggered + // See: LinController::ReceiveMsg(const IServiceEndpoint* from, const LinSendFrameHeaderRequest& msg) + EXPECT_EQ(callCounts.silKitHandlersLinSimulated.FrameHeaderHandler, 0); + // Trivial: No Handler triggered, but a LinTransmission and thus FrameStatusHandler + EXPECT_EQ(callCounts.silKitHandlersLinTrivial.FrameHeaderHandler, 0); + + // - 1 because the handler is not called on the master + EXPECT_EQ(callCounts.silKitHandlersLinSimulated.GoToSleepHandler, numSimulatedLinControllers - 1); + EXPECT_EQ(callCounts.silKitHandlersLinTrivial.GoToSleepHandler, numTrivialLinControllers - 1); + + EXPECT_EQ(callCounts.silKitHandlersLinSimulated.WakeupHandler, numSimulatedLinControllers); + EXPECT_EQ(callCounts.silKitHandlersLinTrivial.WakeupHandler, numTrivialLinControllers); + + // +1 for GoToSleepFrame + EXPECT_EQ(callCounts.netSimLin.OnFrameRequest, numSentFramesSimulated + 1); + + EXPECT_EQ(callCounts.netSimLin.OnFrameHeaderRequest, numSentFrameHeadersSimulated); + + // Oneshot by the masters ILinController::Wakeup + EXPECT_EQ(callCounts.netSimLin.OnWakeupPulse, 1); + + EXPECT_EQ(callCounts.netSimLin.OnControllerConfig, numSimulatedLinControllers); + + // linController->SendFrame will send a LinFrameResponseUpdate+LinSendFrameRequest + EXPECT_EQ(callCounts.netSimLin.OnFrameResponseUpdate, numSentFramesSimulated); + + // Once via ILinController::Wakeup, once via ILinController::GoToSleep + EXPECT_EQ(callCounts.netSimLin.OnControllerStatusUpdate, 2); + + EXPECT_EQ(callCounts.silKitSentMsgLin.SentFramesSimulated, numSentFramesSimulated); + EXPECT_EQ(callCounts.silKitSentMsgLin.SentFrameHeadersSimulated, numSentFrameHeadersSimulated); + EXPECT_EQ(callCounts.silKitSentMsgLin.SentFramesTrivial, numSentFramesTrivial); + EXPECT_EQ(callCounts.silKitSentMsgLin.SentFrameHeadersTrivial, numSentFrameHeadersTrivial); +} + + +// Testing NetSim API with LIN Experimental Dynamic Mode + +TEST_F(ITest_NetSimLin, networksimulation_lin_dynamic) +{ + const bool isDynamic = true; + { + // ---------------------------- + // NetworkSimulator, LIN slave + // ---------------------------- + + //auto configWithLogging = MakeParticipantConfigurationStringWithLogging(SilKit::Services::Logging::Level::Info); + auto&& simParticipant = _simTestHarness->GetParticipant(_participantNameNetSim); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& networkSimulator = simParticipant->GetOrCreateNetworkSimulator(); + + auto simulatedNetwork = + std::make_unique(SimulatedNetworkType::LIN, _simulatedNetworkName, isDynamic); + networkSimulator->SimulateNetwork(_simulatedNetworkName, SimulatedNetworkType::LIN, + std::move(simulatedNetwork)); + + for (const auto& emptyNetworkName : _emptyNetworks) + { + auto emptyLinNetwork = + std::make_unique(SimulatedNetworkType::FlexRay, emptyNetworkName); + networkSimulator->SimulateNetwork(emptyNetworkName, SimulatedNetworkType::FlexRay, + std::move(emptyLinNetwork)); + } + + // The network simulator has a simulated controller as well + auto&& participant = simParticipant->Participant(); + auto&& linController = participant->CreateLinController("LIN1", _simulatedNetworkName); + SetupLinController(lifecycleService, linController, callCounts.silKitHandlersLinSimulated, false, isDynamic); + + networkSimulator->Start(); + + timeSyncService->SetSimulationStepHandler( + [this, lifecycleService](auto now, const std::chrono::nanoseconds /*duration*/) { + if (now == _stopAtMs) + { + lifecycleService->Stop("stopping the simulation"); + } + }, _stepSize); + } + + { + // ------------------------------------------------------------------ + // Simulated Participants, first one is LIN master, others are slaves + // ------------------------------------------------------------------ + + bool isLinMaster = true; + for (const auto& participantName : _participantNamesSimulated) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& linController = participant->CreateLinController("LIN1", _simulatedNetworkName); + SetupLinController(lifecycleService, linController, callCounts.silKitHandlersLinSimulated, isLinMaster, + isDynamic); + + timeSyncService->SetSimulationStepHandler( + [this, linController, isLinMaster](auto now, const std::chrono::nanoseconds /*duration*/) { + if (isLinMaster) + { + // Dynamic mode: Only send frameHeaders + SendLinFrameHeaders(now, linController, callCounts.silKitSentMsgLin.SentFrameHeadersSimulated); + GoToSleepOnce(now, linController); + WakeupOnce(now, linController); + } + }, _stepSize); + + isLinMaster = false; + } + } + + { + // ---------------------------------------------------------------- + // Trivial Participants, first one is LIN master, others are slaves + // ---------------------------------------------------------------- + + bool isLinMaster = true; + for (const auto& participantName : _participantNamesTrivial) + { + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + auto&& participant = simParticipant->Participant(); + auto&& linController = participant->CreateLinController("LIN1", _trivialNetworkName); + + // Not dynamic! + SetupLinController(lifecycleService, linController, callCounts.silKitHandlersLinTrivial, isLinMaster, + false); + + timeSyncService->SetSimulationStepHandler( + [this, linController, isLinMaster](auto now, const std::chrono::nanoseconds /*duration*/) { + if (isLinMaster) + { + SendLinFrames(now, linController, callCounts.silKitSentMsgLin.SentFramesTrivial); + SendLinFrameHeaders(now, linController, callCounts.silKitSentMsgLin.SentFrameHeadersTrivial); + WakeupOnce(now, linController); + GoToSleepOnce(now, linController); + } + }, _stepSize); + + isLinMaster = false; + } + } + + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + + const size_t numSimulatedLinControllers = + _numParticipantsSimulated + 1; // +1 for the LIN controller on the Netsim participant + const size_t numTrivialLinControllers = _numParticipantsTrivial; + const size_t numSentFramesSimulated = 0; // No direct call of SendFrame in dynamic mode + const size_t numSentFrameHeadersSimulated = 1 * _numFramesPerSimStep * _numSimSteps; + const size_t numSentFramesTrivial = 1 * _numFramesPerSimStep * _numSimSteps; + const size_t numSentFrameHeadersTrivial = 1 * _numFramesPerSimStep * _numSimSteps; + + EXPECT_EQ(callCounts.simulatedNetwork.EventProducer, _numSimulatedNetworks); + EXPECT_EQ(callCounts.simulatedNetwork.ProvideSimulatedController, numSimulatedLinControllers); + + // Each sent FrameHeader leads to a Transmission + 1 for GoToSleepFrame + EXPECT_EQ(callCounts.silKitHandlersLinSimulated.FrameStatusHandler, + (numSentFrameHeadersSimulated + 1) * numSimulatedLinControllers); + + // + 1 for GoToSleepFrame + // Trivial: SendFrameHeader also leads to FrameStatusHandler if ID is configured for TX -> numSentFrameHeadersTrivial included + EXPECT_EQ(callCounts.silKitHandlersLinTrivial.FrameStatusHandler, + (numSentFramesTrivial + numSentFrameHeadersTrivial) * numTrivialLinControllers + 1); + + // Dynamic: Handler triggered + // See: LinController::ReceiveMsg(const IServiceEndpoint* from, const LinSendFrameHeaderRequest& msg) + EXPECT_EQ(callCounts.silKitHandlersLinSimulated.FrameHeaderHandler, + numSentFrameHeadersSimulated * numSimulatedLinControllers); + // Trivial: No Handler triggered, but a LinTransmission and thus FrameStatusHandler + EXPECT_EQ(callCounts.silKitHandlersLinTrivial.FrameHeaderHandler, 0); + + // - 1 because the handler is not called on the master + EXPECT_EQ(callCounts.silKitHandlersLinSimulated.GoToSleepHandler, numSimulatedLinControllers - 1); + EXPECT_EQ(callCounts.silKitHandlersLinTrivial.GoToSleepHandler, numTrivialLinControllers - 1); + + EXPECT_EQ(callCounts.silKitHandlersLinSimulated.WakeupHandler, numSimulatedLinControllers); + EXPECT_EQ(callCounts.silKitHandlersLinTrivial.WakeupHandler, numTrivialLinControllers); + + // Only the GoToSleepFrame comes in as a FrameRequest in dynamic mode + EXPECT_EQ(callCounts.netSimLin.OnFrameRequest, 1); + + EXPECT_EQ(callCounts.netSimLin.OnFrameHeaderRequest, numSentFrameHeadersSimulated); + + // Oneshot by the masters ILinController::Wakeup + EXPECT_EQ(callCounts.netSimLin.OnWakeupPulse, 1); + + EXPECT_EQ(callCounts.netSimLin.OnControllerConfig, numSimulatedLinControllers); + + // linController->SendFrameHeader leads to a LinFrameResponseUpdate via SendDynamicResponse + EXPECT_EQ(callCounts.netSimLin.OnFrameResponseUpdate, numSentFrameHeadersSimulated); + + // Once via ILinController::Wakeup, once via ILinController::GoToSleep + EXPECT_EQ(callCounts.netSimLin.OnControllerStatusUpdate, 2); + + EXPECT_EQ(callCounts.silKitSentMsgLin.SentFramesSimulated, numSentFramesSimulated); + EXPECT_EQ(callCounts.silKitSentMsgLin.SentFrameHeadersSimulated, numSentFrameHeadersSimulated); + EXPECT_EQ(callCounts.silKitSentMsgLin.SentFramesTrivial, numSentFramesTrivial); + EXPECT_EQ(callCounts.silKitSentMsgLin.SentFrameHeadersTrivial, numSentFrameHeadersTrivial); +} + +} //end namespace diff --git a/SilKit/IntegrationTests/ITest_Orchestration.cpp b/SilKit/IntegrationTests/ITest_Orchestration.cpp index 8f559ebe9..13ef52b5c 100644 --- a/SilKit/IntegrationTests/ITest_Orchestration.cpp +++ b/SilKit/IntegrationTests/ITest_Orchestration.cpp @@ -36,89 +36,88 @@ using namespace SilKit::Services::Can; struct StopTestState { - // Test Results - std::atomic lastNow{}; + // Test Results + std::atomic lastNow{}; }; TEST_F(ITest_Orchestration, stop_in_simtask_does_not_trigger_simtask_again) { - std::vector canParticipantNames; - for (char participantSuffix = 'A'; participantSuffix <= 'K'; ++participantSuffix) - { - canParticipantNames.emplace_back(std::string{"CanParticipant"} + participantSuffix); - } - - { - auto participantNames = canParticipantNames; - participantNames.emplace_back("SimulationStopper"); - SetupFromParticipantList(participantNames); - } - - auto state = std::make_shared(); - - // Set up the Sending and receiving participants - { - ///////////////////////////////////////////////////////////////////////// - // SimulationStopper - ///////////////////////////////////////////////////////////////////////// - const auto participantName = "SimulationStopper"; - auto&& simParticipant = _simTestHarness->GetParticipant(participantName); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - - timeSyncService->SetSimulationStepHandler( - [state, lifecycleService](auto now, const std::chrono::nanoseconds /*duration*/) { - state->lastNow = now; - - if (now == 5ms) - { - lifecycleService->Stop("stopping the simulation through another participant"); - } - }, - 1ms); - } - - for (const auto& participantName : canParticipantNames) - { - ///////////////////////////////////////////////////////////////////////// - // CAN Participants - ///////////////////////////////////////////////////////////////////////// - auto&& simParticipant = _simTestHarness->GetParticipant(participantName); - auto&& participant = simParticipant->Participant(); - auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); - auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); - auto&& canController = participant->CreateCanController("CAN1", "CAN_1"); - - lifecycleService->SetCommunicationReadyHandler([canController] { - canController->SetBaudRate(10'000, 1'000'000, 2'000'000); - canController->Start(); - }); - - timeSyncService->SetSimulationStepHandler( - [state, canController, dataByte = static_cast(participantName.back())]( - auto /*now*/, const std::chrono::nanoseconds /*duration*/) { - std::array dataBytes{dataByte}; - - CanFrame frame{}; - frame.flags = {}; - frame.canId = 0x12; - frame.dlc = 1; - frame.dataField = SilKit::Util::MakeSpan(dataBytes); - - for (int i = 0; i < 10; ++i) - { - canController->SendFrame(frame); - } - }, - 1ms); - } - - auto ok = _simTestHarness->Run(5s); - ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; - - auto lastNow = state->lastNow.load(); - std::cout << "lastNow = " << lastNow << std::endl; - EXPECT_TRUE(state->lastNow.load() == 5ms); + std::vector canParticipantNames; + for (char participantSuffix = 'A'; participantSuffix <= 'K'; ++participantSuffix) + { + canParticipantNames.emplace_back(std::string{"CanParticipant"} + participantSuffix); + } + + { + auto participantNames = canParticipantNames; + participantNames.emplace_back("SimulationStopper"); + SetupFromParticipantList(participantNames); + } + + auto state = std::make_shared(); + + // Set up the Sending and receiving participants + { + ///////////////////////////////////////////////////////////////////////// + // SimulationStopper + ///////////////////////////////////////////////////////////////////////// + const auto participantName = "SimulationStopper"; + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + + timeSyncService->SetSimulationStepHandler( + [state, lifecycleService](auto now, const std::chrono::nanoseconds /*duration*/) { + state->lastNow = now; + + if (now == 5ms) + { + lifecycleService->Stop("stopping the simulation through another participant"); + } + }, 1ms); + } + + for (const auto& participantName : canParticipantNames) + { + ///////////////////////////////////////////////////////////////////////// + // CAN Participants + ///////////////////////////////////////////////////////////////////////// + auto&& simParticipant = _simTestHarness->GetParticipant(participantName); + auto&& participant = simParticipant->Participant(); + auto&& lifecycleService = simParticipant->GetOrCreateLifecycleService(); + auto&& timeSyncService = simParticipant->GetOrCreateTimeSyncService(); + auto&& canController = participant->CreateCanController("CAN1", "CAN_1"); + + lifecycleService->SetCommunicationReadyHandler([canController] { + canController->SetBaudRate(10'000, 1'000'000, 2'000'000); + canController->Start(); + }); + + timeSyncService->SetSimulationStepHandler( + [state, canController, dataByte = static_cast(participantName.back())]( + auto /*now*/, const std::chrono::nanoseconds /*duration*/) { + std::array dataBytes{dataByte}; + + CanFrame frame{}; + frame.flags = {}; + frame.canId = 0x12; + frame.dlc = 1; + frame.dataField = SilKit::Util::MakeSpan(dataBytes); + + for (int i = 0; i < 10; ++i) + { + canController->SendFrame(frame); + } + }, + 1ms); + } + + auto ok = _simTestHarness->Run(5s); + ASSERT_TRUE(ok) << "SimTestHarness should terminate without timeout"; + + auto lastNow = state->lastNow.load(); + std::cout << "lastNow = " << lastNow << std::endl; + EXPECT_TRUE(state->lastNow.load() == 5ms); } } //end namespace diff --git a/SilKit/IntegrationTests/ITest_RequestRemoteParticipantConnect.cpp b/SilKit/IntegrationTests/ITest_RequestRemoteParticipantConnect.cpp index c60067a4b..4aecc6da9 100644 --- a/SilKit/IntegrationTests/ITest_RequestRemoteParticipantConnect.cpp +++ b/SilKit/IntegrationTests/ITest_RequestRemoteParticipantConnect.cpp @@ -115,20 +115,18 @@ void TestDirectConnectionNotPossible(std::vector participantConfigs }); auto publisher1 = pubParticipant->Participant()->CreateDataPublisher("test", pubSubSpec); - pubParticipant->GetOrCreateTimeSyncService()->SetSimulationStepHandler( - [&](auto&&, auto&&) { - std::unique_lock lock{mx}; - if (numDataReceived >= 2) - { - pubParticipant->Stop(); - } - else - { - std::cout << "<---- published" << std::endl; - publisher1->Publish(testData); - } - }, - 1ms); + pubParticipant->GetOrCreateTimeSyncService()->SetSimulationStepHandler([&](auto&&, auto&&) { + std::unique_lock lock{mx}; + if (numDataReceived >= 2) + { + pubParticipant->Stop(); + } + else + { + std::cout << "<---- published" << std::endl; + publisher1->Publish(testData); + } + }, 1ms); ASSERT_TRUE(testSetup.Run(4s)); ASSERT_GE(numDataReceived, 2); diff --git a/SilKit/IntegrationTests/ITest_SameParticipants.cpp b/SilKit/IntegrationTests/ITest_SameParticipants.cpp index 87dda71da..35f30e092 100644 --- a/SilKit/IntegrationTests/ITest_SameParticipants.cpp +++ b/SilKit/IntegrationTests/ITest_SameParticipants.cpp @@ -43,7 +43,8 @@ TEST(ITest_SameParticipants, test_participants_with_unique_name) // start registry auto registryUri = MakeTestRegistryUri(); - auto registry = SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); + auto registry = + SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); registry->StartListening(registryUri); auto pCfg = SilKit::Config::ParticipantConfigurationFromString(""); @@ -60,7 +61,8 @@ TEST(ITest_SameParticipants, test_participants_with_same_name) // start registry auto registryUri = MakeTestRegistryUri(); - auto registry = SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); + auto registry = + SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); registry->StartListening(registryUri); auto pCfg = SilKit::Config::ParticipantConfigurationFromString(""); @@ -68,4 +70,4 @@ TEST(ITest_SameParticipants, test_participants_with_same_name) EXPECT_THROW(participant2 = SilKit::CreateParticipant(pCfg, "Participant", registryUri), SilKit::SilKitError); } -} /* anonymous namespace */ +} /* anonymous namespace */ diff --git a/SilKit/IntegrationTests/ITest_SimTask.cpp b/SilKit/IntegrationTests/ITest_SimTask.cpp index 1b8683a98..8fabbc4c0 100644 --- a/SilKit/IntegrationTests/ITest_SimTask.cpp +++ b/SilKit/IntegrationTests/ITest_SimTask.cpp @@ -49,13 +49,25 @@ class Counter _minor = 0; } - void IncrementMinor() { ++_minor; } + void IncrementMinor() + { + ++_minor; + } - auto Value() const -> uint64_t { return (static_cast(_major) << 32) | static_cast(_minor); } + auto Value() const -> uint64_t + { + return (static_cast(_major) << 32) | static_cast(_minor); + } - auto Major() const -> uint32_t { return _major; } + auto Major() const -> uint32_t + { + return _major; + } - auto Minor() const -> uint32_t { return _minor; } + auto Minor() const -> uint32_t + { + return _minor; + } void PublishValue(SilKit::Services::PubSub::IDataPublisher *publisher) const { @@ -82,9 +94,15 @@ class Counter return value; } - static auto ExtractMajor(const uint64_t value) -> uint32_t { return static_cast(value >> 32); } + static auto ExtractMajor(const uint64_t value) -> uint32_t + { + return static_cast(value >> 32); + } - static auto ExtractMinor(const uint64_t value) -> uint32_t { return static_cast(value & 0xFFFFFFFF); } + static auto ExtractMinor(const uint64_t value) -> uint32_t + { + return static_cast(value & 0xFFFFFFFF); + } }; TEST(ITest_SimTask, blocking_during_simtask_does_not_affect_processing_order) @@ -126,12 +144,9 @@ TEST(ITest_SimTask, blocking_during_simtask_does_not_affect_processing_order) SilKit::Services::Orchestration::WorkflowConfiguration workflowConfiguration{{"Pub", "Sub", "Control"}}; cSystemController->SetWorkflowConfiguration(workflowConfiguration); - cTimeSyncService->SetSimulationStepHandler( - [](std::chrono::nanoseconds, std::chrono::nanoseconds) { - - // do nothing - }, - 1ms); + cTimeSyncService->SetSimulationStepHandler([](std::chrono::nanoseconds, std::chrono::nanoseconds) { + // do nothing + }, 1ms); auto lifecycleDone = cLifecycleService->StartLifecycle(); ASSERT_EQ(lifecycleDone.wait_for(5s), std::future_status::ready); @@ -160,56 +175,51 @@ TEST(ITest_SimTask, blocking_during_simtask_does_not_affect_processing_order) pTimeSyncService->SetSimulationStepHandler( [pLifecycleService, pPublisher, &counter, &s](std::chrono::nanoseconds now, std::chrono::nanoseconds) { - if (!s.running) - { - return; - } + if (!s.running) + { + return; + } - if (now >= 100ms) - { - pLifecycleService->Stop("test reached limit"); - s.running = false; - s.cv.notify_all(); - return; - } - - counter.IncrementMajor(); + if (now >= 100ms) + { + pLifecycleService->Stop("test reached limit"); + s.running = false; + s.cv.notify_all(); + return; + } - counter.IncrementMinor(); - counter.PublishValue(pPublisher); + counter.IncrementMajor(); - { - Lock lock{s.mx}; - s.blocking = true; - } - s.cv.notify_all(); + counter.IncrementMinor(); + counter.PublishValue(pPublisher); + + { + Lock lock{s.mx}; + s.blocking = true; + } + s.cv.notify_all(); + + // do nothing - // do nothing + { + Lock lock{s.mx}; + s.cv.wait(lock, [&s] { return !s.blocking || !s.running; }); + if (!s.running) { - Lock lock{s.mx}; - s.cv.wait(lock, [&s] { - return !s.blocking || !s.running; - }); - - if (!s.running) - { - return; - } + return; } + } - counter.IncrementMinor(); - counter.PublishValue(pPublisher); - }, - 1ms); + counter.IncrementMinor(); + counter.PublishValue(pPublisher); + }, 1ms); auto completerDone = std::async(std::launch::async, [pPublisher, &counter, &s] { while (s.running) { Lock lock{s.mx}; - s.cv.wait(lock, [&s] { - return s.blocking || !s.running; - }); + s.cv.wait(lock, [&s] { return s.blocking || !s.running; }); if (!s.running) { @@ -239,20 +249,18 @@ TEST(ITest_SimTask, blocking_during_simtask_does_not_affect_processing_order) s->CreateDataSubscriber("Sub", spec, [&received](SilKit::Services::PubSub::IDataSubscriber *, const SilKit::Services::PubSub::DataMessageEvent &event) { - ASSERT_EQ(event.data.size(), 8); - const auto value = Counter::ExtractValue(event.data); - ASSERT_GT(Counter::ExtractMajor(value), uint32_t{0}) - << SilKit::Util::AsHexString(event.data).WithSeparator(":"); - ASSERT_GT(Counter::ExtractMinor(value), uint32_t{0}) - << SilKit::Util::AsHexString(event.data).WithSeparator(":"); - received.emplace_back(value); - }); - - sTimeSyncService->SetSimulationStepHandler( - [](std::chrono::nanoseconds, std::chrono::nanoseconds) { - // do nothing - }, - 1ms); + ASSERT_EQ(event.data.size(), 8); + const auto value = Counter::ExtractValue(event.data); + ASSERT_GT(Counter::ExtractMajor(value), uint32_t{0}) + << SilKit::Util::AsHexString(event.data).WithSeparator(":"); + ASSERT_GT(Counter::ExtractMinor(value), uint32_t{0}) + << SilKit::Util::AsHexString(event.data).WithSeparator(":"); + received.emplace_back(value); + }); + + sTimeSyncService->SetSimulationStepHandler([](std::chrono::nanoseconds, std::chrono::nanoseconds) { + // do nothing + }, 1ms); auto lifecycleDone = sLifecycleService->StartLifecycle(); diff --git a/SilKit/IntegrationTests/ITest_SingleParticipant.cpp b/SilKit/IntegrationTests/ITest_SingleParticipant.cpp index acf0cf3fb..3dd90417f 100644 --- a/SilKit/IntegrationTests/ITest_SingleParticipant.cpp +++ b/SilKit/IntegrationTests/ITest_SingleParticipant.cpp @@ -49,10 +49,7 @@ using testing::Return; auto AnAckWithCanIdAndUserContext(uint32_t canId, void* userContext) -> testing::Matcher { using namespace testing; - return AllOf( - Field(&CanFrameTransmitEvent::canId, canId), - Field(&CanFrameTransmitEvent::userContext, userContext) - ); + return AllOf(Field(&CanFrameTransmitEvent::canId, canId), Field(&CanFrameTransmitEvent::userContext, userContext)); } class ITest_SingleParticipant : public testing::Test @@ -78,46 +75,41 @@ class ITest_SingleParticipant : public testing::Test void SetupWriter(SilKit::Tests::SimParticipant* participant) { - auto* canController = participant->Participant()->CreateCanController("CAN1", "CAN1"); canController->AddFrameTransmitHandler( [this, participant](ICanController* /*ctrl*/, const CanFrameTransmitEvent& ack) { - callbacks.AckHandler(ack); - numAcked++; - if (numAcked >= testMessages.size()) - { - participant->Stop(); - } - }); + callbacks.AckHandler(ack); + numAcked++; + if (numAcked >= testMessages.size()) + { + participant->Stop(); + } + }); auto* lifecycleService = participant->GetOrCreateLifecycleService(); auto* timeSyncService = participant->GetOrCreateTimeSyncService(); - lifecycleService->SetCommunicationReadyHandler([canController]() { - canController->Start(); - }); + lifecycleService->SetCommunicationReadyHandler([canController]() { canController->Start(); }); + + timeSyncService->SetSimulationStepHandler([this, canController, lifecycleService](auto, auto) { + EXPECT_EQ(lifecycleService->State(), Services::Orchestration::ParticipantState::Running); + if (numSent < testMessages.size()) + { + const auto& message = testMessages.at(numSent); + + std::vector expectedData; + expectedData.resize(message.expectedData.size()); + std::copy(message.expectedData.begin(), message.expectedData.end(), expectedData.begin()); + + CanFrame msg; + msg.canId = 1; + msg.dataField = expectedData; + msg.dlc = static_cast(msg.dataField.size()); - timeSyncService->SetSimulationStepHandler( - [this, canController, lifecycleService](auto, auto) { - EXPECT_EQ(lifecycleService->State(), Services::Orchestration::ParticipantState::Running); - if (numSent < testMessages.size()) - { - const auto& message = testMessages.at(numSent); - - std::vector expectedData; - expectedData.resize(message.expectedData.size()); - std::copy(message.expectedData.begin(), message.expectedData.end(), expectedData.begin()); - - CanFrame msg; - msg.canId = 1; - msg.dataField = expectedData; - msg.dlc = static_cast(msg.dataField.size()); - - numSent++; - canController->SendFrame(std::move(msg), (void*)(static_cast(numSent))); - } - }, - 1ms); + numSent++; + canController->SendFrame(std::move(msg), (void*)(static_cast(numSent))); + } + }, 1ms); } void ExecuteTest() @@ -135,11 +127,8 @@ class ITest_SingleParticipant : public testing::Test EXPECT_CALL(callbacks, AckHandler(AnAckWithCanIdAndUserContext(1, (void*)uintptr_t(0)))).Times(0); EXPECT_CALL(callbacks, AckHandler(AnAckWithCanIdAndUserContext(1, (void*)uintptr_t(6)))).Times(0); - EXPECT_TRUE(testHarness.Run(10s)) - << "TestHarness timeout occurred!" - << " numSent=" << numSent - << " numAcked=" << numAcked - ; + EXPECT_TRUE(testHarness.Run(10s)) << "TestHarness timeout occurred!" + << " numSent=" << numSent << " numAcked=" << numAcked; EXPECT_EQ(numSent, testMessages.size()); EXPECT_EQ(numAcked, testMessages.size()); } @@ -154,8 +143,7 @@ class ITest_SingleParticipant : public testing::Test std::vector syncParticipantNames; std::vector testMessages; - unsigned numSent{0}, - numAcked{0}; + unsigned numSent{0}, numAcked{0}; Callbacks callbacks; }; diff --git a/SilKit/IntegrationTests/ITest_StateMachineVAsio.cpp b/SilKit/IntegrationTests/ITest_StateMachineVAsio.cpp index 28dd16524..e3567c2eb 100644 --- a/SilKit/IntegrationTests/ITest_StateMachineVAsio.cpp +++ b/SilKit/IntegrationTests/ITest_StateMachineVAsio.cpp @@ -58,7 +58,8 @@ class ITest_StateMachineVAsio : public testing::Test MOCK_METHOD0(CommunicationReadyHandler, void()); MOCK_METHOD0(StopHandler, void()); MOCK_METHOD0(ShutdownHandler, void()); - MOCK_METHOD1(ParticipantStateHandler, void(ParticipantState)); // Helper to only check for status.state; no longer part of the API + MOCK_METHOD1(ParticipantStateHandler, + void(ParticipantState)); // Helper to only check for status.state; no longer part of the API }; protected: @@ -69,10 +70,10 @@ class ITest_StateMachineVAsio : public testing::Test _targetState = state; _targetStatePromise = std::promise{}; auto future = _targetStatePromise.get_future(); - if (_currentState == state) + if (_currentState == state) { // If we are already in the correct state, we have to set the promise immediately. - // This happens if the ParticipantStateHandler is triggered before setting up the + // This happens if the ParticipantStateHandler is triggered before setting up the // expectation here. _targetStatePromise.set_value(); } @@ -102,7 +103,8 @@ TEST_F(ITest_StateMachineVAsio, DISABLED_vasio_state_machine) auto registryUri = MakeTestRegistryUri(); std::vector syncParticipantNames{"TestUnit"}; - auto registry = SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); + auto registry = + SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::ParticipantConfigurationFromString("")); registry->StartListening(registryUri); // Setup Participant for TestController @@ -113,9 +115,8 @@ TEST_F(ITest_StateMachineVAsio, DISABLED_vasio_state_machine) systemController->SetWorkflowConfiguration({syncParticipantNames}); auto monitor = participant->CreateSystemMonitor(); - monitor->AddParticipantStatusHandler([this](ParticipantStatus status) { - this->ParticipantStateHandler(status.state); - }); + monitor->AddParticipantStatusHandler( + [this](ParticipantStatus status) { this->ParticipantStateHandler(status.state); }); // Setup Participant for Test Unit auto participantTestUnit = @@ -124,18 +125,12 @@ TEST_F(ITest_StateMachineVAsio, DISABLED_vasio_state_machine) participantTestUnit->CreateLifecycleService({SilKit::Services::Orchestration::OperationMode::Coordinated}); auto* timeSyncService = lifecycleService->CreateTimeSyncService(); - lifecycleService->SetCommunicationReadyHandler([&callbacks = callbacks]() { - callbacks.CommunicationReadyHandler(); - }); - timeSyncService->SetSimulationStepHandler([](auto /*now*/, auto /*duration*/) { - }, 1ms); - - lifecycleService->SetStopHandler([&callbacks = callbacks]() { - callbacks.StopHandler(); - }); - lifecycleService->SetShutdownHandler([&callbacks = callbacks]() { - callbacks.ShutdownHandler(); - }); + lifecycleService->SetCommunicationReadyHandler( + [&callbacks = callbacks]() { callbacks.CommunicationReadyHandler(); }); + timeSyncService->SetSimulationStepHandler([](auto /*now*/, auto /*duration*/) {}, 1ms); + + lifecycleService->SetStopHandler([&callbacks = callbacks]() { callbacks.StopHandler(); }); + lifecycleService->SetShutdownHandler([&callbacks = callbacks]() { callbacks.ShutdownHandler(); }); std::string participantName = "TestUnit"; diff --git a/SilKit/IntegrationTests/ITest_SystemMonitor.cpp b/SilKit/IntegrationTests/ITest_SystemMonitor.cpp index 268698452..4b242f25f 100644 --- a/SilKit/IntegrationTests/ITest_SystemMonitor.cpp +++ b/SilKit/IntegrationTests/ITest_SystemMonitor.cpp @@ -46,12 +46,10 @@ class ITest_SystemMonitor : public testing::Test struct Callbacks { MOCK_METHOD(void, ParticipantConnectedHandler, - (const SilKit::Services::Orchestration::ParticipantConnectionInformation&), - (const)); + (const SilKit::Services::Orchestration::ParticipantConnectionInformation&), (const)); MOCK_METHOD(void, ParticipantDisconnectedHandler, (const SilKit::Services::Orchestration::ParticipantConnectionInformation&), (const)); - }; struct SequencePoints @@ -61,9 +59,7 @@ class ITest_SystemMonitor : public testing::Test MOCK_METHOD(void, C_AfterThirdParticipantDestroyed, ()); }; - ITest_SystemMonitor() - { - } + ITest_SystemMonitor() {} Callbacks callbacks; Callbacks secondCallbacks; @@ -90,14 +86,14 @@ TEST_F(ITest_SystemMonitor, discover_services) auto* firstSystemMonitor = firstParticipant->CreateSystemMonitor(); firstSystemMonitor->SetParticipantConnectedHandler( [this](const SilKit::Services::Orchestration::ParticipantConnectionInformation& participantInformation) { - callbacks.ParticipantConnectedHandler(participantInformation); + callbacks.ParticipantConnectedHandler(participantInformation); }); firstSystemMonitor->SetParticipantDisconnectedHandler( [this](const SilKit::Services::Orchestration::ParticipantConnectionInformation& participantInformation) { - callbacks.ParticipantDisconnectedHandler(participantInformation); + callbacks.ParticipantDisconnectedHandler(participantInformation); }); - SilKit::Services::Orchestration::ISystemMonitor * secondSystemMonitor = nullptr; + SilKit::Services::Orchestration::ISystemMonitor* secondSystemMonitor = nullptr; testing::Sequence sequence, secondSequence; @@ -108,14 +104,11 @@ TEST_F(ITest_SystemMonitor, discover_services) std::promise secondParticipantDisconnectedPromise; auto secondParticipantDisconnectedFuture = secondParticipantDisconnectedPromise.get_future(); - EXPECT_CALL(callbacks, ParticipantConnectedHandler(secondParticipantConnection)) - .Times(1); + EXPECT_CALL(callbacks, ParticipantConnectedHandler(secondParticipantConnection)).Times(1); EXPECT_CALL(sequencePoints, A_BeforeCreateThirdParticipant()).Times(1).InSequence(sequence, secondSequence); { - EXPECT_CALL(callbacks, ParticipantConnectedHandler(thirdParticipantConnection)) - .Times(1) - .InSequence(sequence); + EXPECT_CALL(callbacks, ParticipantConnectedHandler(thirdParticipantConnection)).Times(1).InSequence(sequence); EXPECT_CALL(secondCallbacks, ParticipantConnectedHandler(thirdParticipantConnection)) .Times(1) .InSequence(secondSequence); @@ -126,19 +119,18 @@ TEST_F(ITest_SystemMonitor, discover_services) .Times(1) .InSequence(sequence) .WillOnce([&] { - ASSERT_FALSE(firstSystemMonitor->IsParticipantConnected(thirdParticipantConnection.participantName)); - thirdParticipantDisconnectedPromiseA.set_value(); - }); + ASSERT_FALSE(firstSystemMonitor->IsParticipantConnected(thirdParticipantConnection.participantName)); + thirdParticipantDisconnectedPromiseA.set_value(); + }); EXPECT_CALL(secondCallbacks, ParticipantDisconnectedHandler(thirdParticipantConnection)) .Times(1) .InSequence(secondSequence) .WillOnce([&] { - ASSERT_NE(secondSystemMonitor, nullptr); - ASSERT_FALSE( - secondSystemMonitor->IsParticipantConnected(thirdParticipantConnection.participantName)); - thirdParticipantDisconnectedPromiseB.set_value(); - }); + ASSERT_NE(secondSystemMonitor, nullptr); + ASSERT_FALSE(secondSystemMonitor->IsParticipantConnected(thirdParticipantConnection.participantName)); + thirdParticipantDisconnectedPromiseB.set_value(); + }); } EXPECT_CALL(sequencePoints, C_AfterThirdParticipantDestroyed()).Times(1).InSequence(sequence, secondSequence); { @@ -146,9 +138,9 @@ TEST_F(ITest_SystemMonitor, discover_services) .Times(1) .InSequence(sequence) .WillOnce([&] { - ASSERT_FALSE(firstSystemMonitor->IsParticipantConnected(secondParticipantConnection.participantName)); - secondParticipantDisconnectedPromise.set_value(); - }); + ASSERT_FALSE(firstSystemMonitor->IsParticipantConnected(secondParticipantConnection.participantName)); + secondParticipantDisconnectedPromise.set_value(); + }); } ASSERT_FALSE(firstSystemMonitor->IsParticipantConnected(secondParticipantConnection.participantName)); @@ -161,12 +153,12 @@ TEST_F(ITest_SystemMonitor, discover_services) secondSystemMonitor->SetParticipantConnectedHandler( [this](const SilKit::Services::Orchestration::ParticipantConnectionInformation& participantConnectionInformation) { - secondCallbacks.ParticipantConnectedHandler(participantConnectionInformation); + secondCallbacks.ParticipantConnectedHandler(participantConnectionInformation); }); secondSystemMonitor->SetParticipantDisconnectedHandler( [this](const SilKit::Services::Orchestration::ParticipantConnectionInformation& participantConnectionInformation) { - secondCallbacks.ParticipantDisconnectedHandler(participantConnectionInformation); + secondCallbacks.ParticipantDisconnectedHandler(participantConnectionInformation); }); ASSERT_FALSE(firstSystemMonitor->IsParticipantConnected(thirdParticipantConnection.participantName)); @@ -175,9 +167,8 @@ TEST_F(ITest_SystemMonitor, discover_services) sequencePoints.A_BeforeCreateThirdParticipant(); // Create the third participant which should trigger the callbacks of the first and second - auto&& thirdParticipant = - SilKit::CreateParticipant(SilKit::Config::MakeEmptyParticipantConfiguration(), - thirdParticipantConnection.participantName, registryUri); + auto&& thirdParticipant = SilKit::CreateParticipant(SilKit::Config::MakeEmptyParticipantConfiguration(), + thirdParticipantConnection.participantName, registryUri); ASSERT_TRUE(firstSystemMonitor->IsParticipantConnected(thirdParticipantConnection.participantName)); ASSERT_TRUE(secondSystemMonitor->IsParticipantConnected(thirdParticipantConnection.participantName)); diff --git a/SilKit/IntegrationTests/ITest_ThreeCanController.cpp b/SilKit/IntegrationTests/ITest_ThreeCanController.cpp old mode 100755 new mode 100644 index 43bd84749..4962f31bb --- a/SilKit/IntegrationTests/ITest_ThreeCanController.cpp +++ b/SilKit/IntegrationTests/ITest_ThreeCanController.cpp @@ -62,7 +62,8 @@ bool CheckUserContextContainsFrameCounter(void* userContext, uint16_t frameCount return (reinterpret_cast(userContext) & 0xFFFF) == frameCounter; } -MATCHER_P(UserContextContainsFrameCounter, frameCounter, "") { +MATCHER_P(UserContextContainsFrameCounter, frameCounter, "") +{ if (CheckUserContextContainsFrameCounter(arg, frameCounter)) { return true; @@ -72,13 +73,12 @@ MATCHER_P(UserContextContainsFrameCounter, frameCounter, "") { return false; } -auto AnAckWithCanIdAndFrameCounter(uint32_t canId, uint16_t frameCounter) -> testing::Matcher +auto AnAckWithCanIdAndFrameCounter(uint32_t canId, + uint16_t frameCounter) -> testing::Matcher { using namespace testing; - return AllOf( - Field(&CanFrameTransmitEvent::canId, canId), - Field(&CanFrameTransmitEvent::userContext, UserContextContainsFrameCounter(frameCounter)) - ); + return AllOf(Field(&CanFrameTransmitEvent::canId, canId), + Field(&CanFrameTransmitEvent::userContext, UserContextContainsFrameCounter(frameCounter))); } class ITest_ThreeCanController : public testing::Test @@ -100,75 +100,63 @@ class ITest_ThreeCanController : public testing::Test testMessages[index].expectedData = messageBuilder.str(); } - syncParticipantNames = { "CanWriter", "CanReader1", "CanReader2" }; + syncParticipantNames = {"CanWriter", "CanReader1", "CanReader2"}; } void SetupWriter(SilKit::Tests::SimParticipant* writer) { - auto* controller = writer->Participant()->CreateCanController("CAN1", "CAN1"); controllerToId.emplace(controller, static_cast(controllerToId.size())); ASSERT_LT(controllerToId[controller], std::numeric_limits::max()); - controller->AddFrameTransmitHandler( - [this](ICanController* ctrl, const CanFrameTransmitEvent& ack) { + controller->AddFrameTransmitHandler([this](ICanController* ctrl, const CanFrameTransmitEvent& ack) { callbacks.AckHandler(ack); EXPECT_TRUE(CheckUserContextContainsControllerId(ack.userContext, controllerToId[ctrl])); }); auto* lifecycleService = writer->GetOrCreateLifecycleService(); - lifecycleService->SetCommunicationReadyHandler([controller]() { - controller->Start(); - }); + lifecycleService->SetCommunicationReadyHandler([controller]() { controller->Start(); }); auto name = writer->Name(); - lifecycleService->SetStopHandler([name]() { - std::cout << "Stop received by participant " << name << std::endl; - }); - lifecycleService->SetShutdownHandler([name]() { - std::cout << "Shutdown received by participant " << name << std::endl; - }); + lifecycleService->SetStopHandler( + [name]() { std::cout << "Stop received by participant " << name << std::endl; }); + lifecycleService->SetShutdownHandler( + [name]() { std::cout << "Shutdown received by participant " << name << std::endl; }); auto* timeSyncService = writer->GetOrCreateTimeSyncService(); - timeSyncService->SetSimulationStepHandler( - [this, controller](auto, auto) + timeSyncService->SetSimulationStepHandler([this, controller](auto, auto) { + if (numSent < testMessages.size()) { - if (numSent < testMessages.size()) - { - const auto& message = testMessages.at(numSent); + const auto& message = testMessages.at(numSent); - std::vector expectedData; - expectedData.resize(message.expectedData.size()); - std::copy(message.expectedData.begin(), message.expectedData.end(), expectedData.begin()); + std::vector expectedData; + expectedData.resize(message.expectedData.size()); + std::copy(message.expectedData.begin(), message.expectedData.end(), expectedData.begin()); - CanFrame msg; - msg.canId = 1; - msg.dataField = expectedData; - msg.dlc = static_cast(msg.dataField.size()); + CanFrame msg; + msg.canId = 1; + msg.dataField = expectedData; + msg.dlc = static_cast(msg.dataField.size()); - const auto frameCounter = numSent + 1; - ASSERT_LT(numSent + 1, std::numeric_limits::max()); + const auto frameCounter = numSent + 1; + ASSERT_LT(numSent + 1, std::numeric_limits::max()); - controller->SendFrame(msg, MakeUserContext(controllerToId[controller], static_cast(frameCounter))); - numSent++; - } + controller->SendFrame(msg, + MakeUserContext(controllerToId[controller], static_cast(frameCounter))); + numSent++; + } }, 1ms); } void SetupReader(SilKit::Tests::SimParticipant* reader) { - auto* controller = reader->Participant()->CreateCanController("CAN1", "CAN1"); controller->AddFrameTransmitHandler( - [this](ICanController* /*ctrl*/, const CanFrameTransmitEvent& ack) { - callbacks.AckHandler(ack); - }); + [this](ICanController* /*ctrl*/, const CanFrameTransmitEvent& ack) { callbacks.AckHandler(ack); }); - controller->AddFrameHandler( - [this, reader](ICanController*, const CanFrameEvent& msg) { - - if ( reader->Name() == "CanReader1") + controller->AddFrameHandler([this, reader](ICanController*, const CanFrameEvent& msg) { + if (reader->Name() == "CanReader1") { std::string message(msg.frame.dataField.begin(), msg.frame.dataField.end()); testMessages.at(numReceived++).receivedData = message; @@ -185,17 +173,13 @@ class ITest_ThreeCanController : public testing::Test auto* lifecycleService = reader->GetOrCreateLifecycleService(); - lifecycleService->SetCommunicationReadyHandler([controller]() { - controller->Start(); - }); + lifecycleService->SetCommunicationReadyHandler([controller]() { controller->Start(); }); auto name = reader->Name(); - lifecycleService->SetStopHandler([name]() { - std::cout << "Stop received by participant " << name << std::endl; - }); - lifecycleService->SetShutdownHandler([name]() { - std::cout << "Shutdown received by participant " << name << std::endl; - }); + lifecycleService->SetStopHandler( + [name]() { std::cout << "Stop received by participant " << name << std::endl; }); + lifecycleService->SetShutdownHandler( + [name]() { std::cout << "Shutdown received by participant " << name << std::endl; }); } void ExecuteTest() @@ -221,10 +205,7 @@ class ITest_ThreeCanController : public testing::Test EXPECT_TRUE(testHarness.Run(30s)) << "TestHarness timeout occurred!" - << " numSent=" << numSent - << " numReceived=" << numReceived - << " numReceived2=" << numReceived2 - ; + << " numSent=" << numSent << " numReceived=" << numReceived << " numReceived2=" << numReceived2; for (auto&& message : testMessages) { @@ -245,11 +226,9 @@ class ITest_ThreeCanController : public testing::Test std::vector testMessages; - std::unordered_map controllerToId; + std::unordered_map controllerToId; - unsigned numSent{0}, - numReceived{0}, - numReceived2{0}; + unsigned numSent{0}, numReceived{0}, numReceived2{0}; Callbacks callbacks; }; diff --git a/SilKit/IntegrationTests/ITest_ThreeEthController.cpp b/SilKit/IntegrationTests/ITest_ThreeEthController.cpp old mode 100755 new mode 100644 index 339ab3208..aa979c61b --- a/SilKit/IntegrationTests/ITest_ThreeEthController.cpp +++ b/SilKit/IntegrationTests/ITest_ThreeEthController.cpp @@ -87,7 +87,7 @@ class ITest_ThreeEthController : public testing::Test testMessages[index].expectedData = std::move(messageString); } - syncParticipantNames = { "EthWriter" ,"EthReader1" ,"EthReader2" }; + syncParticipantNames = {"EthWriter", "EthReader1", "EthReader2"}; } void SetupSender(SilKit::Tests::SimParticipant* participant) @@ -103,31 +103,30 @@ class ITest_ThreeEthController : public testing::Test }); auto* lifecycleService = participant->GetOrCreateLifecycleService(); - lifecycleService->SetCommunicationReadyHandler([controller]() { - controller->Activate(); - }); + lifecycleService->SetCommunicationReadyHandler([controller]() { controller->Activate(); }); auto* timeSyncService = participant->GetOrCreateTimeSyncService(); timeSyncService->SetSimulationStepHandler( [this, participant, controller](std::chrono::nanoseconds now, std::chrono::nanoseconds) { - if (numSent < testMessages.size()) - { - const auto& message = testMessages.at(numSent); + if (numSent < testMessages.size()) + { + const auto& message = testMessages.at(numSent); - std::cout << participant->Name() << " -> sent frame @" << now.count() << "ns" << std::endl; + std::cout << participant->Name() << " -> sent frame @" << now.count() << "ns" << std::endl; - EthernetMac destinationMac{ 0x12, 0x23, 0x45, 0x67, 0x89, 0x9a }; - EthernetMac sourceMac{ 0x9a, 0x89, 0x67, 0x45, 0x23, 0x12 }; - EthernetEtherType etherType{ 0x0800 }; - EthernetVlanTagControlIdentifier tci{ 0x0000 }; + EthernetMac destinationMac{0x12, 0x23, 0x45, 0x67, 0x89, 0x9a}; + EthernetMac sourceMac{0x9a, 0x89, 0x67, 0x45, 0x23, 0x12}; + EthernetEtherType etherType{0x0800}; + EthernetVlanTagControlIdentifier tci{0x0000}; - auto ethernetFrameData = CreateEthernetFrameWithVlanTagFromString(destinationMac, sourceMac, etherType, message.expectedData, tci); - auto ethernetFrame = SilKit::Services::Ethernet::EthernetFrame{ethernetFrameData}; + auto ethernetFrameData = CreateEthernetFrameWithVlanTagFromString(destinationMac, sourceMac, etherType, + message.expectedData, tci); + auto ethernetFrame = SilKit::Services::Ethernet::EthernetFrame{ethernetFrameData}; - EXPECT_GE(ethernetFrame.raw.size(), MINIMUM_ETHERNET_FRAME_LENGTH); - controller->SendFrame(ethernetFrame, reinterpret_cast(static_cast(numSent + 1))); - numSent++; - } + EXPECT_GE(ethernetFrame.raw.size(), MINIMUM_ETHERNET_FRAME_LENGTH); + controller->SendFrame(ethernetFrame, reinterpret_cast(static_cast(numSent + 1))); + numSent++; + } }, 1ms); } @@ -137,34 +136,26 @@ class ITest_ThreeEthController : public testing::Test auto* controller = participant->Participant()->CreateEthernetController("ETH1", "LINK1"); controller->AddFrameTransmitHandler( - [this](IEthernetController* , const EthernetFrameTransmitEvent& ack) { - callbacks.AckHandler(ack); + [this](IEthernetController*, const EthernetFrameTransmitEvent& ack) { callbacks.AckHandler(ack); }); + + controller->AddFrameHandler([this, participant](IEthernetController*, const EthernetFrameEvent& event) { + const auto& frame = event.frame; + std::string message(frame.raw.begin() + EthernetFrameHeaderSize + EthernetFrameVlanTagSize, + frame.raw.end()); + std::cout << participant->Name() << " <- received frame" + << ": frame size=" << frame.raw.size() << ": testMessages size=" << testMessages.size() + << ": receiveCount=" << numReceived << ": message='" << message << "'" << std::endl; + testMessages[numReceived].receivedData = message; + numReceived++; + if (numReceived >= testMessages.size()) + { + participant->Stop(); + } }); - controller->AddFrameHandler( - [this, participant](IEthernetController*, const EthernetFrameEvent& event) { - const auto& frame = event.frame; - std::string message(frame.raw.begin() + EthernetFrameHeaderSize + EthernetFrameVlanTagSize, frame.raw.end()); - std::cout << participant->Name() - <<" <- received frame" - << ": frame size=" << frame.raw.size() - << ": testMessages size=" << testMessages.size() - << ": receiveCount=" << numReceived - << ": message='" << message << "'" - << std::endl; - testMessages[numReceived].receivedData = message; - numReceived++; - if (numReceived >= testMessages.size()) - { - participant->Stop(); - } - }); - auto* lifecycleService = participant->GetOrCreateLifecycleService(); - lifecycleService->SetCommunicationReadyHandler([controller]() { - controller->Activate(); - }); + lifecycleService->SetCommunicationReadyHandler([controller]() { controller->Activate(); }); } void ExecuteTest() @@ -172,7 +163,7 @@ class ITest_ThreeEthController : public testing::Test SilKit::Tests::SimTestHarness testHarness(syncParticipantNames, registryUri); //participant setup - auto* ethWriter = testHarness.GetParticipant("EthWriter"); + auto* ethWriter = testHarness.GetParticipant("EthWriter"); auto* ethReader1 = testHarness.GetParticipant("EthReader1"); auto* ethReader2 = testHarness.GetParticipant("EthReader2"); @@ -181,25 +172,19 @@ class ITest_ThreeEthController : public testing::Test // reader 2 simply counts the number of messages auto* controller = ethReader2->Participant()->CreateEthernetController("ETH1", "LINK1"); - controller->AddFrameHandler( - [this](auto, auto) { - numReceived2++; - } - ); - + controller->AddFrameHandler([this](auto, auto) { numReceived2++; }); + // run the simulation and check invariants for (auto index = 1u; index <= testMessages.size(); index++) { - EXPECT_CALL(callbacks, AckHandler(MatchUserContext(reinterpret_cast(static_cast(index))))); + EXPECT_CALL(callbacks, + AckHandler(MatchUserContext(reinterpret_cast(static_cast(index))))); } EXPECT_CALL(callbacks, AckHandler(MatchUserContext(nullptr))).Times(0); - EXPECT_TRUE(testHarness.Run(30s)) - << "TestHarness Timeout occurred!" - << " numSent=" << numSent - << " numAcked=" << numAcked - << " numReceived=" << numReceived - << " numReceived2=" << numReceived2; + EXPECT_TRUE(testHarness.Run(30s)) << "TestHarness Timeout occurred!" + << " numSent=" << numSent << " numAcked=" << numAcked + << " numReceived=" << numReceived << " numReceived2=" << numReceived2; EXPECT_EQ(numAcked, numSent); EXPECT_EQ(numSent, numReceived); @@ -220,10 +205,7 @@ class ITest_ThreeEthController : public testing::Test std::string receivedData; }; std::vector testMessages; - unsigned numSent{0}, - numReceived{0}, - numReceived2{0}, - numAcked{0}; + unsigned numSent{0}, numReceived{0}, numReceived2{0}, numAcked{0}; Callbacks callbacks; }; diff --git a/SilKit/IntegrationTests/IntegrationTestInfrastructure.hpp b/SilKit/IntegrationTests/IntegrationTestInfrastructure.hpp index 0e703c54f..deb8f531c 100644 --- a/SilKit/IntegrationTests/IntegrationTestInfrastructure.hpp +++ b/SilKit/IntegrationTests/IntegrationTestInfrastructure.hpp @@ -35,7 +35,6 @@ using namespace SilKit::Config; class TestInfrastructure { - public: TestInfrastructure() {} @@ -46,8 +45,9 @@ class TestInfrastructure _systemMaster.systemController->AbortSimulation(); FAIL() << ss.str(); } - - void SetupRegistryAndSystemMaster(const std::string& registryUri, bool sync, std::vector requiredParticipantNames) + + void SetupRegistryAndSystemMaster(const std::string& registryUri, bool sync, + std::vector requiredParticipantNames) { try { @@ -77,7 +77,6 @@ class TestInfrastructure } private: - void RunRegistry(const std::string& registryUri) { _registry = SilKit::Vendor::Vector::CreateSilKitRegistry(SilKit::Config::MakeEmptyParticipantConfiguration()); @@ -96,11 +95,9 @@ class TestInfrastructure _systemMaster.lifecycleService = _systemMaster.participant->CreateLifecycleService({OperationMode::Coordinated}); - ITimeSyncService * timeSyncService = _systemMaster.lifecycleService->CreateTimeSyncService(); + ITimeSyncService* timeSyncService = _systemMaster.lifecycleService->CreateTimeSyncService(); timeSyncService->SetSimulationStepHandler( - [](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) { - }, - std::chrono::seconds{1}); + [](std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/) {}, std::chrono::seconds{1}); requiredParticipantNames.push_back(systemMasterName); _systemMaster.systemController->SetWorkflowConfiguration({requiredParticipantNames}); @@ -116,15 +113,19 @@ class TestInfrastructure case SystemState::Running: _systemMaster.systemStateRunningPromise.set_value(); break; - default: break; + default: + break; } }); _systemMaster.systemMonitor->AddParticipantStatusHandler([this](const ParticipantStatus& newStatus) { switch (newStatus.state) { - case ParticipantState::Error: _systemMaster.systemController->AbortSimulation(); break; - default: break; + case ParticipantState::Error: + _systemMaster.systemController->AbortSimulation(); + break; + default: + break; } }); @@ -146,5 +147,4 @@ class TestInfrastructure }; SystemMaster _systemMaster; - }; diff --git a/SilKit/IntegrationTests/IntegrationTestUtils.hpp b/SilKit/IntegrationTests/IntegrationTestUtils.hpp old mode 100755 new mode 100644 index 02bb1947e..4f2f7d26d --- a/SilKit/IntegrationTests/IntegrationTestUtils.hpp +++ b/SilKit/IntegrationTests/IntegrationTestUtils.hpp @@ -38,7 +38,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if _WIN32 #include //for 'HANDLE' -#endif//__WIN32 +#endif //__WIN32 #include "silkit/participant/exception.hpp" @@ -51,23 +51,21 @@ struct Barrier std::atomic_uint expected{0}; std::atomic_uint have{0}; std::chrono::seconds timeout{1}; - + Barrier(const Barrier&) = delete; Barrier() = delete; Barrier(unsigned expectedEntries, std::chrono::seconds timeout) : expected{expectedEntries} , timeout{timeout} - {} + { + } ~Barrier() { - if(have < expected) + if (have < expected) { - std::cout << "Barrier: error in destructor: have=" - << have - << " expected=" << expected - << std::endl; + std::cout << "Barrier: error in destructor: have=" << have << " expected=" << expected << std::endl; //wakeup dormant threads have.store(expected); cv.notify_all(); @@ -85,12 +83,11 @@ struct Barrier } else { - auto ok = cv.wait_for(lock, timeout, [this] {return have == expected; }); + auto ok = cv.wait_for(lock, timeout, [this] { return have == expected; }); if (!ok) { std::stringstream ss; - ss << "Barrier Enter: timeout! have=" - << have << " expected=" << expected; + ss << "Barrier Enter: timeout! have=" << have << " expected=" << expected; std::cout << ss.str() << std::endl; throw SilKit::SilKitError(ss.str()); //abort test! @@ -110,13 +107,7 @@ struct Pipe { auto path = R"(\\.\pipe\)" + pipeName; - handle = CreateFileA(path.c_str(), - GENERIC_READ, - 0, - nullptr, - OPEN_EXISTING, - 0, - nullptr); + handle = CreateFileA(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr); if (handle == INVALID_HANDLE_VALUE) { throw SilKit::SilKitError("Cannot open WIN32 pipe " + path); @@ -137,7 +128,7 @@ struct Pipe DWORD actualRead = 0; buffer_t buf{}; buf.resize(size); - auto ok = ReadFile(handle, buf.data(), buf.size(), &actualRead, nullptr); + auto ok = ReadFile(handle, buf.data(), static_cast(buf.size()), &actualRead, nullptr); if (!ok) { @@ -171,8 +162,7 @@ struct Pipe auto ok = fclose(file); if (ok != 0) { - std::cout << "Fclose on linux pipe failed: " << strerror(errno) - << std::endl; + std::cout << "Fclose on linux pipe failed: " << strerror(errno) << std::endl; } file = nullptr; } @@ -236,12 +226,11 @@ void removeTempFile(const std::string& fileName) std::string randomString(size_t len) { static const std::string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789" - "_-" - ; + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "_-"; static std::default_random_engine re{std::random_device{}()}; - static std::uniform_int_distribution randPick(0, chars.size()-1); + static std::uniform_int_distribution randPick(0, chars.size() - 1); std::string rv; rv.resize(len); @@ -250,5 +239,4 @@ std::string randomString(size_t len) } - } // end namespace IntegrationTestUtils diff --git a/SilKit/IntegrationTests/SimTestHarness/SimSystemController.hpp b/SilKit/IntegrationTests/SimTestHarness/SimSystemController.hpp index c656a4325..3fcf41d46 100644 --- a/SilKit/IntegrationTests/SimTestHarness/SimSystemController.hpp +++ b/SilKit/IntegrationTests/SimTestHarness/SimSystemController.hpp @@ -56,7 +56,8 @@ class SimSystemController SilKit::Experimental::Services::Orchestration::ISystemController* _controller; SilKit::Services::Orchestration::ISystemMonitor* _monitor; std::vector _syncParticipantNames; - std::map _participantStates; //for printing status updates + std::map + _participantStates; //for printing status updates std::atomic _isShuttingDown{false}; std::unique_ptr _participant; }; diff --git a/SilKit/IntegrationTests/SimTestHarness/SimTestHarness.cpp b/SilKit/IntegrationTests/SimTestHarness/SimTestHarness.cpp old mode 100755 new mode 100644 index 9936bac2a..425c8f398 --- a/SilKit/IntegrationTests/SimTestHarness/SimTestHarness.cpp +++ b/SilKit/IntegrationTests/SimTestHarness/SimTestHarness.cpp @@ -67,6 +67,11 @@ void SimParticipant::Stop() GetOrCreateLifecycleService()->Stop("Stop"); } +void SimParticipant::Disconnect() +{ + _participant.reset(); +} + auto SimParticipant::GetOrCreateSystemMonitor() -> Services::Orchestration::ISystemMonitor* { if (!_systemMonitor) @@ -85,9 +90,8 @@ auto SimParticipant::GetOrCreateSystemController() -> Experimental::Services::Or return _systemController; } -auto SimParticipant::GetOrCreateLifecycleService( - SilKit::Services::Orchestration::LifecycleConfiguration startConfiguration) - -> Services::Orchestration::ILifecycleService* +auto SimParticipant::GetOrCreateLifecycleService(SilKit::Services::Orchestration::LifecycleConfiguration + startConfiguration) -> Services::Orchestration::ILifecycleService* { if (!_lifecycleService) { @@ -105,7 +109,16 @@ auto SimParticipant::GetOrCreateTimeSyncService() -> Services::Orchestration::IT return _timeSyncService; } -auto SimParticipant::GetOrGetLogger() -> Services::Logging::ILogger* +auto SimParticipant::GetOrCreateNetworkSimulator() -> Experimental::NetworkSimulation::INetworkSimulator* +{ + if (!_networkSimulator) + { + _networkSimulator = SilKit::Experimental::Participant::CreateNetworkSimulator(_participant.get()); + } + return _networkSimulator; +} + +auto SimParticipant::GetLogger() -> Services::Logging::ILogger* { if (!_logger) { @@ -177,6 +190,11 @@ void SimTestHarness::CreateSystemController() } bool SimTestHarness::Run(std::chrono::nanoseconds testRunTimeout) +{ + return Run(testRunTimeout, {}); +} + +bool SimTestHarness::Run(std::chrono::nanoseconds testRunTimeout, const std::vector& keepAlive) { auto lock = Lock(); std::promise simulationFinishedPromise; @@ -210,6 +228,12 @@ bool SimTestHarness::Run(std::chrono::nanoseconds testRunTimeout) //C++17: for (auto& [name, participant] : _simParticipants) for (auto& kv : _simParticipants) { + if (std::find(keepAlive.begin(), keepAlive.end(), kv.first) != keepAlive.end()) + { + // Ignore waiting for participants in keepAlive list + continue; + } + auto& participant = kv.second; if (noTimeout) { @@ -296,14 +320,10 @@ void SimTestHarness::AddParticipant(const std::string& participantName, const st if (startConfiguration.operationMode == SilKit::Services::Orchestration::OperationMode::Coordinated) { auto* timeSyncService = participant->GetOrCreateTimeSyncService(); - timeSyncService->SetSimulationStepHandler( - [](auto, auto) { - }, - 1ms); + timeSyncService->SetSimulationStepHandler([](auto, auto) {}, 1ms); } - lifecycleService->SetCommunicationReadyHandler([]() { - }); + lifecycleService->SetCommunicationReadyHandler([]() {}); _simParticipants[participantName] = std::move(participant); } diff --git a/SilKit/IntegrationTests/SimTestHarness/SimTestHarness.hpp b/SilKit/IntegrationTests/SimTestHarness/SimTestHarness.hpp old mode 100755 new mode 100644 index 52a0a227e..828d0f3c1 --- a/SilKit/IntegrationTests/SimTestHarness/SimTestHarness.hpp +++ b/SilKit/IntegrationTests/SimTestHarness/SimTestHarness.hpp @@ -37,7 +37,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "silkit/experimental/services/orchestration/ISystemController.hpp" -namespace SilKit { namespace Tests { +namespace SilKit { +namespace Tests { //forward class SimSystemController; @@ -57,6 +58,7 @@ class SimParticipant auto Participant() const -> SilKit::IParticipant*; auto Result() -> FutureResult&; void Stop(); + void Disconnect(); // Helpers to circumvent one-time-only orchestration service creation auto GetOrCreateSystemMonitor() -> Services::Orchestration::ISystemMonitor*; @@ -65,7 +67,8 @@ class SimParticipant {SilKit::Services::Orchestration::OperationMode::Coordinated}) -> Services::Orchestration::ILifecycleService*; auto GetOrCreateTimeSyncService() -> Services::Orchestration::ITimeSyncService*; - auto GetOrGetLogger() -> Services::Logging::ILogger*; + auto GetOrCreateNetworkSimulator() -> Experimental::NetworkSimulation::INetworkSimulator*; + auto GetLogger() -> Services::Logging::ILogger*; private: std::string _name; @@ -76,6 +79,7 @@ class SimParticipant Experimental::Services::Orchestration::ISystemController* _systemController{nullptr}; Services::Orchestration::ILifecycleService* _lifecycleService{nullptr}; Services::Orchestration::ITimeSyncService* _timeSyncService{nullptr}; + Experimental::NetworkSimulation::INetworkSimulator* _networkSimulator{nullptr}; Services::Logging::ILogger* _logger{nullptr}; friend class SimTestHarness; @@ -94,7 +98,8 @@ struct SimTestHarnessArgs /// in the SimTestHarness constructor. bool deferSystemControllerCreation{false}; - struct { + struct + { std::string participantConfiguration{""}; std::string listenUri{"silkit://127.0.0.1:0"}; } registry; @@ -110,14 +115,18 @@ class SimTestHarness /// \deprecated Please use the single-argument constructor which takes a SimTestHarnessArgs object. Since the struct /// fields are named when assigned, the resulting code should be much more readable. SimTestHarness(const std::vector& syncParticipantNames, const std::string& registryUri, - bool deferParticipantCreation = false, bool deferSystemControllerCreation = false, - const std::vector& asyncParticipantNames = std::vector()); + bool deferParticipantCreation = false, bool deferSystemControllerCreation = false, + const std::vector& asyncParticipantNames = std::vector()); ~SimTestHarness(); void CreateSystemController(); //! \brief Run the simulation, return false if timeout is reached. bool Run(std::chrono::nanoseconds testRunTimeout = std::chrono::nanoseconds::min()); + //! \brief Run the simulation for at most \p testRunTimeout and wait for all participants to shutdown, except the participants mentioned in \p keepAlive. + //! \return false if timeout is reached + bool Run(std::chrono::nanoseconds testRunTimeout, const std::vector& keepAlive); + //! \brief Get the SimParticipant by name SimParticipant* GetParticipant(const std::string& participantName); //! \brief Get the SimParticipant by name. If it does not exist yet, create a SimParticipant with the specified name and provide its ParticipantConfiguration as a string. @@ -130,7 +139,8 @@ class SimTestHarness private: void AddParticipant(const std::string& participantName, const std::string& participantConfiguration, - SilKit::Services::Orchestration::LifecycleConfiguration startConfiguration = {SilKit::Services::Orchestration::OperationMode::Coordinated}); + SilKit::Services::Orchestration::LifecycleConfiguration startConfiguration = { + SilKit::Services::Orchestration::OperationMode::Coordinated}); bool IsSync(const std::string& participantName); bool IsAsync(const std::string& participantName); @@ -150,6 +160,5 @@ class SimTestHarness }; - -} //end ns silkit -} //end ns test +} // namespace Tests +} // namespace SilKit diff --git a/SilKit/ci/Jenkinsfile b/SilKit/ci/Jenkinsfile index a421b8678..21d9d561e 100755 --- a/SilKit/ci/Jenkinsfile +++ b/SilKit/ci/Jenkinsfile @@ -19,7 +19,7 @@ buildWarningsAsErrors=true // compiler warnings are treated as errors artifactoryServer = Artifactory.server('IntegrationBusArtifactory') artifactoryBuildInfo = Artifactory.newBuildInfo() -def gitBranch="main" // overriden in parallel pipeline based on scm vars +def gitBranch="main-mirror" // overriden in parallel pipeline based on scm vars def buildConfigs = [ // Windows builds: @@ -135,7 +135,7 @@ def buildConfigs = [ @NonCPS def isFullBuildRequired(branchName) { // Master and Pull Requests are always full builds - if(branchName == 'main' || branchName.startsWith("PR-")) { + if(branchName == 'main-mirror' || branchName.startsWith("PR-")) { return true; } // A user requests a fullbuild by adding a "/full" suffix @@ -156,7 +156,7 @@ def isClangBuild(label) { } def setBuildRetention(bi) { - if(gitBranch == 'main' || gitBranch == 'origin/main') { + if(gitBranch == 'main-mirror' || gitBranch == 'origin/main-mirror') { bi.retention(maxBuilds: 40, deleteBuildArtifacts: true, async: true) } else { bi.retention(maxBuilds: 2, maxDays: 50, deleteBuildArtifacts: true, async: true) @@ -355,7 +355,7 @@ def doBuild(Map config) { scmVars = checkoutGit() // For reproducible build set SOURCE_DATE_EPOCH to time of last commit - def commitTime = runWithOutput("git log --max-count=1 --format=%ct -r origin/main") + def commitTime = runWithOutput("git log --max-count=1 --format=%ct -r origin/main-mirror") buildEnv.add("SOURCE_DATE_EPOCH=${commitTime}") buildEnv.add("TZ=UTC") buildEnv.add("LC_ALL=C.UTF-8") diff --git a/SilKit/ci/check_files_changed.py b/SilKit/ci/check_files_changed.py new file mode 100644 index 000000000..624334386 --- /dev/null +++ b/SilKit/ci/check_files_changed.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +# +# SPDX-License-Identifier: MIT + +import requests +import argparse +import os + +isCI = os.getenv('CI') +INFO_PREFIX = "::notice ::" if isCI != None else "INFO: " +WARN_PREFIX = "::warning ::" if isCI != None else "WARNING: " +ERROR_PREFIX = "::error ::" if isCI != None else "ERROR: " + +## Convenience +def log(fmt, *args): + print(fmt.format(*args)) + +def info(fmt, *args): + log(INFO_PREFIX + fmt, *args) + +def warn(fmt, *args): + log(WARN_PREFIX + fmt, *args) + +def die(status, fmt, *args): + log(ERROR_PREFIX + fmt, *args) + sys.exit(status) + +# File Set +exceptional_files = {'README.rst', 'CHANGELOG.rst', 'LICENSE', 'CONTRIBUTING.md'} + +parser = argparse.ArgumentParser(prog="JobStatusChecker", + description="Check Job Status of a specific github workflow run") +parser.add_argument('repo', type=str) +parser.add_argument('PR', type=str) +args = parser.parse_args() + +run_builds = "false" + +url = 'https://api.github.com/repos/' + args.repo + '/pulls/' + args.PR + '/files' + +log("Checking at {}".format(url)) + +r = requests.get(url, verify=False) + +for fileObject in r.json(): + + file_path = fileObject["filename"]; + file = file_path.split(sep="/")[-1] + + if file not in exceptional_files: + run_builds = "true" + break + +log("Builds should run: {}".format(run_builds)) + +if isCI != None: + log("Setting GITHUB_OUTPUT!") + with open(os.environ["GITHUB_OUTPUT"], 'a') as f: + print("run_builds={}".format(run_builds), file=f) diff --git a/SilKit/cmake/SilKitBuildTools.cmake b/SilKit/cmake/SilKitBuildTools.cmake index 5fb452abe..8b3ad0343 100644 --- a/SilKit/cmake/SilKitBuildTools.cmake +++ b/SilKit/cmake/SilKitBuildTools.cmake @@ -20,6 +20,7 @@ endmacro() macro(silkit_package_debugsymbols targetName) if(MSVC) + message(STATUS "Creating symbol package ${SILKIT_SYMBOLS_DIR_NAME}") add_custom_command( TARGET "${targetName}" POST_BUILD @@ -37,6 +38,7 @@ macro(silkit_package_debugsymbols targetName) file(MAKE_DIRECTORY "${SILKIT_SYMBOLS_DIR}") + message(STATUS "Creating symbol package ${SILKIT_SYMBOLS_DIR_NAME}") add_custom_command( TARGET "${targetName}" POST_BUILD diff --git a/SilKit/cmake/SilKitTest.cmake b/SilKit/cmake/SilKitTest.cmake index e8663fa61..520cb6f78 100644 --- a/SilKit/cmake/SilKitTest.cmake +++ b/SilKit/cmake/SilKitTest.cmake @@ -64,12 +64,6 @@ function(add_silkit_test_executable SILKIT_TEST_EXECUTABLE_NAME) if (MSVC) target_compile_options("${SILKIT_TEST_EXECUTABLE_NAME}" PRIVATE "/bigobj") endif(MSVC) - - #ensure test execution has the MinGW libraries in PATH - if(MINGW) - get_filename_component(compilerDir ${CMAKE_CXX_COMPILER} DIRECTORY) - set_tests_properties(${SILKIT_TEST_EXECUTABLE_NAME} PROPERTIES ENVIRONMENT "PATH=${compilerDir};") - endif() endfunction() function(add_silkit_test_to_executable SILKIT_TEST_EXECUTABLE_NAME) diff --git a/SilKit/cmake/SilKitVersion.cmake b/SilKit/cmake/SilKitVersion.cmake index fab1d393a..f1880fd1f 100644 --- a/SilKit/cmake/SilKitVersion.cmake +++ b/SilKit/cmake/SilKitVersion.cmake @@ -27,7 +27,7 @@ macro(configure_silkit_version project_name) set(SILKIT_VERSION_MAJOR 4) set(SILKIT_VERSION_MINOR 0) - set(SILKIT_VERSION_PATCH 45) + set(SILKIT_VERSION_PATCH 50) set(SILKIT_BUILD_NUMBER 0 CACHE STRING "The build number") set(SILKIT_VERSION_SUFFIX "") diff --git a/SilKit/include/silkit/SilKit.hpp b/SilKit/include/silkit/SilKit.hpp index 68866679a..01ac03bf1 100644 --- a/SilKit/include/silkit/SilKit.hpp +++ b/SilKit/include/silkit/SilKit.hpp @@ -44,8 +44,8 @@ DETAIL_SILKIT_DETAIL_VN_NAMESPACE_BEGIN * \throw SilKit::SilKitError The participant could not be created. */ DETAIL_SILKIT_CPP_API auto CreateParticipant( - std::shared_ptr participantConfig, const std::string& participantName) - -> std::unique_ptr; + std::shared_ptr participantConfig, + const std::string& participantName) -> std::unique_ptr; /*! \brief Create a participant and join the simulation. * diff --git a/SilKit/include/silkit/capi/Can.h b/SilKit/include/silkit/capi/Can.h old mode 100755 new mode 100644 index 7149c5cd1..864adde62 --- a/SilKit/include/silkit/capi/Can.h +++ b/SilKit/include/silkit/capi/Can.h @@ -73,17 +73,17 @@ typedef int32_t SilKit_CanTransmitStatus; /*! The message was successfully transmitted on the CAN bus. */ -#define SilKit_CanTransmitStatus_Transmitted ((SilKit_CanTransmitStatus) BIT(0)) +#define SilKit_CanTransmitStatus_Transmitted ((SilKit_CanTransmitStatus)BIT(0)) /*! (currently not in use) * * The transmit queue was reset. */ -#define SilKit_CanTransmitStatus_Canceled ((SilKit_CanTransmitStatus) BIT(1)) +#define SilKit_CanTransmitStatus_Canceled ((SilKit_CanTransmitStatus)BIT(1)) /*! The transmit request was rejected, because the transmit queue is full. */ -#define SilKit_CanTransmitStatus_TransmitQueueFull ((SilKit_CanTransmitStatus) BIT(2)) +#define SilKit_CanTransmitStatus_TransmitQueueFull ((SilKit_CanTransmitStatus)BIT(2)) /* (SilKit_CanTransmitStatus) BIT(3) is RESERVED (used to be SilKit_CanTransmitStatus_DuplicatedTransmitId) */ @@ -117,16 +117,16 @@ typedef struct SilKit_CanFrameTransmitEvent SilKit_CanFrameTransmitEvent; typedef int32_t SilKit_CanControllerState; /*! CAN controller is not initialized (initial state after reset). */ -#define SilKit_CanControllerState_Uninit ((SilKit_CanControllerState) 0) +#define SilKit_CanControllerState_Uninit ((SilKit_CanControllerState)0) /*! CAN controller is initialized but does not participate on the CAN bus. */ -#define SilKit_CanControllerState_Stopped ((SilKit_CanControllerState) 1) +#define SilKit_CanControllerState_Stopped ((SilKit_CanControllerState)1) /*! CAN controller is in normal operation mode. */ -#define SilKit_CanControllerState_Started ((SilKit_CanControllerState) 2) +#define SilKit_CanControllerState_Started ((SilKit_CanControllerState)2) /*! CAN controller is in sleep mode which is similar to the Stopped state. */ -#define SilKit_CanControllerState_Sleep ((SilKit_CanControllerState) 3) +#define SilKit_CanControllerState_Sleep ((SilKit_CanControllerState)3) /*! \brief An incoming state change of a CAN controller */ @@ -145,18 +145,18 @@ typedef int32_t SilKit_CanErrorState; * * *AUTOSAR Doc:* Successful transmission. */ -#define SilKit_CanErrorState_NotAvailable ((SilKit_CanControllerState) 0) +#define SilKit_CanErrorState_NotAvailable ((SilKit_CanControllerState)0) /*! Error Active Mode, the CAN controller is allowed to send messages and active error flags. */ -#define SilKit_CanErrorState_ErrorActive ((SilKit_CanControllerState) 1) +#define SilKit_CanErrorState_ErrorActive ((SilKit_CanControllerState)1) /*! Error Passive Mode, the CAN controller is still allowed to send messages, but must not send active error flags. */ -#define SilKit_CanErrorState_ErrorPassive ((SilKit_CanControllerState) 2) +#define SilKit_CanErrorState_ErrorPassive ((SilKit_CanControllerState)2) /*! (currently not in use) * * *AUTOSAR Doc:* Bus Off Mode, the CAN controller does not take part in communication. */ -#define SilKit_CanErrorState_BusOff ((SilKit_CanControllerState) 3) +#define SilKit_CanErrorState_BusOff ((SilKit_CanControllerState)3) /*! \brief An incoming state change of a CAN controller */ @@ -175,32 +175,32 @@ typedef struct SilKit_CanController SilKit_CanController; * \param controller The CAN controller that received the acknowledge. * \param frameTransmitEvent The incoming CAN frame transmit event. */ -typedef void (SilKitFPTR *SilKit_CanFrameTransmitHandler_t)(void* context, SilKit_CanController* controller, - SilKit_CanFrameTransmitEvent* frameTransmitEvent); +typedef void(SilKitFPTR* SilKit_CanFrameTransmitHandler_t)(void* context, SilKit_CanController* controller, + SilKit_CanFrameTransmitEvent* frameTransmitEvent); /*! Callback type to indicate that a CanMessage has been received. * \param context The by the user provided context on registration. * \param controller The CAN controller that received the message. * \param frameEvent The incoming CAN frame event containing timestamp, transmit ID and referencing the CAN frame itself. */ -typedef void (SilKitFPTR *SilKit_CanFrameHandler_t)(void* context, SilKit_CanController* controller, - SilKit_CanFrameEvent* frameEvent); +typedef void(SilKitFPTR* SilKit_CanFrameHandler_t)(void* context, SilKit_CanController* controller, + SilKit_CanFrameEvent* frameEvent); /*! Callback type to indicate that the State of the CAN Controller has changed. * \param context The by the user provided context on registration. * \param controller The CAN controller that changed its state. * \param stateChangeEvent The state change event containing timestamp and new state. */ -typedef void (SilKitFPTR *SilKit_CanStateChangeHandler_t)(void* context, SilKit_CanController* controller, - SilKit_CanStateChangeEvent* stateChangeEvent); +typedef void(SilKitFPTR* SilKit_CanStateChangeHandler_t)(void* context, SilKit_CanController* controller, + SilKit_CanStateChangeEvent* stateChangeEvent); /*! Callback type to indicate that the controller CAN error state has changed. * \param context The by the user provided context on registration. * \param controller The CAN controller that received the message. * \param errorStateChangeEvent The error state change event containing timestamp and new error state. */ -typedef void (SilKitFPTR *SilKit_CanErrorStateChangeHandler_t)(void* context, SilKit_CanController* controller, - SilKit_CanErrorStateChangeEvent* errorStateChangeEvent); +typedef void(SilKitFPTR* SilKit_CanErrorStateChangeHandler_t)(void* context, SilKit_CanController* controller, + SilKit_CanErrorStateChangeEvent* errorStateChangeEvent); /*! \brief Create a CAN controller at this SIL Kit simulation participant. * \param outCanController Pointer that refers to the resulting CAN controller (out parameter). @@ -214,12 +214,12 @@ typedef void (SilKitFPTR *SilKit_CanErrorStateChangeHandler_t)(void* context, Si * The object returned must not be deallocated using free()! */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_Create(SilKit_CanController** outCanController, - SilKit_Participant* participant, const char* name, - const char* network); + SilKit_Participant* participant, const char* name, + const char* network); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_Create_t)(SilKit_CanController** outCanController, - SilKit_Participant* participant, const char* name, - const char* network); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_Create_t)(SilKit_CanController** outCanController, + SilKit_Participant* participant, const char* name, + const char* network); /*! \brief Start the CAN controller * @@ -227,7 +227,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_Create_t)(SilKit_Can */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_Start(SilKit_CanController* controller); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_Start_t)(SilKit_CanController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_Start_t)(SilKit_CanController* controller); /*! \brief Stop the CAN controller * @@ -235,7 +235,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_Start_t)(SilKit_CanC */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_Stop(SilKit_CanController* controller); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_Stop_t)(SilKit_CanController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_Stop_t)(SilKit_CanController* controller); /*! \brief Reset the CAN controller * @@ -248,7 +248,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_Stop_t)(SilKit_CanCo */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_Reset(SilKit_CanController* controller); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_Reset_t)(SilKit_CanController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_Reset_t)(SilKit_CanController* controller); /*! \brief Put the CAN controller in sleep mode * @@ -256,7 +256,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_Reset_t)(SilKit_CanC */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_Sleep(SilKit_CanController* controller); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_CanController_Sleep_t)(SilKit_CanController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_Sleep_t)(SilKit_CanController* controller); /*! \brief Request the transmission of a CanFrame * @@ -270,11 +270,11 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_CanController_Sleep_t)(SilKit_CanCo * reobtained in the SilKit_CanController_AddFrameTransmitHandler * handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_SendFrame(SilKit_CanController* controller, SilKit_CanFrame* frame, - void* userContext); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_SendFrame(SilKit_CanController* controller, + SilKit_CanFrame* frame, void* userContext); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_SendFrame_t)(SilKit_CanController* controller, SilKit_CanFrame* frame, - void* userContext); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_SendFrame_t)(SilKit_CanController* controller, + SilKit_CanFrame* frame, void* userContext); /*! \brief Configure the baud rate of the controller * @@ -294,10 +294,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_SendFrame_t)(SilKit_ * configuration and interoperation of the connected controllers. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_SetBaudRate(SilKit_CanController* controller, uint32_t rate, - uint32_t fdRate, uint32_t xlRate); + uint32_t fdRate, uint32_t xlRate); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_SetBaudRate_t)(SilKit_CanController* controller, uint32_t rate, - uint32_t fdRate, uint32_t xlRate); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_SetBaudRate_t)(SilKit_CanController* controller, + uint32_t rate, uint32_t fdRate, + uint32_t xlRate); /*! \brief Register a callback for the TX status of sent CAN messages * @@ -313,15 +314,13 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_SetBaudRate_t)(SilKi * \param statusMask A mask to select for which transmit statuses the handler should be called. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_AddFrameTransmitHandler(SilKit_CanController* controller, void* context, - SilKit_CanFrameTransmitHandler_t handler, - SilKit_CanTransmitStatus statusMask, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_AddFrameTransmitHandler( + SilKit_CanController* controller, void* context, SilKit_CanFrameTransmitHandler_t handler, + SilKit_CanTransmitStatus statusMask, SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_AddFrameTransmitHandler_t)(SilKit_CanController* controller, void* context, - SilKit_CanFrameTransmitHandler_t handler, - SilKit_CanTransmitStatus statusMask, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_AddFrameTransmitHandler_t)( + SilKit_CanController* controller, void* context, SilKit_CanFrameTransmitHandler_t handler, + SilKit_CanTransmitStatus statusMask, SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_CanFrameTransmitHandler_t by SilKit_HandlerId on this controller * @@ -329,10 +328,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_AddFrameTransmitHand * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveFrameTransmitHandler(SilKit_CanController* controller, - SilKit_HandlerId handlerId); + SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_RemoveFrameTransmitHandler_t)(SilKit_CanController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_RemoveFrameTransmitHandler_t)( + SilKit_CanController* controller, SilKit_HandlerId handlerId); /*! \brief Register a callback for CAN message reception * @@ -345,13 +344,16 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_RemoveFrameTransmitH * \param directionMask A bit mask defining the transmit direction of the messages (rx/tx) * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_AddFrameHandler(SilKit_CanController* controller, void* context, - SilKit_CanFrameHandler_t handler, - SilKit_Direction directionMask, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_AddFrameHandler(SilKit_CanController* controller, + void* context, + SilKit_CanFrameHandler_t handler, + SilKit_Direction directionMask, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_AddFrameHandler_t)(SilKit_CanController* controller, void* context, - SilKit_CanFrameHandler_t handler, SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_AddFrameHandler_t)(SilKit_CanController* controller, + void* context, + SilKit_CanFrameHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_CanFrameHandler_t by SilKit_HandlerId on this controller * @@ -359,9 +361,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_AddFrameHandler_t)(S * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveFrameHandler(SilKit_CanController* controller, - SilKit_HandlerId handlerId); + SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_RemoveFrameHandler_t)(SilKit_CanController* controller, SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_RemoveFrameHandler_t)(SilKit_CanController* controller, + SilKit_HandlerId handlerId); /*! \brief Register a callback for controller state changes * @@ -375,13 +378,13 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_RemoveFrameHandler_t * \param handler The handler to be called on state change. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_AddStateChangeHandler(SilKit_CanController* controller, void* context, - SilKit_CanStateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_CanController_AddStateChangeHandler(SilKit_CanController* controller, void* context, + SilKit_CanStateChangeHandler_t handler, SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_AddStateChangeHandler_t)(SilKit_CanController* controller, void* context, - SilKit_CanStateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_AddStateChangeHandler_t)( + SilKit_CanController* controller, void* context, SilKit_CanStateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_CanStateChangeHandler_t by SilKit_HandlerId on this controller * @@ -389,10 +392,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_AddStateChangeHandle * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveStateChangeHandler(SilKit_CanController* controller, - SilKit_HandlerId handlerId); + SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_RemoveStateChangeHandler_t)(SilKit_CanController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_RemoveStateChangeHandler_t)(SilKit_CanController* controller, + SilKit_HandlerId handlerId); /*! \brief Register a callback for changes of the controller's error state * @@ -406,25 +409,24 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_RemoveStateChangeHan * \param handler The handler to be called on error state change. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_AddErrorStateChangeHandler(SilKit_CanController* controller, - void* context, - SilKit_CanErrorStateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_AddErrorStateChangeHandler( + SilKit_CanController* controller, void* context, SilKit_CanErrorStateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_AddErrorStateChangeHandler_t)(SilKit_CanController* controller, void* context, - SilKit_CanErrorStateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_AddErrorStateChangeHandler_t)( + SilKit_CanController* controller, void* context, SilKit_CanErrorStateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_CanErrorStateChangeHandler_t by SilKit_HandlerId on this controller * * \param controller The CAN controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveErrorStateChangeHandler(SilKit_CanController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_CanController_RemoveErrorStateChangeHandler(SilKit_CanController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_CanController_RemoveErrorStateChangeHandler_t)(SilKit_CanController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_CanController_RemoveErrorStateChangeHandler_t)( + SilKit_CanController* controller, SilKit_HandlerId handlerId); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/DataPubSub.h b/SilKit/include/silkit/capi/DataPubSub.h old mode 100755 new mode 100644 index 1030e47a9..a434620f9 --- a/SilKit/include/silkit/capi/DataPubSub.h +++ b/SilKit/include/silkit/capi/DataPubSub.h @@ -47,7 +47,7 @@ typedef struct //! Send timestamp of the event SilKit_NanosecondsTime timestamp; //! Data field containing the payload - SilKit_ByteVector data; + SilKit_ByteVector data; } SilKit_DataMessageEvent; /*! \brief Represents a handle to a data publisher instance */ @@ -60,8 +60,8 @@ typedef struct SilKit_DataSubscriber SilKit_DataSubscriber; * \param subscriber The affected subscriber. * \param dataMessageEvent Contains the raw data and send timestamp. */ -typedef void (SilKitFPTR *SilKit_DataMessageHandler_t)(void* context, SilKit_DataSubscriber* subscriber, - const SilKit_DataMessageEvent* dataMessageEvent); +typedef void(SilKitFPTR* SilKit_DataMessageHandler_t)(void* context, SilKit_DataSubscriber* subscriber, + const SilKit_DataMessageEvent* dataMessageEvent); /*! \brief Create a DataPublisher on the provided simulation participant with the provided properties. * \param outPublisher Pointer to which the resulting DataPublisher reference will be written. @@ -103,9 +103,11 @@ typedef SilKit_ReturnCode(SilKitFPTR* SilKit_DataSubscriber_Create_t)( * \param self The DataPublisher that should publish the data. * \param data The data that should be published. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_DataPublisher_Publish(SilKit_DataPublisher* self, const SilKit_ByteVector* data); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_DataPublisher_Publish(SilKit_DataPublisher* self, + const SilKit_ByteVector* data); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_DataPublisher_Publish_t)(SilKit_DataPublisher* self, const SilKit_ByteVector* data); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_DataPublisher_Publish_t)(SilKit_DataPublisher* self, + const SilKit_ByteVector* data); /*! \brief Sets / overwrites the default handler to be called on data reception. * \param self The DataSubscriber for which the handler should be set. @@ -115,8 +117,8 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_DataPublisher_Publish_t)(SilKit_Da SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_DataSubscriber_SetDataMessageHandler( SilKit_DataSubscriber* self, void* context, SilKit_DataMessageHandler_t dataHandler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_DataSubscriber_SetDataMessageHandler_t)(SilKit_DataSubscriber* self, void* context, - SilKit_DataMessageHandler_t dataHandler); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_DataSubscriber_SetDataMessageHandler_t)( + SilKit_DataSubscriber* self, void* context, SilKit_DataMessageHandler_t dataHandler); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/Ethernet.h b/SilKit/include/silkit/capi/Ethernet.h old mode 100755 new mode 100644 index 8d3b71841..391a4f443 --- a/SilKit/include/silkit/capi/Ethernet.h +++ b/SilKit/include/silkit/capi/Ethernet.h @@ -33,21 +33,21 @@ SILKIT_BEGIN_DECLS typedef uint32_t SilKit_EthernetTransmitStatus; //! The message was successfully transmitted on the CAN bus. -#define SilKit_EthernetTransmitStatus_Transmitted ((SilKit_EthernetTransmitStatus) BIT(0)) +#define SilKit_EthernetTransmitStatus_Transmitted ((SilKit_EthernetTransmitStatus)BIT(0)) //! The transmit request was rejected, because the Ethernet controller is not active. -#define SilKit_EthernetTransmitStatus_ControllerInactive ((SilKit_EthernetTransmitStatus) BIT(1)) +#define SilKit_EthernetTransmitStatus_ControllerInactive ((SilKit_EthernetTransmitStatus)BIT(1)) //! The transmit request was rejected, because the Ethernet link is down. -#define SilKit_EthernetTransmitStatus_LinkDown ((SilKit_EthernetTransmitStatus) BIT(2)) +#define SilKit_EthernetTransmitStatus_LinkDown ((SilKit_EthernetTransmitStatus)BIT(2)) //! The transmit request was dropped, because the transmit queue is full. -#define SilKit_EthernetTransmitStatus_Dropped ((SilKit_EthernetTransmitStatus) BIT(3)) +#define SilKit_EthernetTransmitStatus_Dropped ((SilKit_EthernetTransmitStatus)BIT(3)) /* (SilKit_EthernetTransmitStatus) BIT(4) is RESERVED (used to be SilKit_EthernetTransmitStatus_DuplicatedTransmitId) */ //! The given raw Ethernet frame is ill formated (e.g. frame length is too small or too large, etc.). -#define SilKit_EthernetTransmitStatus_InvalidFrameFormat ((SilKit_EthernetTransmitStatus) BIT(5)) +#define SilKit_EthernetTransmitStatus_InvalidFrameFormat ((SilKit_EthernetTransmitStatus)BIT(5)) //! Combines all available transmit statuses. #define SilKit_EthernetTransmitStatus_DefaultMask \ @@ -59,13 +59,13 @@ typedef uint32_t SilKit_EthernetTransmitStatus; typedef uint32_t SilKit_EthernetState; //! The Ethernet controller is switched off (default after reset). -#define SilKit_EthernetState_Inactive ((SilKit_EthernetState) 0) +#define SilKit_EthernetState_Inactive ((SilKit_EthernetState)0) //! The Ethernet controller is active, but a link to another Ethernet controller in not yet established. -#define SilKit_EthernetState_LinkDown ((SilKit_EthernetState) 1) +#define SilKit_EthernetState_LinkDown ((SilKit_EthernetState)1) //! The Ethernet controller is active and the link to another Ethernet controller is established. -#define SilKit_EthernetState_LinkUp ((SilKit_EthernetState) 2) +#define SilKit_EthernetState_LinkUp ((SilKit_EthernetState)2) typedef struct @@ -92,7 +92,7 @@ typedef struct } SilKit_EthernetFrame; -typedef struct +typedef struct { SilKit_StructHeader structHeader; //!< The interface id that specifies which version of this struct was obtained SilKit_NanosecondsTime timestamp; //!< Send time @@ -117,32 +117,32 @@ typedef struct SilKit_EthernetController SilKit_EthernetController; * \param controller The Ethernet controller that received the message. * \param frameEvent Contains the raw frame and the timestamp of the event. */ -typedef void (SilKitFPTR *SilKit_EthernetFrameHandler_t)(void* context, SilKit_EthernetController* controller, - SilKit_EthernetFrameEvent* frameEvent); - +typedef void(SilKitFPTR* SilKit_EthernetFrameHandler_t)(void* context, SilKit_EthernetController* controller, + SilKit_EthernetFrameEvent* frameEvent); + /*! Callback type to indicate that a EthernetFrame has been sent. * \param context The by the user provided context on registration. * \param controller The Ethernet controller that received the acknowledge. * \param frameTransmitEvent Contains the transmit status and the timestamp of the event. */ -typedef void (SilKitFPTR *SilKit_EthernetFrameTransmitHandler_t)(void* context, SilKit_EthernetController* controller, - SilKit_EthernetFrameTransmitEvent* frameTransmitEvent); - +typedef void(SilKitFPTR* SilKit_EthernetFrameTransmitHandler_t)(void* context, SilKit_EthernetController* controller, + SilKit_EthernetFrameTransmitEvent* frameTransmitEvent); + /*! Callback type to indicate that the Ethernet controller state has changed. * \param context The by the user provided context on registration. * \param controller The Ethernet controller whose state did change. * \param stateChangeEvent Contains the new state and the timestamp of the event. */ -typedef void (SilKitFPTR *SilKit_EthernetStateChangeHandler_t)(void* context, SilKit_EthernetController* controller, - SilKit_EthernetStateChangeEvent* stateChangeEvent); +typedef void(SilKitFPTR* SilKit_EthernetStateChangeHandler_t)(void* context, SilKit_EthernetController* controller, + SilKit_EthernetStateChangeEvent* stateChangeEvent); /*! Callback type to indicate that the link bit rate has changed. * \param context Context pointer provided by the user on registration. * \param controller The Ethernet controller that is affected. * \param bitrateChangeEvent Contains the new bitrate and the timestamp of the event. */ -typedef void (SilKitFPTR *SilKit_EthernetBitrateChangeHandler_t)(void* context, SilKit_EthernetController* controller, - SilKit_EthernetBitrateChangeEvent* bitrateChangeEvent); +typedef void(SilKitFPTR* SilKit_EthernetBitrateChangeHandler_t)(void* context, SilKit_EthernetController* controller, + SilKit_EthernetBitrateChangeEvent* bitrateChangeEvent); /*! \brief Create an Ethernet controller at this SIL Kit simulation participant. * @@ -154,15 +154,13 @@ typedef void (SilKitFPTR *SilKit_EthernetBitrateChangeHandler_t)(void* context, * ! \note The object returned must not be deallocated using free()! * */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_Create( - SilKit_EthernetController** outController, - SilKit_Participant* participant, const char* name, const char* network); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_Create(SilKit_EthernetController** outController, + SilKit_Participant* participant, + const char* name, const char* network); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_EthernetController_Create_t)( - SilKit_EthernetController** outController, - SilKit_Participant* participant, - const char* name, - const char* network); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_Create_t)(SilKit_EthernetController** outController, + SilKit_Participant* participant, + const char* name, const char* network); /*! \brief Activates the Ethernet controller * @@ -176,7 +174,7 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_EthernetController_Create_t)( */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_Activate(SilKit_EthernetController* controller); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_EthernetController_Activate_t)(SilKit_EthernetController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_Activate_t)(SilKit_EthernetController* controller); /*! \brief Deactivate the Ethernet controller * @@ -190,7 +188,7 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_EthernetController_Activate_t)(SilK */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_Deactivate(SilKit_EthernetController* controller); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_EthernetController_Deactivate_t)(SilKit_EthernetController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_Deactivate_t)(SilKit_EthernetController* controller); /*! \brief Register a callback for Ethernet message reception * @@ -206,27 +204,25 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_EthernetController_Deactivate_t)(Si * */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddFrameHandler(SilKit_EthernetController* controller, - void* context, - SilKit_EthernetFrameHandler_t handler, - SilKit_Direction directionMask, - SilKit_HandlerId* outHandlerId); + void* context, + SilKit_EthernetFrameHandler_t handler, + SilKit_Direction directionMask, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_AddFrameHandler_t)(SilKit_EthernetController* controller, - void* context, - SilKit_EthernetFrameHandler_t handler, - SilKit_Direction directionMask, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_AddFrameHandler_t)( + SilKit_EthernetController* controller, void* context, SilKit_EthernetFrameHandler_t handler, + SilKit_Direction directionMask, SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_EthernetFrameHandler_t by SilKit_HandlerId on this controller * * \param controller The Ethernet controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveFrameHandler(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_EthernetController_RemoveFrameHandler(SilKit_EthernetController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_RemoveFrameHandler_t)(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_RemoveFrameHandler_t)( + SilKit_EthernetController* controller, SilKit_HandlerId handlerId); /*! \brief Register a callback for Ethernet transmit acknowledgments * @@ -246,14 +242,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_RemoveFrameHand * \result A return code identifying the success/failure of the call. * */ -SilKitAPI SilKit_ReturnCode - SilKitCALL SilKit_EthernetController_AddFrameTransmitHandler(SilKit_EthernetController* controller, - void* context, - SilKit_EthernetFrameTransmitHandler_t handler, - SilKit_EthernetTransmitStatus transmitStatusMask, - SilKit_HandlerId* outHandlerId); - -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_AddFrameTransmitHandler_t)( +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddFrameTransmitHandler( + SilKit_EthernetController* controller, void* context, SilKit_EthernetFrameTransmitHandler_t handler, + SilKit_EthernetTransmitStatus transmitStatusMask, SilKit_HandlerId* outHandlerId); + +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_AddFrameTransmitHandler_t)( SilKit_EthernetController* controller, void* context, SilKit_EthernetFrameTransmitHandler_t handler, SilKit_EthernetTransmitStatus transmitStatusMask, SilKit_HandlerId* outHandlerId); @@ -262,11 +255,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_AddFrameTransmi * \param controller The Ethernet controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveFrameTransmitHandler(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_EthernetController_RemoveFrameTransmitHandler(SilKit_EthernetController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_RemoveFrameTransmitHandler_t)(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_RemoveFrameTransmitHandler_t)( + SilKit_EthernetController* controller, SilKit_HandlerId handlerId); /*! \brief Register a callback for changes of the controller state * @@ -284,26 +277,24 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_RemoveFrameTran * \result A return code identifying the success/failure of the call. * */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddStateChangeHandler(SilKit_EthernetController* controller, - void* context, - SilKit_EthernetStateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddStateChangeHandler( + SilKit_EthernetController* controller, void* context, SilKit_EthernetStateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_AddStateChangeHandler_t)(SilKit_EthernetController* controller, - void* context, - SilKit_EthernetStateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_AddStateChangeHandler_t)( + SilKit_EthernetController* controller, void* context, SilKit_EthernetStateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_EthernetStateChangeHandler_t by SilKit_HandlerId on this controller * * \param controller The Ethernet controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveStateChangeHandler(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_EthernetController_RemoveStateChangeHandler(SilKit_EthernetController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_RemoveStateChangeHandler_t)(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_RemoveStateChangeHandler_t)( + SilKit_EthernetController* controller, SilKit_HandlerId handlerId); /*! \brief Register a callback for changes of the link bit rate @@ -319,24 +310,23 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_RemoveStateChan * \result A return code identifying the success/failure of the call. * */ -SilKitAPI SilKit_ReturnCode -SilKitCALL SilKit_EthernetController_AddBitrateChangeHandler(SilKit_EthernetController* controller, void* context, - SilKit_EthernetBitrateChangeHandler_t handler, SilKit_HandlerId* outHandlerId); - -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_AddBitrateChangeHandler_t)(SilKit_EthernetController* controller, - void* context, - SilKit_EthernetBitrateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddBitrateChangeHandler( + SilKit_EthernetController* controller, void* context, SilKit_EthernetBitrateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId); + +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_AddBitrateChangeHandler_t)( + SilKit_EthernetController* controller, void* context, SilKit_EthernetBitrateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_EthernetBitrateChangeHandler_t by SilKit_HandlerId on this controller * * \param controller The Ethernet controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveBitrateChangeHandler(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_EthernetController_RemoveBitrateChangeHandler(SilKit_EthernetController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_RemoveBitrateChangeHandler_t)(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_RemoveBitrateChangeHandler_t)( + SilKit_EthernetController* controller, SilKit_HandlerId handlerId); /*! \brief Send an Ethernet frame * @@ -358,15 +348,13 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_EthernetController_RemoveBitrateCh * the frame ack handler * \result A return code identifying the success/failure of the call. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_SendFrame( - SilKit_EthernetController* controller, - SilKit_EthernetFrame* frame, - void* userContext); - -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_EthernetController_SendFrame_t)( - SilKit_EthernetController* controller, - SilKit_EthernetFrame* frame, - void* userContext); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_EthernetController_SendFrame(SilKit_EthernetController* controller, + SilKit_EthernetFrame* frame, + void* userContext); + +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_EthernetController_SendFrame_t)(SilKit_EthernetController* controller, + SilKit_EthernetFrame* frame, + void* userContext); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/EventProducer.h b/SilKit/include/silkit/capi/EventProducer.h new file mode 100644 index 000000000..96f1cf287 --- /dev/null +++ b/SilKit/include/silkit/capi/EventProducer.h @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include "silkit/capi/Types.h" +#include "silkit/capi/InterfaceIdentifiers.h" +#include "silkit/capi/SilKitMacros.h" +#include "silkit/capi/NetworkSimulator.h" + +#include "silkit/capi/Can.h" +#include "silkit/capi/Flexray.h" +#include "silkit/capi/Ethernet.h" +#include "silkit/capi/Lin.h" + +#pragma pack(push) +#pragma pack(8) + +SILKIT_BEGIN_DECLS + +typedef struct SilKit_Experimental_EventProducer SilKit_Experimental_EventProducer; +typedef struct SilKit_Experimental_CanEventProducer SilKit_Experimental_CanEventProducer; +typedef struct SilKit_Experimental_FlexRayEventProducer SilKit_Experimental_FlexRayEventProducer; +typedef struct SilKit_Experimental_EthernetEventProducer SilKit_Experimental_EthernetEventProducer; +typedef struct SilKit_Experimental_LinEventProducer SilKit_Experimental_LinEventProducer; + +typedef uint64_t SilKit_Experimental_ControllerDescriptor; +#define SilKit_Experimental_ControllerDescriptor_Invalid ((SilKit_Experimental_ControllerDescriptor)0) + +struct SilKit_Experimental_EventReceivers +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + size_t numReceivers; + const SilKit_Experimental_ControllerDescriptor* controllerDescriptors; +}; +typedef struct SilKit_Experimental_EventReceivers SilKit_Experimental_EventReceivers; + +// -------------------------------- +// CAN +// -------------------------------- + +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_CanEventProducer_Produce( + SilKit_Experimental_CanEventProducer* eventProducer, SilKit_StructHeader* msg, + const SilKit_Experimental_EventReceivers* receivers); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_CanEventProducer_Produce_t)( + SilKit_Experimental_CanEventProducer* eventProducer, SilKit_StructHeader* msg, + const SilKit_Experimental_EventReceivers* receivers); + +// -------------------------------- +// FlexRay +// -------------------------------- + +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_FlexRayEventProducer_Produce( + SilKit_Experimental_FlexRayEventProducer* eventProducer, SilKit_StructHeader* msg, + const SilKit_Experimental_EventReceivers* receivers); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_FlexRayEventProducer_Produce_t)( + SilKit_Experimental_FlexRayEventProducer* eventProducer, SilKit_StructHeader* msg, + const SilKit_Experimental_EventReceivers* receivers); + +// -------------------------------- +// Ethernet +// -------------------------------- + +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_EthernetEventProducer_Produce( + SilKit_Experimental_EthernetEventProducer* eventProducer, SilKit_StructHeader* msg, + const SilKit_Experimental_EventReceivers* receivers); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_EthernetEventProducer_Produce_t)( + SilKit_Experimental_EthernetEventProducer* eventProducer, SilKit_StructHeader* msg, + const SilKit_Experimental_EventReceivers* receivers); + + +// -------------------------------- +// Lin +// -------------------------------- + +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinEventProducer_Produce( + SilKit_Experimental_LinEventProducer* eventProducer, SilKit_StructHeader* msg, + const SilKit_Experimental_EventReceivers* receivers); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_LinEventProducer_Produce_t)( + SilKit_Experimental_LinEventProducer* eventProducer, SilKit_StructHeader* msg, + const SilKit_Experimental_EventReceivers* receivers); + +SILKIT_END_DECLS + +#pragma pack(pop) diff --git a/SilKit/include/silkit/capi/Flexray.h b/SilKit/include/silkit/capi/Flexray.h old mode 100755 new mode 100644 index c5ea93842..b45436162 --- a/SilKit/include/silkit/capi/Flexray.h +++ b/SilKit/include/silkit/capi/Flexray.h @@ -40,18 +40,18 @@ typedef int32_t SilKit_FlexrayMacroTick; //! \brief Type and constants for the FlexRay channel parameter A, B, or AB typedef uint32_t SilKit_FlexrayChannel; #define SilKit_FlexrayChannel_None ((SilKit_FlexrayChannel)0x00) -#define SilKit_FlexrayChannel_A ((SilKit_FlexrayChannel)0x01) -#define SilKit_FlexrayChannel_B ((SilKit_FlexrayChannel)0x02) -#define SilKit_FlexrayChannel_AB ((SilKit_FlexrayChannel)0x03) +#define SilKit_FlexrayChannel_A ((SilKit_FlexrayChannel)0x01) +#define SilKit_FlexrayChannel_B ((SilKit_FlexrayChannel)0x02) +#define SilKit_FlexrayChannel_AB ((SilKit_FlexrayChannel)0x03) //! \brief Period of the clock (used for micro tick period and sample clock period). typedef uint32_t SilKit_FlexrayClockPeriod; //!< 12.5ns / 80MHz #define SilKit_FlexrayClockPeriod_T12_5NS ((SilKit_FlexrayClockPeriod)1) //!< 25ns / 40MHz -#define SilKit_FlexrayClockPeriod_T25NS ((SilKit_FlexrayClockPeriod)2) +#define SilKit_FlexrayClockPeriod_T25NS ((SilKit_FlexrayClockPeriod)2) //!< 50ns / 20MHz -#define SilKit_FlexrayClockPeriod_T50NS ((SilKit_FlexrayClockPeriod)3) +#define SilKit_FlexrayClockPeriod_T50NS ((SilKit_FlexrayClockPeriod)3) /*! * \brief Protocol relevant global cluster parameters @@ -60,86 +60,86 @@ typedef uint32_t SilKit_FlexrayClockPeriod; */ struct SilKit_FlexrayClusterParameters { - //! The interface id specifying which version of this struct was obtained - SilKit_StructHeader structHeader; + //! The interface id specifying which version of this struct was obtained + SilKit_StructHeader structHeader; - //! Number of attempts for a cold start before giving up (range 2-31). - uint8_t gColdstartAttempts; + //! Number of attempts for a cold start before giving up (range 2-31). + uint8_t gColdstartAttempts; - //! Max cycle count value in a given cluster (range 7-63, must be an odd integer). - uint8_t gCycleCountMax; + //! Max cycle count value in a given cluster (range 7-63, must be an odd integer). + uint8_t gCycleCountMax; - //! Time offset for a static slot in MacroTicks (MT) (range 1-63). - uint16_t gdActionPointOffset; + //! Time offset for a static slot in MacroTicks (MT) (range 1-63). + uint16_t gdActionPointOffset; - ////! Not used by network simulator - // gdCASRxLowMax + ////! Not used by network simulator + // gdCASRxLowMax - //! Duration of the idle phase within a dynamic slot in gdMiniSlots (range 0-2). - uint16_t gdDynamicSlotIdlePhase; + //! Duration of the idle phase within a dynamic slot in gdMiniSlots (range 0-2). + uint16_t gdDynamicSlotIdlePhase; - ////! Not used by network simulator - // gdIgnoreAfterTx + ////! Not used by network simulator + // gdIgnoreAfterTx - //! Duration of a mini slot in MacroTicks (MT) (2-63). - uint16_t gdMiniSlot; + //! Duration of a mini slot in MacroTicks (MT) (2-63). + uint16_t gdMiniSlot; - //! Time offset for a mini slot in MacroTicks (MT) (range 1-31). - uint16_t gdMiniSlotActionPointOffset; + //! Time offset for a mini slot in MacroTicks (MT) (range 1-31). + uint16_t gdMiniSlotActionPointOffset; - //! Duration of a static slot in MacroTicks (MT) (3-664). - uint16_t gdStaticSlot; + //! Duration of a static slot in MacroTicks (MT) (3-664). + uint16_t gdStaticSlot; - //! Duration of the symbol window in MacroTicks (MT) (range 0-162). - uint16_t gdSymbolWindow; + //! Duration of the symbol window in MacroTicks (MT) (range 0-162). + uint16_t gdSymbolWindow; - //! Time offset for a static symbol windows in MacroTicks (MT) (range 1-63). - uint16_t gdSymbolWindowActionPointOffset; + //! Time offset for a static symbol windows in MacroTicks (MT) (range 1-63). + uint16_t gdSymbolWindowActionPointOffset; - //! Duration of TSS (Transmission Start Sequence) in gdBits (range 1-15). - uint16_t gdTSSTransmitter; + //! Duration of TSS (Transmission Start Sequence) in gdBits (range 1-15). + uint16_t gdTSSTransmitter; - ////! Not used by network simulator - // gdWakeupRxIdle + ////! Not used by network simulator + // gdWakeupRxIdle - ////! Not used by network simulator - // gdWakeupRxLow + ////! Not used by network simulator + // gdWakeupRxLow - ////! Not used by network simulator - // gdWakeupRxWindow + ////! Not used by network simulator + // gdWakeupRxWindow - //! Duration of LOW Phase of a wakeup symbol in gdBit (range 15-60). - uint16_t gdWakeupTxActive; + //! Duration of LOW Phase of a wakeup symbol in gdBit (range 15-60). + uint16_t gdWakeupTxActive; - //! Duration of the idle of a wakeup symbol in gdBit (45-180). - uint16_t gdWakeupTxIdle; + //! Duration of the idle of a wakeup symbol in gdBit (45-180). + uint16_t gdWakeupTxIdle; - /*! + /*! * Upper limit for the startup listen timeout and wakeup listen timeout in the * presence of noise. Used as a multiplier of pdListenTimeout (range 2-16). */ - uint8_t gListenNoise; + uint8_t gListenNoise; - //! Number of MacroTicks (MT) per cycle, (range 8-16000). - uint16_t gMacroPerCycle; + //! Number of MacroTicks (MT) per cycle, (range 8-16000). + uint16_t gMacroPerCycle; - //! Threshold used for testing the vClockCorrectionFailed counter (range 1-15). - uint8_t gMaxWithoutClockCorrectionFatal; + //! Threshold used for testing the vClockCorrectionFailed counter (range 1-15). + uint8_t gMaxWithoutClockCorrectionFatal; - //! Threshold used for testing the vClockCorrectionFailed counter (range 1-15). - uint8_t gMaxWithoutClockCorrectionPassive; + //! Threshold used for testing the vClockCorrectionFailed counter (range 1-15). + uint8_t gMaxWithoutClockCorrectionPassive; - //! Number of mini slots (range 0-7988). - uint16_t gNumberOfMiniSlots; + //! Number of mini slots (range 0-7988). + uint16_t gNumberOfMiniSlots; - //! Number of static slots in a cycle (range 2-1023). - uint16_t gNumberOfStaticSlots; + //! Number of static slots in a cycle (range 2-1023). + uint16_t gNumberOfStaticSlots; - //! Length of the payload of a static frame in 16-Bits words (range 0-127). - uint16_t gPayloadLengthStatic; + //! Length of the payload of a static frame in 16-Bits words (range 0-127). + uint16_t gPayloadLengthStatic; - //! Max number of distinct sync frame identifiers present in a given cluster. (range 2-15). - uint8_t gSyncFrameIDCountMax; + //! Max number of distinct sync frame identifiers present in a given cluster. (range 2-15). + uint8_t gSyncFrameIDCountMax; }; typedef struct SilKit_FlexrayClusterParameters SilKit_FlexrayClusterParameters; @@ -150,116 +150,116 @@ typedef struct SilKit_FlexrayClusterParameters SilKit_FlexrayClusterParameters; */ struct SilKit_FlexrayNodeParameters { - //! The interface id specifying which version of this struct was obtained - SilKit_StructHeader structHeader; + //! The interface id specifying which version of this struct was obtained + SilKit_StructHeader structHeader; - // ---------------------------------------------------------------------- - // Parameters according to B.3.2.1 + // ---------------------------------------------------------------------- + // Parameters according to B.3.2.1 - //! Controls the transition to halt state due to clock synchronization errors. (0,1). - uint8_t pAllowHaltDueToClock; + //! Controls the transition to halt state due to clock synchronization errors. (0,1). + uint8_t pAllowHaltDueToClock; - //! Required number of consecutive even / odd cycle pairs for normal passive to normal active (range 0-31). - uint8_t pAllowPassiveToActive; + //! Required number of consecutive even / odd cycle pairs for normal passive to normal active (range 0-31). + uint8_t pAllowPassiveToActive; - //! Channel(s) to which the controller is connected (values FlexrayChannel::A, FlexrayChannel::B, FlexrayChannel::AB). - SilKit_FlexrayChannel pChannels; + //! Channel(s) to which the controller is connected (values FlexrayChannel::A, FlexrayChannel::B, FlexrayChannel::AB). + SilKit_FlexrayChannel pChannels; - //! Cluster drift damping factor for rate correction in MicroTicks (range 0-10). - uint8_t pClusterDriftDamping; + //! Cluster drift damping factor for rate correction in MicroTicks (range 0-10). + uint8_t pClusterDriftDamping; - //! Allowed deviation for startup frames during integration in MicroTicks (range 29-2743). - SilKit_FlexrayMicroTick pdAcceptedStartupRange; + //! Allowed deviation for startup frames during integration in MicroTicks (range 29-2743). + SilKit_FlexrayMicroTick pdAcceptedStartupRange; - ////! Not used by network simulator - // pDecodingCorrection + ////! Not used by network simulator + // pDecodingCorrection - ////! Not used by network simulator - // pDelayCompensationA + ////! Not used by network simulator + // pDelayCompensationA - ////! Not used by network simulator - // pDelayCompensationB + ////! Not used by network simulator + // pDelayCompensationB - //! Duration of listen phase in MicroTicks (range 1926-2567692). - SilKit_FlexrayMicroTick pdListenTimeout; + //! Duration of listen phase in MicroTicks (range 1926-2567692). + SilKit_FlexrayMicroTick pdListenTimeout; - ////! Not used by network simulator - // pExternalSync + ////! Not used by network simulator + // pExternalSync - ////! Not used by network simulator - // pExternOffsetCorrection + ////! Not used by network simulator + // pExternOffsetCorrection - ////! Not used by network simulator - // pExternRateCorrection + ////! Not used by network simulator + // pExternRateCorrection - ////! Not used by network simulator - // pFallBackInternal + ////! Not used by network simulator + // pFallBackInternal - //! Slot ID of the key slot (range 0-1023, value 0 means that there is no key slot). - uint16_t pKeySlotId; + //! Slot ID of the key slot (range 0-1023, value 0 means that there is no key slot). + uint16_t pKeySlotId; - //! Shall the node enter key slot only mode after startup. (values 0, 1) (AUTOSAR pSingleSlotEnabled). - uint8_t pKeySlotOnlyEnabled; + //! Shall the node enter key slot only mode after startup. (values 0, 1) (AUTOSAR pSingleSlotEnabled). + uint8_t pKeySlotOnlyEnabled; - //! Key slot is used for startup (range 0, 1). - uint8_t pKeySlotUsedForStartup; + //! Key slot is used for startup (range 0, 1). + uint8_t pKeySlotUsedForStartup; - //! Key slot is used for sync (range 0, 1). - uint8_t pKeySlotUsedForSync; + //! Key slot is used for sync (range 0, 1). + uint8_t pKeySlotUsedForSync; - //! Last mini slot which can be transmitted (range 0-7988). - uint16_t pLatestTx; + //! Last mini slot which can be transmitted (range 0-7988). + uint16_t pLatestTx; - //! Initial startup offset for frame reference point on channel A (rang 2-68 MacroTicks (MT)). - uint8_t pMacroInitialOffsetA; + //! Initial startup offset for frame reference point on channel A (rang 2-68 MacroTicks (MT)). + uint8_t pMacroInitialOffsetA; - //! Initial startup offset for frame reference point on channel B (rang 2-68 MacroTicks (MT)). - uint8_t pMacroInitialOffsetB; + //! Initial startup offset for frame reference point on channel B (rang 2-68 MacroTicks (MT)). + uint8_t pMacroInitialOffsetB; - //! Offset between secondary time reference and MT boundary (range 0-239 MicroTicks). - SilKit_FlexrayMicroTick pMicroInitialOffsetA; + //! Offset between secondary time reference and MT boundary (range 0-239 MicroTicks). + SilKit_FlexrayMicroTick pMicroInitialOffsetA; - //! Offset between secondary time reference and MT boundary (range 0-239 MicroTicks). - SilKit_FlexrayMicroTick pMicroInitialOffsetB; + //! Offset between secondary time reference and MT boundary (range 0-239 MicroTicks). + SilKit_FlexrayMicroTick pMicroInitialOffsetB; - //! Nominal number of MicroTicks in the communication cycle (range 960-1280000). - SilKit_FlexrayMicroTick pMicroPerCycle; + //! Nominal number of MicroTicks in the communication cycle (range 960-1280000). + SilKit_FlexrayMicroTick pMicroPerCycle; - //! Maximum permissible offset correction value (range 15-16082 MicroTicks). - SilKit_FlexrayMicroTick pOffsetCorrectionOut; + //! Maximum permissible offset correction value (range 15-16082 MicroTicks). + SilKit_FlexrayMicroTick pOffsetCorrectionOut; - //! Start of the offset correction phase within the NIT, (7-15999 MT). - uint16_t pOffsetCorrectionStart; + //! Start of the offset correction phase within the NIT, (7-15999 MT). + uint16_t pOffsetCorrectionStart; - //! Maximum permissible rate correction value (range 3-3846 MicroTicks). - SilKit_FlexrayMicroTick pRateCorrectionOut; + //! Maximum permissible rate correction value (range 3-3846 MicroTicks). + SilKit_FlexrayMicroTick pRateCorrectionOut; - ////! Not used by network simulator - // pSecondKeySlotID + ////! Not used by network simulator + // pSecondKeySlotID - ////! Not used by network simulator - // pTwoKeySlotMode + ////! Not used by network simulator + // pTwoKeySlotMode - //! Channel used by the node to send a wakeup pattern (values FlexrayChannel::A, FlexrayChannel::B). - SilKit_FlexrayChannel pWakeupChannel; + //! Channel used by the node to send a wakeup pattern (values FlexrayChannel::A, FlexrayChannel::B). + SilKit_FlexrayChannel pWakeupChannel; - //! Number of repetitions of the wakeup symbol (range 0-63, value 0 or 1 prevents sending of WUP). - uint8_t pWakeupPattern; + //! Number of repetitions of the wakeup symbol (range 0-63, value 0 or 1 prevents sending of WUP). + uint8_t pWakeupPattern; - // ---------------------------------------------------------------------- - // Parameters according to B.3.2.2 + // ---------------------------------------------------------------------- + // Parameters according to B.3.2.2 - //! Duration of a FlexRay MicroTick (12.5ns, 25ns or 50ns). - SilKit_FlexrayClockPeriod pdMicrotick; + //! Duration of a FlexRay MicroTick (12.5ns, 25ns or 50ns). + SilKit_FlexrayClockPeriod pdMicrotick; - ////! Not used by network simulator - // pNMVectorEarlyUpdate + ////! Not used by network simulator + // pNMVectorEarlyUpdate - ////! Not used by network simulator - // pPayloadLengthDynMax + ////! Not used by network simulator + // pPayloadLengthDynMax - //! Number of samples per MicroTick (values 1 or 2). - uint8_t pSamplesPerMicrotick; + //! Number of samples per MicroTick (values 1 or 2). + uint8_t pSamplesPerMicrotick; }; typedef struct SilKit_FlexrayNodeParameters SilKit_FlexrayNodeParameters; @@ -271,84 +271,84 @@ typedef uint8_t SilKit_FlexrayTransmissionMode; //! Configuration of Tx-Buffer, used in struct FlexrayControllerConfig struct SilKit_FlexrayTxBufferConfig { - //! The interface id specifying which version of this struct was obtained - SilKit_StructHeader structHeader; + //! The interface id specifying which version of this struct was obtained + SilKit_StructHeader structHeader; - //! (values FlexrayChannel::A, FlexrayChannel::B, FlexrayChannel::AB) - SilKit_FlexrayChannel channels; + //! (values FlexrayChannel::A, FlexrayChannel::B, FlexrayChannel::AB) + SilKit_FlexrayChannel channels; - //! The slot Id of frame - uint16_t slotId; + //! The slot Id of frame + uint16_t slotId; - //! Base offset for cycle multiplexing (values 0-63). - uint8_t offset; + //! Base offset for cycle multiplexing (values 0-63). + uint8_t offset; - //! Repetition for cycle multiplexing (values 1,2,4,8,16,32,64). - uint8_t repetition; + //! Repetition for cycle multiplexing (values 1,2,4,8,16,32,64). + uint8_t repetition; - //! Set the PPindicator - SilKit_Bool hasPayloadPreambleIndicator; + //! Set the PPindicator + SilKit_Bool hasPayloadPreambleIndicator; - //! Header CRC, 11 bits - uint16_t headerCrc; + //! Header CRC, 11 bits + uint16_t headerCrc; - //! FlexrayTransmissionMode::SingleShot or FlexrayTransmissionMode::Continuous - SilKit_FlexrayTransmissionMode transmissionMode; + //! FlexrayTransmissionMode::SingleShot or FlexrayTransmissionMode::Continuous + SilKit_FlexrayTransmissionMode transmissionMode; }; typedef struct SilKit_FlexrayTxBufferConfig SilKit_FlexrayTxBufferConfig; //! Configure the communication parameters of the FlexRay controller. struct SilKit_FlexrayControllerConfig { - //! The interface id specifying which version of this struct was obtained - SilKit_StructHeader structHeader; - //! FlexRay cluster parameters - SilKit_FlexrayClusterParameters* clusterParams; - //! FlexRay node parameters - SilKit_FlexrayNodeParameters* nodeParams; - - //! FlexRay buffer configs - uint32_t numBufferConfigs; - SilKit_FlexrayTxBufferConfig* bufferConfigs; + //! The interface id specifying which version of this struct was obtained + SilKit_StructHeader structHeader; + //! FlexRay cluster parameters + SilKit_FlexrayClusterParameters* clusterParams; + //! FlexRay node parameters + SilKit_FlexrayNodeParameters* nodeParams; + + //! FlexRay buffer configs + uint32_t numBufferConfigs; + SilKit_FlexrayTxBufferConfig* bufferConfigs; }; typedef struct SilKit_FlexrayControllerConfig SilKit_FlexrayControllerConfig; //! Update the content of a FlexRay TX-Buffer struct SilKit_FlexrayTxBufferUpdate { - //! The interface id specifying which version of this struct was obtained - SilKit_StructHeader structHeader; + //! The interface id specifying which version of this struct was obtained + SilKit_StructHeader structHeader; - //! Index of the TX Buffers according to the configured buffers (cf. FlexrayControllerConfig). - uint16_t txBufferIndex; + //! Index of the TX Buffers according to the configured buffers (cf. FlexrayControllerConfig). + uint16_t txBufferIndex; - //! Payload data valid flag - SilKit_Bool payloadDataValid; + //! Payload data valid flag + SilKit_Bool payloadDataValid; - //! Raw payload containing 0 to 254 bytes. - SilKit_ByteVector payload; + //! Raw payload containing 0 to 254 bytes. + SilKit_ByteVector payload; }; typedef struct SilKit_FlexrayTxBufferUpdate SilKit_FlexrayTxBufferUpdate; //! FlexRay controller commands typedef uint8_t SilKit_FlexrayChiCommand; -#define SilKit_FlexrayChiCommand_RUN ((SilKit_FlexrayChiCommand)0x00) -#define SilKit_FlexrayChiCommand_DEFERRED_HALT ((SilKit_FlexrayChiCommand)0x01) -#define SilKit_FlexrayChiCommand_FREEZE ((SilKit_FlexrayChiCommand)0x02) +#define SilKit_FlexrayChiCommand_RUN ((SilKit_FlexrayChiCommand)0x00) +#define SilKit_FlexrayChiCommand_DEFERRED_HALT ((SilKit_FlexrayChiCommand)0x01) +#define SilKit_FlexrayChiCommand_FREEZE ((SilKit_FlexrayChiCommand)0x02) #define SilKit_FlexrayChiCommand_ALLOW_COLDSTART ((SilKit_FlexrayChiCommand)0x03) -#define SilKit_FlexrayChiCommand_ALL_SLOTS ((SilKit_FlexrayChiCommand)0x04) -#define SilKit_FlexrayChiCommand_WAKEUP ((SilKit_FlexrayChiCommand)0x05) +#define SilKit_FlexrayChiCommand_ALL_SLOTS ((SilKit_FlexrayChiCommand)0x04) +#define SilKit_FlexrayChiCommand_WAKEUP ((SilKit_FlexrayChiCommand)0x05) typedef uint8_t SilKit_FlexrayHeader_Flag; #define SilKit_FlexrayHeader_SuFIndicator ((SilKit_FlexrayHeader_Flag)0x01) #define SilKit_FlexrayHeader_SyFIndicator ((SilKit_FlexrayHeader_Flag)0x02) -#define SilKit_FlexrayHeader_NFIndicator ((SilKit_FlexrayHeader_Flag)0x04) -#define SilKit_FlexrayHeader_PPIndicator ((SilKit_FlexrayHeader_Flag)0x08) +#define SilKit_FlexrayHeader_NFIndicator ((SilKit_FlexrayHeader_Flag)0x04) +#define SilKit_FlexrayHeader_PPIndicator ((SilKit_FlexrayHeader_Flag)0x08) struct SilKit_FlexrayHeader { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - /*! + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + /*! * \brief Flags bit map according to FlagMask. Description: * - [7-5]: unused * - [4]: Reserved bit @@ -357,28 +357,28 @@ struct SilKit_FlexrayHeader * - [1]: SyFIndicator: 0, frame not used for synchronization; 1, frame shall be used for sync * - [0]: SuFIndicator: 0, not a startup frame; 1, a startup frame */ - uint8_t flags; // = 0; - uint16_t frameId; // = 0; //!< Slot ID in which the frame was sent: 1 - 2047 - uint8_t payloadLength; // = 0; //!< Payload length, 7 bits - uint16_t headerCrc; // = 0; //!< Header CRC, 11 bits - uint8_t cycleCount; // = 0; //!< Cycle in which the frame was sent: 0 - 63 + uint8_t flags; // = 0; + uint16_t frameId; // = 0; //!< Slot ID in which the frame was sent: 1 - 2047 + uint8_t payloadLength; // = 0; //!< Payload length, 7 bits + uint16_t headerCrc; // = 0; //!< Header CRC, 11 bits + uint8_t cycleCount; // = 0; //!< Cycle in which the frame was sent: 0 - 63 }; typedef struct SilKit_FlexrayHeader SilKit_FlexrayHeader; struct SilKit_FlexrayFrame { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - SilKit_FlexrayHeader* header; //!< Header flags, slot, crc, and cycle indidcators - SilKit_ByteVector payload; + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_FlexrayHeader* header; //!< Header flags, slot, crc, and cycle indidcators + SilKit_ByteVector payload; }; typedef struct SilKit_FlexrayFrame SilKit_FlexrayFrame; struct SilKit_FlexrayFrameEvent { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - SilKit_NanosecondsTime timestamp; //!< Time at end of frame transmission - SilKit_FlexrayChannel channel; //!< FlexRay channel A or B. (Valid values: FlexrayChannel::A, FlexrayChannel::B). - SilKit_FlexrayFrame* frame; //!< Received FlexRay frame + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_NanosecondsTime timestamp; //!< Time at end of frame transmission + SilKit_FlexrayChannel channel; //!< FlexRay channel A or B. (Valid values: FlexrayChannel::A, FlexrayChannel::B). + SilKit_FlexrayFrame* frame; //!< Received FlexRay frame }; typedef struct SilKit_FlexrayFrameEvent SilKit_FlexrayFrameEvent; @@ -387,11 +387,11 @@ typedef struct SilKit_FlexrayFrameEvent SilKit_FlexrayFrameEvent; */ struct SilKit_FlexrayFrameTransmitEvent { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - SilKit_NanosecondsTime timestamp; //!< Time at end of frame transmission - uint16_t txBufferIndex; //!< Tx buffer, that was used for the transmission - SilKit_FlexrayChannel channel; //!< FlexRay channel A or B. (Valid values: FlexrayChannel::A, FlexrayChannel::B). - SilKit_FlexrayFrame* frame; //!< Copy of the FlexRay frame that was successfully transmitted + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_NanosecondsTime timestamp; //!< Time at end of frame transmission + uint16_t txBufferIndex; //!< Tx buffer, that was used for the transmission + SilKit_FlexrayChannel channel; //!< FlexRay channel A or B. (Valid values: FlexrayChannel::A, FlexrayChannel::B). + SilKit_FlexrayFrame* frame; //!< Copy of the FlexRay frame that was successfully transmitted }; typedef struct SilKit_FlexrayFrameTransmitEvent SilKit_FlexrayFrameTransmitEvent; @@ -402,19 +402,19 @@ typedef uint8_t SilKit_FlexraySymbolPattern; //! Collision avoidance symbol (CAS) OR media access test symbol (MTS). #define SilKit_FlexraySymbolPattern_CasMts ((SilKit_FlexraySymbolPattern)0x00) //! Wakeup symbol (WUS). -#define SilKit_FlexraySymbolPattern_Wus ((SilKit_FlexraySymbolPattern)0x01) +#define SilKit_FlexraySymbolPattern_Wus ((SilKit_FlexraySymbolPattern)0x01) //! Wakeup During Operation Pattern (WUDOP). -#define SilKit_FlexraySymbolPattern_Wudop ((SilKit_FlexraySymbolPattern)0x02) +#define SilKit_FlexraySymbolPattern_Wudop ((SilKit_FlexraySymbolPattern)0x02) /*! * \brief A FlexRay Symbol as received on the FlexRay bus. */ struct SilKit_FlexraySymbolEvent { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - SilKit_NanosecondsTime timestamp; //!< End time of symbol reception. - SilKit_FlexrayChannel channel; //!< FlexRay channel A or B (values: FlexrayChannel::A, FlexrayChannel::B). - SilKit_FlexraySymbolPattern pattern; //!< The received symbol, e.g. wakeup pattern + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_NanosecondsTime timestamp; //!< End time of symbol reception. + SilKit_FlexrayChannel channel; //!< FlexRay channel A or B (values: FlexrayChannel::A, FlexrayChannel::B). + SilKit_FlexraySymbolPattern pattern; //!< The received symbol, e.g. wakeup pattern }; typedef struct SilKit_FlexraySymbolEvent SilKit_FlexraySymbolEvent; typedef struct SilKit_FlexraySymbolEvent SilKit_FlexraySymbolTransmitEvent; @@ -425,9 +425,9 @@ typedef struct SilKit_FlexraySymbolEvent SilKit_FlexrayWakeupEvent; */ struct SilKit_FlexrayCycleStartEvent { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - SilKit_NanosecondsTime timestamp; //!< Cycle starting time. - uint8_t cycleCounter; //!< Counter of FlexRay cycles. + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_NanosecondsTime timestamp; //!< Cycle starting time. + uint8_t cycleCounter; //!< Counter of FlexRay cycles. }; typedef struct SilKit_FlexrayCycleStartEvent SilKit_FlexrayCycleStartEvent; @@ -439,36 +439,36 @@ typedef uint8_t SilKit_FlexrayPocState; //! CC expects configuration. Initial state after reset. #define SilKit_FlexrayPocState_DefaultConfig ((SilKit_FlexrayPocState)0x00) //! CC is in configuration mode for setting communication parameters -#define SilKit_FlexrayPocState_Config ((SilKit_FlexrayPocState)0x01) +#define SilKit_FlexrayPocState_Config ((SilKit_FlexrayPocState)0x01) //! intermediate state for initialization process (after Config). -#define SilKit_FlexrayPocState_Ready ((SilKit_FlexrayPocState)0x02) +#define SilKit_FlexrayPocState_Ready ((SilKit_FlexrayPocState)0x02) //! FlexRay startup phase -#define SilKit_FlexrayPocState_Startup ((SilKit_FlexrayPocState)0x03) +#define SilKit_FlexrayPocState_Startup ((SilKit_FlexrayPocState)0x03) //! FlexRay wakeup phase -#define SilKit_FlexrayPocState_Wakeup ((SilKit_FlexrayPocState)0x04) +#define SilKit_FlexrayPocState_Wakeup ((SilKit_FlexrayPocState)0x04) //! Normal operating mode -#define SilKit_FlexrayPocState_NormalActive ((SilKit_FlexrayPocState)0x05) +#define SilKit_FlexrayPocState_NormalActive ((SilKit_FlexrayPocState)0x05) //! Operating mode with transient or tolerable errors #define SilKit_FlexrayPocState_NormalPassive ((SilKit_FlexrayPocState)0x06) //! CC is halted (caused by the application (FlexrayChiCommand::DEFERRED_HALT) or by a fatal error). -#define SilKit_FlexrayPocState_Halt ((SilKit_FlexrayPocState)0x07) +#define SilKit_FlexrayPocState_Halt ((SilKit_FlexrayPocState)0x07) /*! * \brief Indicates what slot mode the POC is in. * *AUTOSAR Name:* Fr_SlotModeType */ typedef uint8_t SilKit_FlexraySlotModeType; -#define SilKit_FlexraySlotModeType_KeySlot ((SilKit_FlexraySlotModeType)0x00) +#define SilKit_FlexraySlotModeType_KeySlot ((SilKit_FlexraySlotModeType)0x00) #define SilKit_FlexraySlotModeType_AllPending ((SilKit_FlexraySlotModeType)0x01) -#define SilKit_FlexraySlotModeType_All ((SilKit_FlexraySlotModeType)0x02) +#define SilKit_FlexraySlotModeType_All ((SilKit_FlexraySlotModeType)0x02) /*! * \brief Indicates what error mode the POC is in. * *AUTOSAR Name:* Fr_ErrorModeType */ typedef uint8_t SilKit_FlexrayErrorModeType; -#define SilKit_FlexrayErrorModeType_Active ((SilKit_FlexrayErrorModeType)0x00) -#define SilKit_FlexrayErrorModeType_Passive ((SilKit_FlexrayErrorModeType)0x01) +#define SilKit_FlexrayErrorModeType_Active ((SilKit_FlexrayErrorModeType)0x00) +#define SilKit_FlexrayErrorModeType_Passive ((SilKit_FlexrayErrorModeType)0x01) #define SilKit_FlexrayErrorModeType_CommHalt ((SilKit_FlexrayErrorModeType)0x02) /*! @@ -476,30 +476,30 @@ typedef uint8_t SilKit_FlexrayErrorModeType; * *AUTOSAR Name:* Fr_StartupStateType */ typedef uint8_t SilKit_FlexrayStartupStateType; -#define SilKit_FlexrayStartupStateType_Undefined ((SilKit_FlexrayStartupStateType)0x00) -#define SilKit_FlexrayStartupStateType_ColdStartListen ((SilKit_FlexrayStartupStateType)0x01) -#define SilKit_FlexrayStartupStateType_IntegrationColdstartCheck ((SilKit_FlexrayStartupStateType)0x02) -#define SilKit_FlexrayStartupStateType_ColdStartJoin ((SilKit_FlexrayStartupStateType)0x03) +#define SilKit_FlexrayStartupStateType_Undefined ((SilKit_FlexrayStartupStateType)0x00) +#define SilKit_FlexrayStartupStateType_ColdStartListen ((SilKit_FlexrayStartupStateType)0x01) +#define SilKit_FlexrayStartupStateType_IntegrationColdstartCheck ((SilKit_FlexrayStartupStateType)0x02) +#define SilKit_FlexrayStartupStateType_ColdStartJoin ((SilKit_FlexrayStartupStateType)0x03) #define SilKit_FlexrayStartupStateType_ColdStartCollisionResolution ((SilKit_FlexrayStartupStateType)0x04) -#define SilKit_FlexrayStartupStateType_ColdStartConsistencyCheck ((SilKit_FlexrayStartupStateType)0x05) -#define SilKit_FlexrayStartupStateType_IntegrationListen ((SilKit_FlexrayStartupStateType)0x06) -#define SilKit_FlexrayStartupStateType_InitializeSchedule ((SilKit_FlexrayStartupStateType)0x07) -#define SilKit_FlexrayStartupStateType_IntegrationConsistencyCheck ((SilKit_FlexrayStartupStateType)0x08) -#define SilKit_FlexrayStartupStateType_ColdStartGap ((SilKit_FlexrayStartupStateType)0x09) -#define SilKit_FlexrayStartupStateType_ExternalStartup ((SilKit_FlexrayStartupStateType)0x0A) +#define SilKit_FlexrayStartupStateType_ColdStartConsistencyCheck ((SilKit_FlexrayStartupStateType)0x05) +#define SilKit_FlexrayStartupStateType_IntegrationListen ((SilKit_FlexrayStartupStateType)0x06) +#define SilKit_FlexrayStartupStateType_InitializeSchedule ((SilKit_FlexrayStartupStateType)0x07) +#define SilKit_FlexrayStartupStateType_IntegrationConsistencyCheck ((SilKit_FlexrayStartupStateType)0x08) +#define SilKit_FlexrayStartupStateType_ColdStartGap ((SilKit_FlexrayStartupStateType)0x09) +#define SilKit_FlexrayStartupStateType_ExternalStartup ((SilKit_FlexrayStartupStateType)0x0A) /*! * \brief Indicates the outcome of the wake-up mechanism. * *AUTOSAR Name:* Fr_WakeupStateType */ typedef uint8_t SilKit_FlexrayWakeupStatusType; -#define SilKit_FlexrayWakeupStatusType_Undefined ((SilKit_FlexrayWakeupStatusType)0x00) -#define SilKit_FlexrayWakeupStatusType_ReceivedHeader ((SilKit_FlexrayWakeupStatusType)0x01) -#define SilKit_FlexrayWakeupStatusType_ReceivedWup ((SilKit_FlexrayWakeupStatusType)0x02) -#define SilKit_FlexrayWakeupStatusType_CollisionHeader ((SilKit_FlexrayWakeupStatusType)0x03) -#define SilKit_FlexrayWakeupStatusType_CollisionWup ((SilKit_FlexrayWakeupStatusType)0x04) +#define SilKit_FlexrayWakeupStatusType_Undefined ((SilKit_FlexrayWakeupStatusType)0x00) +#define SilKit_FlexrayWakeupStatusType_ReceivedHeader ((SilKit_FlexrayWakeupStatusType)0x01) +#define SilKit_FlexrayWakeupStatusType_ReceivedWup ((SilKit_FlexrayWakeupStatusType)0x02) +#define SilKit_FlexrayWakeupStatusType_CollisionHeader ((SilKit_FlexrayWakeupStatusType)0x03) +#define SilKit_FlexrayWakeupStatusType_CollisionWup ((SilKit_FlexrayWakeupStatusType)0x04) #define SilKit_FlexrayWakeupStatusType_CollisionUnknown ((SilKit_FlexrayWakeupStatusType)0x05) -#define SilKit_FlexrayWakeupStatusType_Transmitted ((SilKit_FlexrayWakeupStatusType)0x06) +#define SilKit_FlexrayWakeupStatusType_Transmitted ((SilKit_FlexrayWakeupStatusType)0x06) /*! * \brief Protocol Operation Control status as available in the AUTOSAR @@ -512,17 +512,24 @@ typedef uint8_t SilKit_FlexrayWakeupStatusType; */ struct SilKit_FlexrayPocStatusEvent { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - SilKit_NanosecondsTime timestamp; //!< SIL Kit timestamp - SilKit_FlexrayPocState state; /* = SilKit_FlexrayPocState_DefaultConfig; */ //!< Status of the Protocol Operation Control (POC). - SilKit_Bool chiHaltRequest; /* = false; */ //!< indicates whether a halt request was received from the CHI - SilKit_Bool coldstartNoise; /* = false; */ //!< indicates noisy channel conditions during coldstart - SilKit_Bool freeze; /* = false; */ //!< indicates that the POC entered a halt state due to an error condition requiring immediate halt. - SilKit_Bool chiReadyRequest; /* = false; */ //!< indicates that the CHI requested to enter ready state at the end of the communication cycle. - SilKit_FlexrayErrorModeType errorMode; /* = SilKit_FlexrayErrorModeType_Active; */ //!< indicates the error mode of the POC - SilKit_FlexraySlotModeType slotMode; /* = SilKit_FlexraySlotModeType_KeySlot; */ //!< indicates the slot mode of the POC - SilKit_FlexrayStartupStateType startupState; /* = SilKit_FlexrayStartupStateType_Undefined; */ //!< indicates states within the STARTUP mechanism - SilKit_FlexrayWakeupStatusType wakeupStatus; /* = SilKit_FlexrayWakeupStatusType_Undefined; */ //!< outcome of the execution of the WAKEUP mechanism + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_NanosecondsTime timestamp; //!< SIL Kit timestamp + SilKit_FlexrayPocState state; + /* = SilKit_FlexrayPocState_DefaultConfig; */ //!< Status of the Protocol Operation Control (POC). + SilKit_Bool chiHaltRequest; /* = false; */ //!< indicates whether a halt request was received from the CHI + SilKit_Bool coldstartNoise; /* = false; */ //!< indicates noisy channel conditions during coldstart + SilKit_Bool freeze; + /* = false; */ //!< indicates that the POC entered a halt state due to an error condition requiring immediate halt. + SilKit_Bool chiReadyRequest; + /* = false; */ //!< indicates that the CHI requested to enter ready state at the end of the communication cycle. + SilKit_FlexrayErrorModeType errorMode; + /* = SilKit_FlexrayErrorModeType_Active; */ //!< indicates the error mode of the POC + SilKit_FlexraySlotModeType slotMode; + /* = SilKit_FlexraySlotModeType_KeySlot; */ //!< indicates the slot mode of the POC + SilKit_FlexrayStartupStateType startupState; + /* = SilKit_FlexrayStartupStateType_Undefined; */ //!< indicates states within the STARTUP mechanism + SilKit_FlexrayWakeupStatusType wakeupStatus; + /* = SilKit_FlexrayWakeupStatusType_Undefined; */ //!< outcome of the execution of the WAKEUP mechanism }; typedef struct SilKit_FlexrayPocStatusEvent SilKit_FlexrayPocStatusEvent; @@ -533,58 +540,69 @@ typedef void SilKit_FlexrayController; /*! Callback type to indicate that a FlexRay message has been received. * Cf. \ref SilKit_FlexrayController_AddFrameHandler; */ -typedef void (SilKitFPTR *SilKit_FlexrayFrameHandler_t)(void* context, SilKit_FlexrayController* controller, const SilKit_FlexrayFrameEvent* message); +typedef void(SilKitFPTR* SilKit_FlexrayFrameHandler_t)(void* context, SilKit_FlexrayController* controller, + const SilKit_FlexrayFrameEvent* message); /*! Callback type to indicate that a FlexrayFrameTransmitEvent has been received. * Cf. \ref SilKit_FlexrayController_AddFrameTransmitHandler; */ -typedef void (SilKitFPTR *SilKit_FlexrayFrameTransmitHandler_t)(void* context, SilKit_FlexrayController* controller, const SilKit_FlexrayFrameTransmitEvent* acknowledge); +typedef void(SilKitFPTR* SilKit_FlexrayFrameTransmitHandler_t)(void* context, SilKit_FlexrayController* controller, + const SilKit_FlexrayFrameTransmitEvent* acknowledge); /*! Callback type to indicate that a wakeup has been received. * Should be answered by a call to Run(). Cf. \ref SilKit_FlexrayController_AddWakeupHandler; */ -typedef void (SilKitFPTR *SilKit_FlexrayWakeupHandler_t)(void* context, SilKit_FlexrayController* controller, const SilKit_FlexrayWakeupEvent* symbol); +typedef void(SilKitFPTR* SilKit_FlexrayWakeupHandler_t)(void* context, SilKit_FlexrayController* controller, + const SilKit_FlexrayWakeupEvent* symbol); /*! Callback type to indicate that the POC status (including state variables, modes and error codes) has changed. * */ -typedef void (SilKitFPTR *SilKit_FlexrayPocStatusHandler_t)(void* context, SilKit_FlexrayController* controller, const SilKit_FlexrayPocStatusEvent* status); +typedef void(SilKitFPTR* SilKit_FlexrayPocStatusHandler_t)(void* context, SilKit_FlexrayController* controller, + const SilKit_FlexrayPocStatusEvent* status); /*! Callback type to indicate that the controller has received a symbol. * Cf. \ref SilKit_FlexrayController_AddSymbolHandler; */ -typedef void (SilKitFPTR *SilKit_FlexraySymbolHandler_t)(void* context, SilKit_FlexrayController* controller, const SilKit_FlexraySymbolEvent* symbol); +typedef void(SilKitFPTR* SilKit_FlexraySymbolHandler_t)(void* context, SilKit_FlexrayController* controller, + const SilKit_FlexraySymbolEvent* symbol); /*! Callback type to indicate that the controller has sent a symbol. * Cf. \ref SilKit_FlexrayController_AddSymbolTransmitHandler; */ -typedef void (SilKitFPTR *SilKit_FlexraySymbolTransmitHandler_t)(void* context, SilKit_FlexrayController* controller, const SilKit_FlexraySymbolTransmitEvent* acknowledge); +typedef void(SilKitFPTR* SilKit_FlexraySymbolTransmitHandler_t)(void* context, SilKit_FlexrayController* controller, + const SilKit_FlexraySymbolTransmitEvent* acknowledge); /*! Callback type to indicate that a new FlexRay cycle did start. * Cf. \ref SilKit_FlexrayController_AddCycleStartHandler; */ -typedef void (SilKitFPTR *SilKit_FlexrayCycleStartHandler_t)(void* context, SilKit_FlexrayController* controller, const SilKit_FlexrayCycleStartEvent* cycleStart); +typedef void(SilKitFPTR* SilKit_FlexrayCycleStartHandler_t)(void* context, SilKit_FlexrayController* controller, + const SilKit_FlexrayCycleStartEvent* cycleStart); /* ! \brief Create a FlexRay controller with the given name. * ! \note The object returned must not be deallocated using free()! */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_Create(SilKit_FlexrayController** outController, - SilKit_Participant* participant, const char* name, - const char* network); + SilKit_Participant* participant, + const char* name, const char* network); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_Create_t)(SilKit_FlexrayController** outController, - SilKit_Participant* participant, const char* name, - const char* network); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_Create_t)(SilKit_FlexrayController** outController, + SilKit_Participant* participant, + const char* name, const char* network); /*! \brief Apply the given controller configuration to the controller.*/ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_Configure(SilKit_FlexrayController* controller, const SilKit_FlexrayControllerConfig* config); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_Configure(SilKit_FlexrayController* controller, + const SilKit_FlexrayControllerConfig* config); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_Configure_t)(SilKit_FlexrayController* controller, const SilKit_FlexrayControllerConfig* config); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_Configure_t)( + SilKit_FlexrayController* controller, const SilKit_FlexrayControllerConfig* config); /*! \brief Reconfigure a TX Buffer that was previously setup with SilKit_FlexrayController_Configure()*/ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_ReconfigureTxBuffer(SilKit_FlexrayController* controller, uint16_t txBufferIdx, const SilKit_FlexrayTxBufferConfig* config); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_ReconfigureTxBuffer( + SilKit_FlexrayController* controller, uint16_t txBufferIdx, const SilKit_FlexrayTxBufferConfig* config); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_ReconfigureTxBuffer_t)(SilKit_FlexrayController* controller, uint16_t txBufferIdx, const SilKit_FlexrayTxBufferConfig* config); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_ReconfigureTxBuffer_t)( + SilKit_FlexrayController* controller, uint16_t txBufferIdx, const SilKit_FlexrayTxBufferConfig* config); /*! \brief Update the content of a previously configured TX buffer. * @@ -595,14 +613,18 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_ReconfigureTxBuf * * \see SilKit_FlexrayController_Configure(const FlexrayControllerConfig&) */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_UpdateTxBuffer(SilKit_FlexrayController* controller, const SilKit_FlexrayTxBufferUpdate* update); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_UpdateTxBuffer( + SilKit_FlexrayController* controller, const SilKit_FlexrayTxBufferUpdate* update); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_UpdateTxBuffer_t)(SilKit_FlexrayController* controller, const SilKit_FlexrayTxBufferUpdate* update); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_UpdateTxBuffer_t)( + SilKit_FlexrayController* controller, const SilKit_FlexrayTxBufferUpdate* update); //! \brief Send the given FlexrayChiCommand. -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_ExecuteCmd(SilKit_FlexrayController* controller, SilKit_FlexrayChiCommand cmd); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_ExecuteCmd(SilKit_FlexrayController* controller, + SilKit_FlexrayChiCommand cmd); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_ExecuteCmd_t)(SilKit_FlexrayController* controller, SilKit_FlexrayChiCommand cmd); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_ExecuteCmd_t)(SilKit_FlexrayController* controller, + SilKit_FlexrayChiCommand cmd); /*! \brief Receive a FlexRay message from the given controller. * @@ -611,13 +633,15 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_ExecuteCmd_t)(Si * \param handler The handler to be called. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddFrameHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayFrameHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddFrameHandler(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexrayFrameHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddFrameHandler_t)(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayFrameHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_AddFrameHandler_t)(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexrayFrameHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_FlexrayFrameHandler_t by SilKit_HandlerId on this controller * @@ -625,10 +649,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddFrameHandler_ * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveFrameHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); + SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveFrameHandler_t)(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_RemoveFrameHandler_t)( + SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); /*! \brief Notification that a FlexRay message has been successfully sent. * @@ -637,26 +661,24 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveFrameHandl * \param handler The handler to be called. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddFrameTransmitHandler(SilKit_FlexrayController* controller, - void* context, - SilKit_FlexrayFrameTransmitHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddFrameTransmitHandler( + SilKit_FlexrayController* controller, void* context, SilKit_FlexrayFrameTransmitHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddFrameTransmitHandler_t)(SilKit_FlexrayController* controller, - void* context, - SilKit_FlexrayFrameTransmitHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_AddFrameTransmitHandler_t)( + SilKit_FlexrayController* controller, void* context, SilKit_FlexrayFrameTransmitHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_FlexrayFrameTransmitHandler_t by SilKit_HandlerId on this controller * * \param controller The FlexRay controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveFrameTransmitHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_FlexrayController_RemoveFrameTransmitHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveFrameTransmitHandler_t)(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_RemoveFrameTransmitHandler_t)( + SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); /*! \brief Notification that a wakeup has been received. * @@ -665,24 +687,25 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveFrameTrans * \param handler The handler to be called. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddWakeupHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayWakeupHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddWakeupHandler(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexrayWakeupHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddWakeupHandler_t)(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayWakeupHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_AddWakeupHandler_t)( + SilKit_FlexrayController* controller, void* context, SilKit_FlexrayWakeupHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_FlexrayWakeupHandler_t by SilKit_HandlerId on this controller * * \param controller The FlexRay controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveWakeupHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_FlexrayController_RemoveWakeupHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveWakeupHandler_t)(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_RemoveWakeupHandler_t)( + SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); /*! \brief Notification that the POC status has changed. * @@ -691,25 +714,24 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveWakeupHand * \param handler The handler to be called. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddPocStatusHandler(SilKit_FlexrayController* controller, - void* context, - SilKit_FlexrayPocStatusHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_FlexrayController_AddPocStatusHandler(SilKit_FlexrayController* controller, void* context, + SilKit_FlexrayPocStatusHandler_t handler, SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddPocStatusHandler_t)(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayPocStatusHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_AddPocStatusHandler_t)( + SilKit_FlexrayController* controller, void* context, SilKit_FlexrayPocStatusHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_FlexrayPocStatusHandler_t by SilKit_HandlerId on this controller * * \param controller The FlexRay controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemovePocStatusHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_FlexrayController_RemovePocStatusHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemovePocStatusHandler_t)(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_RemovePocStatusHandler_t)( + SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); /*! \brief Notification that the controller has received a symbol. * @@ -721,24 +743,25 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemovePocStatusH * \param handler The handler to be called. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddSymbolHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexraySymbolHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddSymbolHandler(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexraySymbolHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddSymbolHandler_t)(SilKit_FlexrayController* controller, void* context, - SilKit_FlexraySymbolHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_AddSymbolHandler_t)( + SilKit_FlexrayController* controller, void* context, SilKit_FlexraySymbolHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_FlexraySymbolHandler_t by SilKit_HandlerId on this controller * * \param controller The FlexRay controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveSymbolHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_FlexrayController_RemoveSymbolHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveSymbolHandler_t)(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_RemoveSymbolHandler_t)( + SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); /*! \brief Notification that the controller has sent a symbol. * @@ -751,25 +774,24 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveSymbolHand * \param handler The handler to be called. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode -SilKitCALL SilKit_FlexrayController_AddSymbolTransmitHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexraySymbolTransmitHandler_t handler, SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddSymbolTransmitHandler( + SilKit_FlexrayController* controller, void* context, SilKit_FlexraySymbolTransmitHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddSymbolTransmitHandler_t)(SilKit_FlexrayController* controller, - void* context, - SilKit_FlexraySymbolTransmitHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_AddSymbolTransmitHandler_t)( + SilKit_FlexrayController* controller, void* context, SilKit_FlexraySymbolTransmitHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_FlexraySymbolTransmitHandler_t by SilKit_HandlerId on this controller * * \param controller The FlexRay controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveSymbolTransmitHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_FlexrayController_RemoveSymbolTransmitHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveSymbolTransmitHandler_t)(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_RemoveSymbolTransmitHandler_t)( + SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); /*! \brief Notification that a new FlexRay cycle did start. * @@ -778,14 +800,13 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveSymbolTran * \param handler The handler to be called. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddCycleStartHandler(SilKit_FlexrayController* controller, - void* context, - SilKit_FlexrayCycleStartHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddCycleStartHandler( + SilKit_FlexrayController* controller, void* context, SilKit_FlexrayCycleStartHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddCycleStartHandler_t)(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayCycleStartHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_AddCycleStartHandler_t)( + SilKit_FlexrayController* controller, void* context, SilKit_FlexrayCycleStartHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_FlexrayCycleStartHandler_t by SilKit_HandlerId on this controller @@ -793,11 +814,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_AddCycleStartHan * \param controller The FlexRay controller for which the callback should be removed. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveCycleStartHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_FlexrayController_RemoveCycleStartHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_FlexrayController_RemoveCycleStartHandler_t)(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_FlexrayController_RemoveCycleStartHandler_t)( + SilKit_FlexrayController* controller, SilKit_HandlerId handlerId); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/InterfaceIdentifiers.h b/SilKit/include/silkit/capi/InterfaceIdentifiers.h old mode 100755 new mode 100644 index 2c4f75754..aeb677bef --- a/SilKit/include/silkit/capi/InterfaceIdentifiers.h +++ b/SilKit/include/silkit/capi/InterfaceIdentifiers.h @@ -45,40 +45,30 @@ typedef struct #define SK_ID_SERVICE_Data 5 #define SK_ID_SERVICE_Rpc 6 #define SK_ID_SERVICE_Participant 7 -#define SK_ID_SERVICE_END 8 //!< sentinel +#define SK_ID_SERVICE_NetworkSimulation 8 +#define SK_ID_SERVICE_END 9 //!< sentinel #define SK_INVALID_DATATYPE_ID 0 #define SK_INVALID_VERSION 0 //! The identifiers service id -#define SK_ID_GET_SERVICE(ID) \ - ((ID >> 40) & 0xFF) +#define SK_ID_GET_SERVICE(ID) ((ID >> 40) & 0xFF) //! The identifiers data type id -#define SK_ID_GET_DATATYPE(ID)\ - ((ID >> 32) & 0xFF) +#define SK_ID_GET_DATATYPE(ID) ((ID >> 32) & 0xFF) //! The identifiers data type version -#define SK_ID_GET_VERSION(ID)\ - ((ID >> 24) & 0xFF) +#define SK_ID_GET_VERSION(ID) ((ID >> 24) & 0xFF) #define SK_ID_MAKE(SERVICE_NAME, DATATYPE_NAME) \ - (uint64_t)(\ - ((uint64_t)83 /*S*/ << 56)\ - | ((uint64_t)75 /*K*/ << 48)\ - | ((uint64_t)(SK_ID_SERVICE_ ## SERVICE_NAME & 0xFF) << 40)\ - | ((uint64_t)(DATATYPE_NAME ## _DATATYPE_ID & 0xff) << 32)\ - | ((uint64_t)(DATATYPE_NAME ## _VERSION & 0xff) << 24)\ - | 0x0) - -#define SK_ID_IS_VALID(ID)\ - (\ - (SK_ID_GET_SERVICE(ID) > SK_ID_SERVICE_START)\ - && (SK_ID_GET_SERVICE(ID) < SK_ID_SERVICE_END)\ - && (SK_ID_GET_DATATYPE(ID) != SK_INVALID_DATATYPE_ID)\ - && (SK_ID_GET_VERSION(ID) != SK_INVALID_VERSION)\ - && ((ID >> 56 & 0xff) == /*S*/ 83)\ - && ((ID >> 48 & 0xff) == /*K*/ 75)\ - ) + (uint64_t)(((uint64_t)83 /*S*/ << 56) | ((uint64_t)75 /*K*/ << 48) \ + | ((uint64_t)(SK_ID_SERVICE_##SERVICE_NAME & 0xFF) << 40) \ + | ((uint64_t)(DATATYPE_NAME##_DATATYPE_ID & 0xff) << 32) \ + | ((uint64_t)(DATATYPE_NAME##_VERSION & 0xff) << 24) | 0x0) + +#define SK_ID_IS_VALID(ID) \ + ((SK_ID_GET_SERVICE(ID) > SK_ID_SERVICE_START) && (SK_ID_GET_SERVICE(ID) < SK_ID_SERVICE_END) \ + && (SK_ID_GET_DATATYPE(ID) != SK_INVALID_DATATYPE_ID) && (SK_ID_GET_VERSION(ID) != SK_INVALID_VERSION) \ + && ((ID >> 56 & 0xff) == /*S*/ 83) && ((ID >> 48 & 0xff) == /*K*/ 75)) //! Helper to access the Interface ID member #define SilKit_Struct_GetHeader(VALUE) ((VALUE).structHeader) @@ -108,14 +98,14 @@ typedef struct #define SilKit_CanErrorStateChangeEvent_VERSION 1 // CAN make versioned IDs -#define SilKit_CanFrame_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanFrame) -#define SilKit_CanFrameTransmitEvent_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanFrameTransmitEvent) -#define SilKit_CanFrameEvent_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanFrameEvent) -#define SilKit_CanStateChangeEvent_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanStateChangeEvent) -#define SilKit_CanErrorStateChangeEvent_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanErrorStateChangeEvent) +#define SilKit_CanFrame_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanFrame) +#define SilKit_CanFrameTransmitEvent_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanFrameTransmitEvent) +#define SilKit_CanFrameEvent_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanFrameEvent) +#define SilKit_CanStateChangeEvent_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanStateChangeEvent) +#define SilKit_CanErrorStateChangeEvent_STRUCT_VERSION SK_ID_MAKE(Can, SilKit_CanErrorStateChangeEvent) // Ethernet -// +// // Ethernet data type IDs #define SilKit_EthernetFrameEvent_DATATYPE_ID 1 #define SilKit_EthernetFrameTransmitEvent_DATATYPE_ID 2 @@ -130,11 +120,11 @@ typedef struct #define SilKit_EthernetBitrateChangeEvent_VERSION 1 #define SilKit_EthernetFrame_VERSION 1 -#define SilKit_EthernetFrameEvent_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetFrameEvent) -#define SilKit_EthernetFrameTransmitEvent_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetFrameTransmitEvent) -#define SilKit_EthernetStateChangeEvent_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetStateChangeEvent) -#define SilKit_EthernetBitrateChangeEvent_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetBitrateChangeEvent) -#define SilKit_EthernetFrame_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetFrame) +#define SilKit_EthernetFrameEvent_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetFrameEvent) +#define SilKit_EthernetFrameTransmitEvent_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetFrameTransmitEvent) +#define SilKit_EthernetStateChangeEvent_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetStateChangeEvent) +#define SilKit_EthernetBitrateChangeEvent_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetBitrateChangeEvent) +#define SilKit_EthernetFrame_STRUCT_VERSION SK_ID_MAKE(Ethernet, SilKit_EthernetFrame) // FlexRay // FlexRay data type IDs @@ -172,21 +162,21 @@ typedef struct #define SilKit_FlexrayTxBufferUpdate_VERSION 1 // Flexray make versioned IDs -#define SilKit_FlexrayFrameEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayFrameEvent) -#define SilKit_FlexrayFrameTransmitEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayFrameTransmitEvent) -#define SilKit_FlexraySymbolEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexraySymbolEvent) -#define SilKit_FlexraySymbolTransmitEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexraySymbolTransmitEvent) -#define SilKit_FlexrayCycleStartEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayCycleStartEvent) -#define SilKit_FlexrayPocStatusEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayPocStatusEvent) -#define SilKit_FlexrayWakeupEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayWakeupEvent) -#define SilKit_FlexrayControllerConfig_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayControllerConfig) -#define SilKit_FlexrayClusterParameters_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayClusterParameters) -#define SilKit_FlexrayNodeParameters_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayNodeParameters) -#define SilKit_FlexrayHostCommand_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayHostCommand) -#define SilKit_FlexrayHeader_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayHeader) -#define SilKit_FlexrayFrame_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayFrame) -#define SilKit_FlexrayTxBufferConfig_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayTxBufferConfig) -#define SilKit_FlexrayTxBufferUpdate_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayTxBufferUpdate) +#define SilKit_FlexrayFrameEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayFrameEvent) +#define SilKit_FlexrayFrameTransmitEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayFrameTransmitEvent) +#define SilKit_FlexraySymbolEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexraySymbolEvent) +#define SilKit_FlexraySymbolTransmitEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexraySymbolTransmitEvent) +#define SilKit_FlexrayCycleStartEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayCycleStartEvent) +#define SilKit_FlexrayPocStatusEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayPocStatusEvent) +#define SilKit_FlexrayWakeupEvent_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayWakeupEvent) +#define SilKit_FlexrayControllerConfig_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayControllerConfig) +#define SilKit_FlexrayClusterParameters_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayClusterParameters) +#define SilKit_FlexrayNodeParameters_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayNodeParameters) +#define SilKit_FlexrayHostCommand_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayHostCommand) +#define SilKit_FlexrayHeader_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayHeader) +#define SilKit_FlexrayFrame_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayFrame) +#define SilKit_FlexrayTxBufferConfig_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayTxBufferConfig) +#define SilKit_FlexrayTxBufferUpdate_STRUCT_VERSION SK_ID_MAKE(Flexray, SilKit_FlexrayTxBufferUpdate) // LIN @@ -201,6 +191,7 @@ typedef struct #define SilKit_Experimental_LinSlaveConfiguration_DATATYPE_ID 8 #define SilKit_Experimental_LinControllerDynamicConfig_DATATYPE_ID 9 #define SilKit_Experimental_LinFrameHeaderEvent_DATATYPE_ID 10 +#define SilKit_LinSendFrameHeaderRequest_DATATYPE_ID 11 // LIN data type versions #define SilKit_LinFrame_VERSION 1 @@ -213,18 +204,23 @@ typedef struct #define SilKit_Experimental_LinSlaveConfiguration_VERSION 1 #define SilKit_Experimental_LinControllerDynamicConfig_VERSION 1 #define SilKit_Experimental_LinFrameHeaderEvent_VERSION 1 +#define SilKit_LinSendFrameHeaderRequest_VERSION 1 // LIN make versioned IDs -#define SilKit_LinFrame_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinFrame) -#define SilKit_LinFrameResponse_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinFrameResponse) -#define SilKit_LinControllerConfig_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinControllerConfig) -#define SilKit_LinFrameStatusEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinFrameStatusEvent) -#define SilKit_LinGoToSleepEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinGoToSleepEvent) -#define SilKit_LinWakeupEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinWakeupEvent) -#define SilKit_Experimental_LinSlaveConfigurationEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_Experimental_LinSlaveConfigurationEvent) -#define SilKit_Experimental_LinSlaveConfiguration_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_Experimental_LinSlaveConfiguration) -#define SilKit_Experimental_LinControllerDynamicConfig_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_Experimental_LinControllerDynamicConfig) -#define SilKit_Experimental_LinFrameHeaderEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_Experimental_LinFrameHeaderEvent) +#define SilKit_LinFrame_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinFrame) +#define SilKit_LinFrameResponse_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinFrameResponse) +#define SilKit_LinControllerConfig_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinControllerConfig) +#define SilKit_LinFrameStatusEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinFrameStatusEvent) +#define SilKit_LinGoToSleepEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinGoToSleepEvent) +#define SilKit_LinWakeupEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinWakeupEvent) +#define SilKit_Experimental_LinSlaveConfigurationEvent_STRUCT_VERSION \ + SK_ID_MAKE(Lin, SilKit_Experimental_LinSlaveConfigurationEvent) +#define SilKit_Experimental_LinSlaveConfiguration_STRUCT_VERSION \ + SK_ID_MAKE(Lin, SilKit_Experimental_LinSlaveConfiguration) +#define SilKit_Experimental_LinControllerDynamicConfig_STRUCT_VERSION \ + SK_ID_MAKE(Lin, SilKit_Experimental_LinControllerDynamicConfig) +#define SilKit_Experimental_LinFrameHeaderEvent_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_Experimental_LinFrameHeaderEvent) +#define SilKit_LinSendFrameHeaderRequest_STRUCT_VERSION SK_ID_MAKE(Lin, SilKit_LinSendFrameHeaderRequest) // Data // Data data type IDs @@ -236,8 +232,8 @@ typedef struct #define SilKit_DataSpec_VERSION 1 // Data public API IDs -#define SilKit_DataMessageEvent_STRUCT_VERSION SK_ID_MAKE(Data, SilKit_DataMessageEvent) -#define SilKit_DataSpec_STRUCT_VERSION SK_ID_MAKE(Data, SilKit_DataSpec) +#define SilKit_DataMessageEvent_STRUCT_VERSION SK_ID_MAKE(Data, SilKit_DataMessageEvent) +#define SilKit_DataSpec_STRUCT_VERSION SK_ID_MAKE(Data, SilKit_DataSpec) // Rpc // Rpc data type IDs @@ -251,9 +247,9 @@ typedef struct #define SilKit_RpcSpec_VERSION 1 // Rpc public API IDs -#define SilKit_RpcCallEvent_STRUCT_VERSION SK_ID_MAKE(Rpc, SilKit_RpcCallEvent) -#define SilKit_RpcCallResultEvent_STRUCT_VERSION SK_ID_MAKE(Rpc, SilKit_RpcCallResultEvent) -#define SilKit_RpcSpec_STRUCT_VERSION SK_ID_MAKE(Rpc, SilKit_RpcSpec) +#define SilKit_RpcCallEvent_STRUCT_VERSION SK_ID_MAKE(Rpc, SilKit_RpcCallEvent) +#define SilKit_RpcCallResultEvent_STRUCT_VERSION SK_ID_MAKE(Rpc, SilKit_RpcCallResultEvent) +#define SilKit_RpcSpec_STRUCT_VERSION SK_ID_MAKE(Rpc, SilKit_RpcSpec) // Participant // Participant data type IDs @@ -269,9 +265,102 @@ typedef struct #define SilKit_ParticipantConnectionInformation_VERSION 1 // Participant public API IDs -#define SilKit_ParticipantStatus_STRUCT_VERSION SK_ID_MAKE(Participant, SilKit_ParticipantStatus) -#define SilKit_LifecycleConfiguration_STRUCT_VERSION SK_ID_MAKE(Participant, SilKit_LifecycleConfiguration) -#define SilKit_WorkflowConfiguration_STRUCT_VERSION SK_ID_MAKE(Participant, SilKit_WorkflowConfiguration) -#define SilKit_ParticipantConnectionInformation_STRUCT_VERSION SK_ID_MAKE(Participant, SilKit_ParticipantConnectionInformation) +#define SilKit_ParticipantStatus_STRUCT_VERSION SK_ID_MAKE(Participant, SilKit_ParticipantStatus) +#define SilKit_LifecycleConfiguration_STRUCT_VERSION SK_ID_MAKE(Participant, SilKit_LifecycleConfiguration) +#define SilKit_WorkflowConfiguration_STRUCT_VERSION SK_ID_MAKE(Participant, SilKit_WorkflowConfiguration) +#define SilKit_ParticipantConnectionInformation_STRUCT_VERSION \ + SK_ID_MAKE(Participant, SilKit_ParticipantConnectionInformation) + +// NetworkSimulator + +// NetworkSimulator data type IDs +#define SilKit_Experimental_EventReceivers_DATATYPE_ID 1 +#define SilKit_Experimental_SimulatedNetworkFunctions_DATATYPE_ID 2 +#define SilKit_Experimental_SimulatedCanControllerFunctions_DATATYPE_ID 3 +#define SilKit_Experimental_SimulatedFlexRayControllerFunctions_DATATYPE_ID 4 +#define SilKit_Experimental_SimulatedEthernetControllerFunctions_DATATYPE_ID 5 +#define SilKit_Experimental_SimulatedLinControllerFunctions_DATATYPE_ID 6 +#define SilKit_Experimental_NetSim_CanConfigureBaudrate_DATATYPE_ID 7 +#define SilKit_Experimental_NetSim_CanControllerMode_DATATYPE_ID 8 +#define SilKit_Experimental_NetSim_CanFrameRequest_DATATYPE_ID 9 +#define SilKit_Experimental_NetSim_FlexrayControllerConfig_DATATYPE_ID 10 +#define SilKit_Experimental_NetSim_FlexrayHostCommand_DATATYPE_ID 11 +#define SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate_DATATYPE_ID 12 +#define SilKit_Experimental_NetSim_FlexrayTxBufferUpdate_DATATYPE_ID 13 +#define SilKit_Experimental_NetSim_EthernetFrameRequest_DATATYPE_ID 14 +#define SilKit_Experimental_NetSim_EthernetControllerMode_DATATYPE_ID 15 +#define SilKit_Experimental_NetSim_LinFrameRequest_DATATYPE_ID 16 +#define SilKit_Experimental_NetSim_LinFrameHeaderRequest_DATATYPE_ID 17 +#define SilKit_Experimental_NetSim_LinWakeupPulse_DATATYPE_ID 18 +#define SilKit_Experimental_NetSim_LinControllerConfig_DATATYPE_ID 19 +#define SilKit_Experimental_NetSim_LinFrameResponseUpdate_DATATYPE_ID 20 +#define SilKit_Experimental_NetSim_LinControllerStatusUpdate_DATATYPE_ID 21 + +// NetworkSimulator data type Versions +#define SilKit_Experimental_EventReceivers_VERSION 1 +#define SilKit_Experimental_SimulatedNetworkFunctions_VERSION 1 +#define SilKit_Experimental_SimulatedCanControllerFunctions_VERSION 1 +#define SilKit_Experimental_SimulatedFlexRayControllerFunctions_VERSION 1 +#define SilKit_Experimental_SimulatedEthernetControllerFunctions_VERSION 1 +#define SilKit_Experimental_SimulatedLinControllerFunctions_VERSION 1 +#define SilKit_Experimental_NetSim_CanConfigureBaudrate_VERSION 1 +#define SilKit_Experimental_NetSim_CanControllerMode_VERSION 1 +#define SilKit_Experimental_NetSim_CanFrameRequest_VERSION 1 +#define SilKit_Experimental_NetSim_FlexrayControllerConfig_VERSION 1 +#define SilKit_Experimental_NetSim_FlexrayHostCommand_VERSION 1 +#define SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate_VERSION 1 +#define SilKit_Experimental_NetSim_FlexrayTxBufferUpdate_VERSION 1 +#define SilKit_Experimental_NetSim_EthernetFrameRequest_VERSION 1 +#define SilKit_Experimental_NetSim_EthernetControllerMode_VERSION 1 +#define SilKit_Experimental_NetSim_LinFrameRequest_VERSION 1 +#define SilKit_Experimental_NetSim_LinFrameHeaderRequest_VERSION 1 +#define SilKit_Experimental_NetSim_LinWakeupPulse_VERSION 1 +#define SilKit_Experimental_NetSim_LinControllerConfig_VERSION 1 +#define SilKit_Experimental_NetSim_LinFrameResponseUpdate_VERSION 1 +#define SilKit_Experimental_NetSim_LinControllerStatusUpdate_VERSION 1 + +// NetworkSimulator public API IDs +#define SilKit_Experimental_EventReceivers_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_EventReceivers) +#define SilKit_Experimental_SimulatedNetworkFunctions_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_SimulatedNetworkFunctions) +#define SilKit_Experimental_SimulatedCanControllerFunctions_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_SimulatedCanControllerFunctions) +#define SilKit_Experimental_SimulatedFlexRayControllerFunctions_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_SimulatedFlexRayControllerFunctions) +#define SilKit_Experimental_SimulatedEthernetControllerFunctions_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_SimulatedEthernetControllerFunctions) +#define SilKit_Experimental_SimulatedLinControllerFunctions_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_SimulatedLinControllerFunctions) +#define SilKit_Experimental_NetSim_CanConfigureBaudrate_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_CanConfigureBaudrate) +#define SilKit_Experimental_NetSim_CanControllerMode_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_CanControllerMode) +#define SilKit_Experimental_NetSim_CanFrameRequest_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_CanFrameRequest) +#define SilKit_Experimental_NetSim_FlexrayControllerConfig_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_FlexrayControllerConfig) +#define SilKit_Experimental_NetSim_FlexrayHostCommand_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_FlexrayHostCommand) +#define SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate) +#define SilKit_Experimental_NetSim_FlexrayTxBufferUpdate_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_FlexrayTxBufferUpdate) +#define SilKit_Experimental_NetSim_EthernetFrameRequest_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_EthernetFrameRequest) +#define SilKit_Experimental_NetSim_EthernetControllerMode_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_EthernetControllerMode) +#define SilKit_Experimental_NetSim_LinFrameRequest_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_LinFrameRequest) +#define SilKit_Experimental_NetSim_LinFrameHeaderRequest_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_LinFrameHeaderRequest) +#define SilKit_Experimental_NetSim_LinWakeupPulse_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_LinWakeupPulse) +#define SilKit_Experimental_NetSim_LinControllerConfig_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_LinControllerConfig) +#define SilKit_Experimental_NetSim_LinFrameResponseUpdate_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_LinFrameResponseUpdate) +#define SilKit_Experimental_NetSim_LinControllerStatusUpdate_STRUCT_VERSION \ + SK_ID_MAKE(NetworkSimulation, SilKit_Experimental_NetSim_LinControllerStatusUpdate) SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/Lin.h b/SilKit/include/silkit/capi/Lin.h old mode 100755 new mode 100644 index 16ffdc73b..6956db4be --- a/SilKit/include/silkit/capi/Lin.h +++ b/SilKit/include/silkit/capi/Lin.h @@ -92,7 +92,8 @@ typedef uint8_t SilKit_LinId; * This type is used to specify the Checksum model to be used for the LIN \ref SilKit_LinFrame. */ typedef uint8_t SilKit_LinChecksumModel; -#define SilKit_LinChecksumModel_Unknown ((SilKit_LinChecksumModel)0) //!< Unknown checksum model. If configured with this value, the checksum model of the first reception will be used. +#define SilKit_LinChecksumModel_Unknown \ + ((SilKit_LinChecksumModel)0) //!< Unknown checksum model. If configured with this value, the checksum model of the first reception will be used. #define SilKit_LinChecksumModel_Enhanced ((SilKit_LinChecksumModel)1) //!< Enhanced checksum model #define SilKit_LinChecksumModel_Classic ((SilKit_LinChecksumModel)2) //!< Classic checksum model @@ -127,19 +128,19 @@ typedef uint8_t SilKit_LinFrameResponseType; typedef uint8_t SilKit_LinFrameStatus; /*! (currently not in use) */ -#define SilKit_LinFrameStatus_NOT_OK ((SilKit_LinFrameStatus)0) +#define SilKit_LinFrameStatus_NOT_OK ((SilKit_LinFrameStatus)0) /*! The controller successfully transmitted a frame response. */ -#define SilKit_LinFrameStatus_LIN_TX_OK ((SilKit_LinFrameStatus)1) +#define SilKit_LinFrameStatus_LIN_TX_OK ((SilKit_LinFrameStatus)1) /*! (currently not in use) */ -#define SilKit_LinFrameStatus_LIN_TX_BUSY ((SilKit_LinFrameStatus)2) +#define SilKit_LinFrameStatus_LIN_TX_BUSY ((SilKit_LinFrameStatus)2) /*! (currently not in use) */ #define SilKit_LinFrameStatus_LIN_TX_HEADER_ERROR ((SilKit_LinFrameStatus)3) /*! (currently not in use) */ -#define SilKit_LinFrameStatus_LIN_TX_ERROR ((SilKit_LinFrameStatus)4) +#define SilKit_LinFrameStatus_LIN_TX_ERROR ((SilKit_LinFrameStatus)4) /*! The controller received a correct frame response. */ -#define SilKit_LinFrameStatus_LIN_RX_OK ((SilKit_LinFrameStatus)5) +#define SilKit_LinFrameStatus_LIN_RX_OK ((SilKit_LinFrameStatus)5) /*! (currently not in use) */ -#define SilKit_LinFrameStatus_LIN_RX_BUSY ((SilKit_LinFrameStatus)6) +#define SilKit_LinFrameStatus_LIN_RX_BUSY ((SilKit_LinFrameStatus)6) /*! The reception of a response failed. * * Indicates a mismatch in expected and received data length or a checksum @@ -147,9 +148,9 @@ typedef uint8_t SilKit_LinFrameStatus; * transmit the same frame or when the sender and receiver use different * checksum models. */ -#define SilKit_LinFrameStatus_LIN_RX_ERROR ((SilKit_LinFrameStatus)7) +#define SilKit_LinFrameStatus_LIN_RX_ERROR ((SilKit_LinFrameStatus)7) /*! No LIN controller did provide a response to the frame header. */ -#define SilKit_LinFrameStatus_LIN_RX_NO_RESPONSE ((SilKit_LinFrameStatus)8) +#define SilKit_LinFrameStatus_LIN_RX_NO_RESPONSE ((SilKit_LinFrameStatus)8) /*! \brief The data length of a LIN \ref SilKit_LinFrame in bytes * @@ -170,11 +171,11 @@ const SilKit_LinDataLength SilKit_LinDataLengthUnknown = 255u; */ struct SilKit_LinFrame { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - SilKit_LinId id; //!< LIN Identifier - SilKit_LinChecksumModel checksumModel; //!< Checksum Model - SilKit_LinDataLength dataLength; //!< Data length - uint8_t data[8]; //!< The actual payload + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_LinId id; //!< LIN Identifier + SilKit_LinChecksumModel checksumModel; //!< Checksum Model + SilKit_LinDataLength dataLength; //!< Data length + uint8_t data[8]; //!< The actual payload }; typedef struct SilKit_LinFrame SilKit_LinFrame; @@ -244,7 +245,7 @@ struct SilKit_LinControllerConfig size_t numFrameResponses; /*! LinFrameResponse configuration. */ - SilKit_LinFrameResponse* frameResponses; + SilKit_LinFrameResponse* frameResponses; }; typedef struct SilKit_LinControllerConfig SilKit_LinControllerConfig; @@ -277,12 +278,20 @@ typedef struct SilKit_Experimental_LinSlaveConfiguration SilKit_Experimental_Lin /*! \brief A LIN frame header event delivered in the \ref SilKit_Experimental_LinFrameHeaderHandler_t. */ struct SilKit_Experimental_LinFrameHeaderEvent { - SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained - SilKit_NanosecondsTime timestamp; //!< Time of the event. - SilKit_LinId id; //!< LIN Identifier + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_NanosecondsTime timestamp; //!< Time of the event. + SilKit_LinId id; //!< LIN Identifier }; typedef struct SilKit_Experimental_LinFrameHeaderEvent SilKit_Experimental_LinFrameHeaderEvent; +struct SilKit_LinSendFrameHeaderRequest +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_NanosecondsTime timestamp; //!< Time of the event. + SilKit_LinId id; //!< LIN Identifier +}; +typedef struct SilKit_LinSendFrameHeaderRequest SilKit_LinSendFrameHeaderRequest; + /*! * The LIN controller can assume the role of a LIN master or a LIN * slave. It provides two kinds of interfaces to perform data @@ -310,33 +319,34 @@ typedef struct SilKit_LinController SilKit_LinController; * \param controller The LIN controller that received the acknowledge. * \param frameStatusEvent The event containing a timestamp, the corresponding frame and the new status. */ -typedef void (SilKitFPTR *SilKit_LinFrameStatusHandler_t)(void* context, SilKit_LinController* controller, - const SilKit_LinFrameStatusEvent* frameStatusEvent); +typedef void(SilKitFPTR* SilKit_LinFrameStatusHandler_t)(void* context, SilKit_LinController* controller, + const SilKit_LinFrameStatusEvent* frameStatusEvent); /*! Callback type to indicate that a go-to-sleep frame has been received. * Cf., \ref SilKit_LinController_AddGoToSleepHandler(); */ -typedef void (SilKitFPTR *SilKit_LinGoToSleepHandler_t)(void* context, SilKit_LinController* controller, - const SilKit_LinGoToSleepEvent* goToSleepEvent); +typedef void(SilKitFPTR* SilKit_LinGoToSleepHandler_t)(void* context, SilKit_LinController* controller, + const SilKit_LinGoToSleepEvent* goToSleepEvent); /*! Callback type to indicate that a wakeup pulse has been received. * Cf., \ref SilKit_LinController_AddWakeupHandler; */ -typedef void (SilKitFPTR *SilKit_LinWakeupHandler_t)(void* context, SilKit_LinController* controller, - const SilKit_LinWakeupEvent* wakeUpEvent); +typedef void(SilKitFPTR* SilKit_LinWakeupHandler_t)(void* context, SilKit_LinController* controller, + const SilKit_LinWakeupEvent* wakeUpEvent); /*! Callback type to indicate that a LIN Slave configuration has been received. * Cf., \ref SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler; */ -typedef void (SilKitFPTR *SilKit_Experimental_LinSlaveConfigurationHandler_t)(void* context, SilKit_LinController* controller, - const SilKit_Experimental_LinSlaveConfigurationEvent* slaveConfigurationEvent); +typedef void(SilKitFPTR* SilKit_Experimental_LinSlaveConfigurationHandler_t)( + void* context, SilKit_LinController* controller, + const SilKit_Experimental_LinSlaveConfigurationEvent* slaveConfigurationEvent); /*! Callback type to indicate the reception of a LIN frame header. * \param context The context provided by the user on registration. * \param controller The LIN controller that received the acknowledge. * \param frameHeaderEvent The event containing information about the frame header. */ -typedef void (SilKitFPTR* SilKit_Experimental_LinFrameHeaderHandler_t)( +typedef void(SilKitFPTR* SilKit_Experimental_LinFrameHeaderHandler_t)( void* context, SilKit_LinController* controller, const SilKit_Experimental_LinFrameHeaderEvent* frameHeaderEvent); @@ -353,17 +363,13 @@ typedef void (SilKitFPTR* SilKit_Experimental_LinFrameHeaderHandler_t)( * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_Create( - SilKit_LinController** outLinController, - SilKit_Participant *participant, - const char* name, - const char* network); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_Create(SilKit_LinController** outLinController, + SilKit_Participant* participant, const char* name, + const char* network); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_Create_t)( - SilKit_LinController** outLinController, - SilKit_Participant* participant, - const char* name, - const char* network); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_Create_t)(SilKit_LinController** outLinController, + SilKit_Participant* participant, const char* name, + const char* network); /*! \brief Initialize the LIN controller defining its role and RX/TX configuration. * @@ -382,8 +388,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_Create_t)( * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_Init(SilKit_LinController* controller, const SilKit_LinControllerConfig* config); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_Init_t)(SilKit_LinController* controller, const SilKit_LinControllerConfig* config); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_Init(SilKit_LinController* controller, + const SilKit_LinControllerConfig* config); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_Init_t)(SilKit_LinController* controller, + const SilKit_LinControllerConfig* config); /*! \brief Initialize the LIN controller in dynamic response mode. @@ -399,7 +407,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_Init_t)(SilKit_LinCo */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_InitDynamic( SilKit_LinController* controller, const SilKit_Experimental_LinControllerDynamicConfig* config); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_InitDynamic_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_LinController_InitDynamic_t)( SilKit_LinController* controller, const SilKit_Experimental_LinControllerDynamicConfig* config); /*! \brief Set a RX/TX configuration during operation. @@ -423,9 +431,9 @@ typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_SetFrameResponse_t)(S * \throws SilKit::StateError if the LIN controller was not initialized into dynamic response mode using \ref SilKit_Experimental_LinController_InitDynamic(). * */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_SendDynamicResponse( - SilKit_LinController* controller, const SilKit_LinFrame* frame); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_SendDynamicResponse_t)( +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_Experimental_LinController_SendDynamicResponse(SilKit_LinController* controller, const SilKit_LinFrame* frame); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_LinController_SendDynamicResponse_t)( SilKit_LinController* controller, const SilKit_LinFrame* frame); /*! \brief Get the current status of the LIN Controller, i.e., Operational or Sleep. @@ -435,8 +443,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_SendDyn * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_Status(SilKit_LinController* controller, SilKit_LinControllerStatus* outStatus); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_Status_t)(SilKit_LinController* controller, SilKit_LinControllerStatus* outStatus); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_Status(SilKit_LinController* controller, + SilKit_LinControllerStatus* outStatus); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_Status_t)(SilKit_LinController* controller, + SilKit_LinControllerStatus* outStatus); /*! \brief Initiate a LIN data transfer of a given LinFrameResponseType (AUTOSAR LIN master interface) * @@ -455,10 +465,12 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_Status_t)(SilKit_Lin * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_SendFrame(SilKit_LinController* controller, const SilKit_LinFrame* frame, - SilKit_LinFrameResponseType responseType); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_SendFrame_t)(SilKit_LinController* controller, const SilKit_LinFrame* frame, - SilKit_LinFrameResponseType responseType); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_SendFrame(SilKit_LinController* controller, + const SilKit_LinFrame* frame, + SilKit_LinFrameResponseType responseType); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_SendFrame_t)(SilKit_LinController* controller, + const SilKit_LinFrame* frame, + SilKit_LinFrameResponseType responseType); /*! \brief Initiate a LIN data transfer by sending a LIN header (AUTOSAR LIN master interface) @@ -469,8 +481,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_SendFrame_t)(SilKit_ * * \throws SilKit::StateError if the LIN Controller is not initialized or not a master node. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_SendFrameHeader(SilKit_LinController* controller, SilKit_LinId linId); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_SendFrameHeader_t)(SilKit_LinController* controller, SilKit_LinId linId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_SendFrameHeader(SilKit_LinController* controller, + SilKit_LinId linId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_SendFrameHeader_t)(SilKit_LinController* controller, + SilKit_LinId linId); /*! Update the response data. The LIN controller needs to be configured with TxUnconditional on this ID. * @@ -481,9 +495,9 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_SendFrameHeader_t)(Si * \return \ref SilKit_ReturnCode */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_UpdateTxBuffer(SilKit_LinController* controller, - const SilKit_LinFrame* frame); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_UpdateTxBuffer_t)(SilKit_LinController* controller, - const SilKit_LinFrame* frame); + const SilKit_LinFrame* frame); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_UpdateTxBuffer_t)(SilKit_LinController* controller, + const SilKit_LinFrame* frame); /*! \brief Transmit a go-to-sleep-command and set SilKit_LinControllerStatus_Sleep and enable wake-up * @@ -494,7 +508,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_UpdateTxBuffer_t)(Si * \return SilKit_ReturnCode_SUCCESS or SilKit_ReturnCode_WRONGSTATE if issued with wrong \ref SilKit_LinControllerMode */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_GoToSleep(SilKit_LinController* controller); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_GoToSleep_t)(SilKit_LinController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_GoToSleep_t)(SilKit_LinController* controller); /*! \brief Set SilKit_LinControllerStatus_Sleep without sending a go-to-sleep command. * @@ -505,7 +519,7 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_GoToSleep_t)(SilKit_L * \return SilKit_ReturnCode_SUCCESS or SilKit_ReturnCode_WRONGSTATE if issued with wrong \ref SilKit_LinControllerMode */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_GoToSleepInternal(SilKit_LinController* controller); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_GoToSleepInternal_t)(SilKit_LinController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_GoToSleepInternal_t)(SilKit_LinController* controller); /*! \brief Generate a wake up pulse and set SilKit_LinControllerStatus_Operational. * @@ -516,7 +530,7 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_GoToSleepInternal_t)( * \return SilKit_ReturnCode_SUCCESS or SilKit_ReturnCode_WRONGSTATE if issued with wrong \ref SilKit_LinControllerMode */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_Wakeup(SilKit_LinController* controller); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_Wakeup_t)(SilKit_LinController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_Wakeup_t)(SilKit_LinController* controller); /*! Set SilKit_LinControllerStatus_Operational without generating a wake up pulse. * @@ -527,7 +541,7 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_Wakeup_t)(SilKit_LinC * \return SilKit_ReturnCode_SUCCESS or SilKit_ReturnCode_WRONGSTATE if issued with wrong \ref SilKit_LinControllerMode */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_WakeupInternal(SilKit_LinController* controller); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_WakeupInternal_t)(SilKit_LinController* controller); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_WakeupInternal_t)(SilKit_LinController* controller); /*! \brief Get the aggregated configuration of all LIN slaves in the network. * @@ -540,7 +554,7 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_WakeupInternal_t)(Sil */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_GetSlaveConfiguration( SilKit_LinController* controller, SilKit_Experimental_LinSlaveConfiguration* outLinSlaveConfiguration); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_GetSlaveConfiguration_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_LinController_GetSlaveConfiguration_t)( SilKit_LinController* controller, SilKit_Experimental_LinSlaveConfiguration* outLinSlaveConfiguration); /*! \brief Reports the SilKit_LinFrameStatus of a SilKit_LinFrame and provides the transmitted frame. @@ -556,13 +570,13 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_GetSlav * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_AddFrameStatusHandler(SilKit_LinController* controller, void* context, - SilKit_LinFrameStatusHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_LinController_AddFrameStatusHandler(SilKit_LinController* controller, void* context, + SilKit_LinFrameStatusHandler_t handler, SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_AddFrameStatusHandler_t)(SilKit_LinController* controller, void* context, - SilKit_LinFrameStatusHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_AddFrameStatusHandler_t)( + SilKit_LinController* controller, void* context, SilKit_LinFrameStatusHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_LinFrameStatusHandler_t by SilKit_HandlerId on this controller * @@ -572,10 +586,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_AddFrameStatusHandle * \return \ref SilKit_ReturnCode */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveFrameStatusHandler(SilKit_LinController* controller, - SilKit_HandlerId handlerId); + SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_RemoveFrameStatusHandler_t)(SilKit_LinController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_RemoveFrameStatusHandler_t)(SilKit_LinController* controller, + SilKit_HandlerId handlerId); /*! \brief The GoToSleepHandler is called whenever a go-to-sleep frame * was received. @@ -598,13 +612,15 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_RemoveFrameStatusHan * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_AddGoToSleepHandler(SilKit_LinController* controller, void* context, - SilKit_LinGoToSleepHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_AddGoToSleepHandler(SilKit_LinController* controller, + void* context, + SilKit_LinGoToSleepHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_AddGoToSleepHandler_t)(SilKit_LinController* controller, void* context, - SilKit_LinGoToSleepHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_AddGoToSleepHandler_t)(SilKit_LinController* controller, + void* context, + SilKit_LinGoToSleepHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_LinGoToSleepHandler_t by SilKit_HandlerId on this controller * @@ -614,10 +630,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_AddGoToSleepHandler_ * \return \ref SilKit_ReturnCode */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveGoToSleepHandler(SilKit_LinController* controller, - SilKit_HandlerId handlerId); + SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_RemoveGoToSleepHandler_t)(SilKit_LinController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_RemoveGoToSleepHandler_t)(SilKit_LinController* controller, + SilKit_HandlerId handlerId); /*! \brief The WakeupHandler is called whenever a wake up pulse is received * @@ -632,13 +648,15 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_RemoveGoToSleepHandl * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_AddWakeupHandler(SilKit_LinController* controller, void* context, - SilKit_LinWakeupHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_AddWakeupHandler(SilKit_LinController* controller, + void* context, + SilKit_LinWakeupHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_AddWakeupHandler_t)(SilKit_LinController* controller, void* context, - SilKit_LinWakeupHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_AddWakeupHandler_t)(SilKit_LinController* controller, + void* context, + SilKit_LinWakeupHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_LinWakeupHandler_t by SilKit_HandlerId on this controller * @@ -646,9 +664,10 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_LinController_AddWakeupHandler_t)(S * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveWakeupHandler(SilKit_LinController* controller, - SilKit_HandlerId handlerId); + SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_RemoveWakeupHandler_t)(SilKit_LinController* controller, SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LinController_RemoveWakeupHandler_t)(SilKit_LinController* controller, + SilKit_HandlerId handlerId); /*! \brief The LinSlaveConfigurationHandler is called whenever a remote LIN Slave is configured via SilKit_LinController_Init @@ -666,13 +685,13 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LinController_RemoveWakeupHandler_ * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler(SilKit_LinController* controller, void* context, - SilKit_Experimental_LinSlaveConfigurationHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler( + SilKit_LinController* controller, void* context, SilKit_Experimental_LinSlaveConfigurationHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler_t)(SilKit_LinController* controller, void* context, - SilKit_Experimental_LinSlaveConfigurationHandler_t handler, - SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler_t)( + SilKit_LinController* controller, void* context, SilKit_Experimental_LinSlaveConfigurationHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_Experimental_LinSlaveConfigurationHandler_t by SilKit_HandlerId on this controller * @@ -681,11 +700,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_AddLinS * * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler(SilKit_LinController* controller, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler( + SilKit_LinController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler_t)(SilKit_LinController* controller, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler_t)( + SilKit_LinController* controller, SilKit_HandlerId handlerId); /*! \brief The LinFrameHeaderHandler is called whenever the master sends a LIN header. @@ -703,14 +722,14 @@ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_AddFram SilKit_LinController* controller, void* context, SilKit_Experimental_LinFrameHeaderHandler_t handler, SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_AddFrameHeaderHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_LinController_AddFrameHeaderHandler_t)( SilKit_LinController* controller, void* context, SilKit_Experimental_LinFrameHeaderHandler_t handler, SilKit_HandlerId* outHandlerId); SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_RemoveFrameHeaderHandler( SilKit_LinController* controller, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_LinController_RemoveFrameHeaderHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_LinController_RemoveFrameHeaderHandler_t)( SilKit_LinController* controller, SilKit_HandlerId handlerId); diff --git a/SilKit/include/silkit/capi/Logger.h b/SilKit/include/silkit/capi/Logger.h index ff644165a..b6e9f67e2 100644 --- a/SilKit/include/silkit/capi/Logger.h +++ b/SilKit/include/silkit/capi/Logger.h @@ -33,13 +33,13 @@ SILKIT_BEGIN_DECLS /*! \brief Information level of log messages */ typedef uint32_t SilKit_LoggingLevel; -#define SilKit_LoggingLevel_Trace ((uint32_t) 0) //!< Detailed debug-level messages -#define SilKit_LoggingLevel_Debug ((uint32_t) 1) //!< Normal debug-level messages -#define SilKit_LoggingLevel_Info ((uint32_t) 2) //!< Informational content -#define SilKit_LoggingLevel_Warn ((uint32_t) 3) //!< Warnings -#define SilKit_LoggingLevel_Error ((uint32_t) 4) //!< Non-critical errors -#define SilKit_LoggingLevel_Critical ((uint32_t) 5) //!< Critical errors -#define SilKit_LoggingLevel_Off ((uint32_t) 0xffffffff) //!< Logging is disabled +#define SilKit_LoggingLevel_Trace ((uint32_t)0) //!< Detailed debug-level messages +#define SilKit_LoggingLevel_Debug ((uint32_t)1) //!< Normal debug-level messages +#define SilKit_LoggingLevel_Info ((uint32_t)2) //!< Informational content +#define SilKit_LoggingLevel_Warn ((uint32_t)3) //!< Warnings +#define SilKit_LoggingLevel_Error ((uint32_t)4) //!< Non-critical errors +#define SilKit_LoggingLevel_Critical ((uint32_t)5) //!< Critical errors +#define SilKit_LoggingLevel_Off ((uint32_t)0xffffffff) //!< Logging is disabled typedef struct SilKit_Logger SilKit_Logger; diff --git a/SilKit/include/silkit/capi/NetworkSimulator.h b/SilKit/include/silkit/capi/NetworkSimulator.h new file mode 100644 index 000000000..3d911b9f9 --- /dev/null +++ b/SilKit/include/silkit/capi/NetworkSimulator.h @@ -0,0 +1,289 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include "silkit/capi/Types.h" +#include "silkit/capi/InterfaceIdentifiers.h" +#include "silkit/capi/SilKitMacros.h" + +#include "silkit/capi/EventProducer.h" + +#include "silkit/capi/Can.h" +#include "silkit/capi/Flexray.h" +#include "silkit/capi/Ethernet.h" +#include "silkit/capi/Lin.h" + +#pragma pack(push) +#pragma pack(8) + +SILKIT_BEGIN_DECLS + +typedef uint32_t SilKit_Experimental_SimulatedNetworkType; +#define SilKit_NetworkType_Undefined ((SilKit_Experimental_SimulatedNetworkType)0) +#define SilKit_NetworkType_CAN ((SilKit_Experimental_SimulatedNetworkType)1) +#define SilKit_NetworkType_LIN ((SilKit_Experimental_SimulatedNetworkType)2) +#define SilKit_NetworkType_Ethernet ((SilKit_Experimental_SimulatedNetworkType)3) +#define SilKit_NetworkType_FlexRay ((SilKit_Experimental_SimulatedNetworkType)4) + +typedef struct SilKit_Experimental_NetworkSimulator SilKit_Experimental_NetworkSimulator; +typedef struct SilKit_Experimental_SimulatedNetwork SilKit_Experimental_SimulatedNetwork; +typedef struct SilKit_Experimental_SimulatedNetworkFunctions SilKit_Experimental_SimulatedNetworkFunctions; + +typedef struct SilKit_Experimental_SimulatedCanController SilKit_Experimental_SimulatedCanController; +typedef struct SilKit_Experimental_SimulatedFlexRayController SilKit_Experimental_SimulatedFlexRayController; + +typedef struct SilKit_Experimental_SimulatedControllerFunctions SilKit_Experimental_SimulatedControllerFunctions; +typedef struct SilKit_Experimental_SimulatedCanControllerFunctions SilKit_Experimental_SimulatedCanControllerFunctions; +typedef struct SilKit_Experimental_SimulatedFlexRayControllerFunctions + SilKit_Experimental_SimulatedFlexRayControllerFunctions; + +struct SilKit_Experimental_SimulatedNetworkFunctions +{ + SilKit_StructHeader structHeader; + void (*ProvideSimulatedController)(void** outSimulatedController, const void** outSimulateControllerFunctions, + SilKit_Experimental_ControllerDescriptor controllerDescriptor, + void* simulatedNetwork); + void (*SimulatedControllerRemoved)(SilKit_Experimental_ControllerDescriptor controllerDescriptor, + void* simulatedNetwork); + void (*SetEventProducer)(void* eventProducer, void* simulatedNetwork); +}; + +// -------------------------------- +// Can +// -------------------------------- + +struct SilKit_Experimental_NetSim_CanFrameRequest +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_CanFrame* frame; //!< The CAN Frame that corresponds to the meta data + void* userContext; //!< Optional pointer provided by user when sending the frame +}; +typedef struct SilKit_Experimental_NetSim_CanFrameRequest SilKit_Experimental_NetSim_CanFrameRequest; + +struct SilKit_Experimental_NetSim_CanConfigureBaudrate +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + uint32_t rate; + uint32_t fdRate; + uint32_t xlRate; +}; +typedef struct SilKit_Experimental_NetSim_CanConfigureBaudrate SilKit_Experimental_NetSim_CanConfigureBaudrate; + +typedef int32_t SilKit_Experimental_NetSim_CanControllerModeFlags; + +#define SilKit_Experimental_NetSim_CanControllerModeFlags_ResetErrorHandling \ + ((SilKit_Experimental_NetSim_CanControllerModeFlags)BIT( \ + 0)) //!< Reset the error counters to zero and the error state to error active. + +#define SilKit_Experimental_NetSim_CanControllerModeFlags_CancelTransmitRequests \ + ((SilKit_Experimental_NetSim_CanControllerModeFlags)BIT( \ + 1)) //!< Cancel all outstanding transmit requests (flush transmit queue of controller). + +struct SilKit_Experimental_NetSim_CanControllerMode +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_Experimental_NetSim_CanControllerModeFlags canControllerModeFlags; + SilKit_CanControllerState state; +}; +typedef struct SilKit_Experimental_NetSim_CanControllerMode SilKit_Experimental_NetSim_CanControllerMode; + +struct SilKit_Experimental_SimulatedCanControllerFunctions +{ + SilKit_StructHeader structHeader; + void (*OnSetBaudrate)(void* controller, const SilKit_Experimental_NetSim_CanConfigureBaudrate* configureBautrate); + void (*OnFrameRequest)(void* controller, const SilKit_Experimental_NetSim_CanFrameRequest* frameRequest); + void (*OnSetControllerMode)(void* controller, const SilKit_Experimental_NetSim_CanControllerMode* controllerMode); +}; + +// -------------------------------- +// FlexRay +// -------------------------------- + +struct SilKit_Experimental_NetSim_FlexrayHostCommand +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_FlexrayChiCommand chiCommand; +}; +typedef struct SilKit_Experimental_NetSim_FlexrayHostCommand SilKit_Experimental_NetSim_FlexrayHostCommand; + +struct SilKit_Experimental_NetSim_FlexrayControllerConfig +{ + //! The interface id specifying which version of this struct was obtained + SilKit_StructHeader structHeader; + //! FlexRay cluster parameters + SilKit_FlexrayClusterParameters* clusterParams; + //! FlexRay node parameters + SilKit_FlexrayNodeParameters* nodeParams; + //! FlexRay buffer configs + uint32_t numBufferConfigs; + SilKit_FlexrayTxBufferConfig* bufferConfigs; +}; +typedef struct SilKit_Experimental_NetSim_FlexrayControllerConfig SilKit_Experimental_NetSim_FlexrayControllerConfig; + +struct SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + uint16_t txBufferIdx; + SilKit_FlexrayTxBufferConfig* txBufferConfig; +}; +typedef struct SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate + SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate; + +struct SilKit_Experimental_NetSim_FlexrayTxBufferUpdate +{ + //! The interface id specifying which version of this struct was obtained + SilKit_StructHeader structHeader; + //! Index of the TX Buffers according to the configured buffers (cf. FlexrayControllerConfig). + uint16_t txBufferIndex; + //! Payload data valid flag + SilKit_Bool payloadDataValid; + //! Raw payload containing 0 to 254 bytes. + SilKit_ByteVector payload; +}; +typedef struct SilKit_Experimental_NetSim_FlexrayTxBufferUpdate SilKit_Experimental_NetSim_FlexrayTxBufferUpdate; + + +struct SilKit_Experimental_SimulatedFlexRayControllerFunctions +{ + SilKit_StructHeader structHeader; + void (*OnHostCommand)(void* controller, const SilKit_Experimental_NetSim_FlexrayHostCommand* hostCommand); + void (*OnControllerConfig)(void* controller, + const SilKit_Experimental_NetSim_FlexrayControllerConfig* controllerConfig); + void (*OnTxBufferConfigUpdate)(void* controller, + const SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate* txBufferConfigUpdate); + void (*OnTxBufferUpdate)(void* controller, const SilKit_Experimental_NetSim_FlexrayTxBufferUpdate* txBufferUpdate); +}; + +// -------------------------------- +// Ethernet +// -------------------------------- + +struct SilKit_Experimental_NetSim_EthernetFrameRequest +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_EthernetFrame* ethernetFrame; + void* userContext; //!< Optional pointer provided by user when sending the frame +}; +typedef struct SilKit_Experimental_NetSim_EthernetFrameRequest SilKit_Experimental_NetSim_EthernetFrameRequest; + +typedef uint8_t SilKit_EthernetControllerMode; +#define SilKit_EthernetControllerMode_Inactive ((SilKit_EthernetControllerMode)0) +#define SilKit_EthernetControllerMode_Active ((SilKit_EthernetControllerMode)1) + +struct SilKit_Experimental_NetSim_EthernetControllerMode +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_EthernetControllerMode mode; +}; +typedef struct SilKit_Experimental_NetSim_EthernetControllerMode SilKit_Experimental_NetSim_EthernetControllerMode; + +struct SilKit_Experimental_SimulatedEthernetControllerFunctions +{ + SilKit_StructHeader structHeader; + void (*OnFrameRequest)(void* controller, const SilKit_Experimental_NetSim_EthernetFrameRequest* frameRequest); + void (*OnSetControllerMode)(void* controller, + const SilKit_Experimental_NetSim_EthernetControllerMode* controllerMode); +}; + +// -------------------------------- +// Lin +// -------------------------------- + +typedef uint8_t SilKit_Experimental_NetSim_LinSimulationMode; +#define SilKit_Experimental_NetSim_LinSimulationMode_Default ((SilKit_Experimental_NetSim_LinSimulationMode)0) +#define SilKit_Experimental_NetSim_LinSimulationMode_Dynamic ((SilKit_Experimental_NetSim_LinSimulationMode)1) + +struct SilKit_Experimental_NetSim_LinFrameRequest +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_LinFrame* frame; + SilKit_LinFrameResponseType responseType; +}; +typedef struct SilKit_Experimental_NetSim_LinFrameRequest SilKit_Experimental_NetSim_LinFrameRequest; + +struct SilKit_Experimental_NetSim_LinFrameHeaderRequest +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_LinId id; +}; +typedef struct SilKit_Experimental_NetSim_LinFrameHeaderRequest SilKit_Experimental_NetSim_LinFrameHeaderRequest; + +struct SilKit_Experimental_NetSim_LinWakeupPulse +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_NanosecondsTime timestamp; //!< Timestamp of the wakeup pulse +}; +typedef struct SilKit_Experimental_NetSim_LinWakeupPulse SilKit_Experimental_NetSim_LinWakeupPulse; + +struct SilKit_Experimental_NetSim_LinControllerConfig +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_LinControllerMode controllerMode; + SilKit_LinBaudRate baudRate; + size_t numFrameResponses; + SilKit_LinFrameResponse* frameResponses; + SilKit_Experimental_NetSim_LinSimulationMode simulationMode; +}; +typedef struct SilKit_Experimental_NetSim_LinControllerConfig SilKit_Experimental_NetSim_LinControllerConfig; + +struct SilKit_Experimental_NetSim_LinFrameResponseUpdate +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + size_t numFrameResponses; + SilKit_LinFrameResponse* frameResponses; +}; +typedef struct SilKit_Experimental_NetSim_LinFrameResponseUpdate SilKit_Experimental_NetSim_LinFrameResponseUpdate; + +struct SilKit_Experimental_NetSim_LinControllerStatusUpdate +{ + SilKit_StructHeader structHeader; //!< The interface id specifying which version of this struct was obtained + SilKit_LinControllerStatus status; + SilKit_NanosecondsTime timestamp; //!< Timestamp of the wakeup pulse +}; +typedef struct SilKit_Experimental_NetSim_LinControllerStatusUpdate + SilKit_Experimental_NetSim_LinControllerStatusUpdate; + +struct SilKit_Experimental_SimulatedLinControllerFunctions +{ + SilKit_StructHeader structHeader; + void (*OnFrameRequest)(void* controller, const SilKit_Experimental_NetSim_LinFrameRequest* frameRequest); + void (*OnFrameHeaderRequest)(void* controller, + const SilKit_Experimental_NetSim_LinFrameHeaderRequest* frameHeaderRequest); + void (*OnWakeupPulse)(void* controller, const SilKit_Experimental_NetSim_LinWakeupPulse* wakeupPulse); + void (*OnControllerConfig)(void* controller, + const SilKit_Experimental_NetSim_LinControllerConfig* controllerConfig); + void (*OnFrameResponseUpdate)(void* controller, + const SilKit_Experimental_NetSim_LinFrameResponseUpdate* frameResponseUpdate); + void (*OnControllerStatusUpdate)(void* controller, + const SilKit_Experimental_NetSim_LinControllerStatusUpdate* statusUpdate); +}; + +// -------------------------------- +// NetworkSimulator +// -------------------------------- + +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_NetworkSimulator_Create( + SilKit_Experimental_NetworkSimulator** outNetworkSimulator, SilKit_Participant* participant); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_NetworkSimulator_Create_t)( + SilKit_Experimental_NetworkSimulator** outNetworkSimulator, SilKit_Participant* participant); + +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_NetworkSimulator_SimulateNetwork( + SilKit_Experimental_NetworkSimulator* networkSimulator, const char* networkName, + SilKit_Experimental_SimulatedNetworkType networkType, void* simulatedNetwork, + const SilKit_Experimental_SimulatedNetworkFunctions* simulatedNetworkFunctions); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_NetworkSimulator_SimulateNetwork_t)( + SilKit_Experimental_NetworkSimulator* networkSimulator, const char* networkName, + SilKit_Experimental_SimulatedNetworkType networkType, void* simulatedNetwork, + const SilKit_Experimental_SimulatedNetworkFunctions* simulatedNetworkFunctions); + +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_Experimental_NetworkSimulator_Start(SilKit_Experimental_NetworkSimulator* networkSimulator); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_NetworkSimulator_Start_t)( + SilKit_Experimental_NetworkSimulator* networkSimulator); + +SILKIT_END_DECLS + +#pragma pack(pop) diff --git a/SilKit/include/silkit/capi/Orchestration.h b/SilKit/include/silkit/capi/Orchestration.h old mode 100755 new mode 100644 index 89ab46d84..4a5567616 --- a/SilKit/include/silkit/capi/Orchestration.h +++ b/SilKit/include/silkit/capi/Orchestration.h @@ -42,73 +42,73 @@ typedef uint64_t SilKit_NanosecondsWallclockTime; typedef int16_t SilKit_ParticipantState; /*! An invalid participant state */ -#define SilKit_ParticipantState_Invalid ((SilKit_ParticipantState) 0) +#define SilKit_ParticipantState_Invalid ((SilKit_ParticipantState)0) /*! The controllers created state */ -#define SilKit_ParticipantState_ServicesCreated ((SilKit_ParticipantState) 10) +#define SilKit_ParticipantState_ServicesCreated ((SilKit_ParticipantState)10) /*! The communication initializing state */ -#define SilKit_ParticipantState_CommunicationInitializing ((SilKit_ParticipantState) 20) +#define SilKit_ParticipantState_CommunicationInitializing ((SilKit_ParticipantState)20) /*! The communication initialized state */ -#define SilKit_ParticipantState_CommunicationInitialized ((SilKit_ParticipantState) 30) +#define SilKit_ParticipantState_CommunicationInitialized ((SilKit_ParticipantState)30) /*! The initialized state */ -#define SilKit_ParticipantState_ReadyToRun ((SilKit_ParticipantState) 40) +#define SilKit_ParticipantState_ReadyToRun ((SilKit_ParticipantState)40) /*! The running state */ -#define SilKit_ParticipantState_Running ((SilKit_ParticipantState) 50) +#define SilKit_ParticipantState_Running ((SilKit_ParticipantState)50) /*! The paused state */ -#define SilKit_ParticipantState_Paused ((SilKit_ParticipantState) 60) +#define SilKit_ParticipantState_Paused ((SilKit_ParticipantState)60) /*! The stopping state */ -#define SilKit_ParticipantState_Stopping ((SilKit_ParticipantState) 70) +#define SilKit_ParticipantState_Stopping ((SilKit_ParticipantState)70) /*! The stopped state */ -#define SilKit_ParticipantState_Stopped ((SilKit_ParticipantState) 80) +#define SilKit_ParticipantState_Stopped ((SilKit_ParticipantState)80) /*! The error state */ -#define SilKit_ParticipantState_Error ((SilKit_ParticipantState) 90) +#define SilKit_ParticipantState_Error ((SilKit_ParticipantState)90) /*! The shutting down state */ -#define SilKit_ParticipantState_ShuttingDown ((SilKit_ParticipantState) 100) +#define SilKit_ParticipantState_ShuttingDown ((SilKit_ParticipantState)100) /*! The shutdown state */ -#define SilKit_ParticipantState_Shutdown ((SilKit_ParticipantState) 110) +#define SilKit_ParticipantState_Shutdown ((SilKit_ParticipantState)110) /*! The aborting state */ -#define SilKit_ParticipantState_Aborting ((SilKit_ParticipantState) 120) +#define SilKit_ParticipantState_Aborting ((SilKit_ParticipantState)120) /*! The state of a system, deduced by states of the required participants. */ typedef int16_t SilKit_SystemState; /*! An invalid participant state */ -#define SilKit_SystemState_Invalid ((SilKit_SystemState) 0) +#define SilKit_SystemState_Invalid ((SilKit_SystemState)0) /*! The controllers created state */ -#define SilKit_SystemState_ServicesCreated ((SilKit_SystemState) 10) +#define SilKit_SystemState_ServicesCreated ((SilKit_SystemState)10) /*! The communication initializing state */ -#define SilKit_SystemState_CommunicationInitializing ((SilKit_SystemState) 20) +#define SilKit_SystemState_CommunicationInitializing ((SilKit_SystemState)20) /*! The communication initialized state */ -#define SilKit_SystemState_CommunicationInitialized ((SilKit_SystemState) 30) +#define SilKit_SystemState_CommunicationInitialized ((SilKit_SystemState)30) /*! The initialized state */ -#define SilKit_SystemState_ReadyToRun ((SilKit_SystemState) 40) +#define SilKit_SystemState_ReadyToRun ((SilKit_SystemState)40) /*! The running state */ -#define SilKit_SystemState_Running ((SilKit_SystemState) 50) +#define SilKit_SystemState_Running ((SilKit_SystemState)50) /*! The paused state */ -#define SilKit_SystemState_Paused ((SilKit_SystemState) 60) +#define SilKit_SystemState_Paused ((SilKit_SystemState)60) /*! The stopping state */ -#define SilKit_SystemState_Stopping ((SilKit_SystemState) 70) +#define SilKit_SystemState_Stopping ((SilKit_SystemState)70) /*! The stopped state */ -#define SilKit_SystemState_Stopped ((SilKit_SystemState) 80) +#define SilKit_SystemState_Stopped ((SilKit_SystemState)80) /*! The error state */ -#define SilKit_SystemState_Error ((SilKit_SystemState) 90) +#define SilKit_SystemState_Error ((SilKit_SystemState)90) /*! The shutting down state */ -#define SilKit_SystemState_ShuttingDown ((SilKit_SystemState) 100) +#define SilKit_SystemState_ShuttingDown ((SilKit_SystemState)100) /*! The shutdown state */ -#define SilKit_SystemState_Shutdown ((SilKit_SystemState) 110) +#define SilKit_SystemState_Shutdown ((SilKit_SystemState)110) /*! The aborting state */ -#define SilKit_SystemState_Aborting ((SilKit_SystemState) 120) +#define SilKit_SystemState_Aborting ((SilKit_SystemState)120) /*! The OperationMode for lifecycle service. */ typedef int8_t SilKit_OperationMode; /*! An invalid operation mode */ -#define SilKit_OperationMode_Invalid ((SilKit_OperationMode) 0) +#define SilKit_OperationMode_Invalid ((SilKit_OperationMode)0) /*! The coordinated operation mode */ -#define SilKit_OperationMode_Coordinated ((SilKit_OperationMode) 10) +#define SilKit_OperationMode_Coordinated ((SilKit_OperationMode)10) /*! The autonomous operation mode */ -#define SilKit_OperationMode_Autonomous ((SilKit_OperationMode) 20) +#define SilKit_OperationMode_Autonomous ((SilKit_OperationMode)20) /*! Details about a status change of a participant. */ @@ -159,13 +159,13 @@ typedef struct SilKit_TimeSyncService SilKit_TimeSyncService; * * The object returned must not be deallocated using free()! */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Create(SilKit_LifecycleService** outLifecycleService, - SilKit_Participant* participant, - const SilKit_LifecycleConfiguration* startConfiguration); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_LifecycleService_Create(SilKit_LifecycleService** outLifecycleService, SilKit_Participant* participant, + const SilKit_LifecycleConfiguration* startConfiguration); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_Create_t)(SilKit_LifecycleService** outLifecycleService, - SilKit_Participant* participant, - const SilKit_LifecycleConfiguration* startConfiguration); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_Create_t)( + SilKit_LifecycleService** outLifecycleService, SilKit_Participant* participant, + const SilKit_LifecycleConfiguration* startConfiguration); /*! \brief The handler to be called on initialization * @@ -209,11 +209,13 @@ typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_SetCommunicationRe * \param context A user provided context accessible in the handler * \param handler The handler to be called on initialization */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetCommunicationReadyHandlerAsync( - SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_CommunicationReadyHandler_t handler); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_LifecycleService_SetCommunicationReadyHandlerAsync(SilKit_LifecycleService* lifecycleService, void* context, + SilKit_LifecycleService_CommunicationReadyHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_SetCommunicationReadyHandlerAsync_t)( - SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_CommunicationReadyHandler_t handler); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_SetCommunicationReadyHandlerAsync_t)( + SilKit_LifecycleService* lifecycleService, void* context, + SilKit_LifecycleService_CommunicationReadyHandler_t handler); /*! \brief Notify that the async \ref SilKit_LifecycleService_CommunicationReadyHandler_t is completed. * @@ -221,10 +223,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_SetCommunicationR * \param lifecycleService The lifecycle service receiving the update. * \return \ref SilKit_ReturnCode */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_CompleteCommunicationReadyHandlerAsync( - SilKit_LifecycleService* lifecycleService); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_LifecycleService_CompleteCommunicationReadyHandlerAsync(SilKit_LifecycleService* lifecycleService); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_CompleteCommunicationReadyHandlerAsync_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_CompleteCommunicationReadyHandlerAsync_t)( SilKit_LifecycleService* lifecycleService); /*! \brief This handler is triggered just before the lifecycle service changes to SilKit_ParticipantState_Running. @@ -234,7 +236,8 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_CompleteCommunica * \param context The user provided context passed in \ref SilKit_LifecycleService_SetCommunicationReadyHandler. * \param lifecycleService The lifecycle service receiving the update. */ -typedef void (SilKitFPTR *SilKit_LifecycleService_StartingHandler_t)(void* context, SilKit_LifecycleService* lifecycleService); +typedef void(SilKitFPTR* SilKit_LifecycleService_StartingHandler_t)(void* context, + SilKit_LifecycleService* lifecycleService); /*! \brief (Asynchronous participants only) Register a callback that is executed once directly before the participant enters SilKit_ParticipantState_Running. * @@ -253,7 +256,7 @@ typedef void (SilKitFPTR *SilKit_LifecycleService_StartingHandler_t)(void* conte SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetStartingHandler( SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_StartingHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_SetStartingHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_SetStartingHandler_t)( SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_StartingHandler_t handler); /*! \brief The handler to be called on a simulation stop @@ -261,7 +264,8 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_SetStartingHandle * \param context The user provided context passed in \ref SilKit_LifecycleService_SetStopHandler * \param lifecycleService The lifecycle service receiving the stop command */ -typedef void (SilKitFPTR *SilKit_LifecycleService_StopHandler_t)(void* context, SilKit_LifecycleService* lifecycleService); +typedef void(SilKitFPTR* SilKit_LifecycleService_StopHandler_t)(void* context, + SilKit_LifecycleService* lifecycleService); /*! \brief Register a callback that is executed on simulation stop. * @@ -279,20 +283,19 @@ typedef void (SilKitFPTR *SilKit_LifecycleService_StopHandler_t)(void* context, * \param context A user provided context accessible in the handler * \param handler The handler to be called */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetStopHandler(SilKit_LifecycleService* lifecycleService, - void* context, - SilKit_LifecycleService_StopHandler_t handler); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetStopHandler( + SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_StopHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_SetStopHandler_t)(SilKit_LifecycleService* lifecycleService, - void* context, - SilKit_LifecycleService_StopHandler_t handler); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_SetStopHandler_t)( + SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_StopHandler_t handler); /*! \brief The handler to be called on a simulation shutdown * * \param context The user provided context passed in \ref SilKit_LifecycleService_SetShutdownHandler * \param lifecycleService The lifecycleService receiving the shutdown */ -typedef void (SilKitFPTR *SilKit_LifecycleService_ShutdownHandler_t)(void* context, SilKit_LifecycleService* lifecycleService); +typedef void(SilKitFPTR* SilKit_LifecycleService_ShutdownHandler_t)(void* context, + SilKit_LifecycleService* lifecycleService); /*! \brief Register a callback that is executed on simulation shutdown. * @@ -310,7 +313,7 @@ typedef void (SilKitFPTR *SilKit_LifecycleService_ShutdownHandler_t)(void* conte SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetShutdownHandler( SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_ShutdownHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_SetShutdownHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_SetShutdownHandler_t)( SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_ShutdownHandler_t handler); /*! \brief The handler to be called on a simulation abort. @@ -332,17 +335,17 @@ typedef void(SilKitFPTR* SilKit_LifecycleService_AbortHandler_t)(void* context, SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetAbortHandler( SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_AbortHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_SetAbortHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_SetAbortHandler_t)( SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_AbortHandler_t handler); /*! \brief Start the lifecycle. * * \param lifecycleService The instance of the lifecycleService. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_StartLifecycle( - SilKit_LifecycleService* lifecycleService); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_LifecycleService_StartLifecycle(SilKit_LifecycleService* lifecycleService); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_StartLifecycle_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_StartLifecycle_t)( SilKit_LifecycleService* lifecycleService); /*! \brief Wait for to asynchronous run operation to complete and return the final participant state @@ -356,7 +359,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_StartLifecycle_t) SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_WaitForLifecycleToComplete( SilKit_LifecycleService* lifecycleService, SilKit_ParticipantState* outParticipantState); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_WaitForLifecycleToComplete_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_WaitForLifecycleToComplete_t)( SilKit_LifecycleService* lifecycleService, SilKit_ParticipantState* outParticipantState); /*! \brief Abort current simulation run due to an error. @@ -370,8 +373,8 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_WaitForLifecycleT SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_ReportError(SilKit_LifecycleService* lifecycleService, const char* reason); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_ReportError_t)(SilKit_LifecycleService* lifecycleService, - const char* reason); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_ReportError_t)(SilKit_LifecycleService* lifecycleService, + const char* reason); /*! \brief Pause execution of the participant * @@ -387,10 +390,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_ReportError_t)(Si * \param reason A string describing the reason why the simulation was paused (UTF-8). */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Pause(SilKit_LifecycleService* lifecycleService, - const char* reason); + const char* reason); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_Pause_t)(SilKit_LifecycleService* lifecycleService, - const char* reason); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_Pause_t)(SilKit_LifecycleService* lifecycleService, + const char* reason); /*! \brief Switch back to \ref SilKit_ParticipantState_Running * after having paused. @@ -399,7 +402,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_Pause_t)(SilKit_L */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Continue(SilKit_LifecycleService* lifecycleService); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_Continue_t)(SilKit_LifecycleService* lifecycleService); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_Continue_t)(SilKit_LifecycleService* lifecycleService); /*! \brief Stop execution of the participant. * @@ -419,9 +422,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_Continue_t)(SilKi * \param lifecycleService The lifecycle service of the simulation. * \param reason A string describing why the simulation was stopped (UTF-8). */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Stop(SilKit_LifecycleService* lifecycleService, const char* reason); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Stop(SilKit_LifecycleService* lifecycleService, + const char* reason); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_Stop_t)(SilKit_LifecycleService* lifecycleService, const char* reason); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_Stop_t)(SilKit_LifecycleService* lifecycleService, + const char* reason); /*! \brief Get the current participant state. * @@ -442,8 +447,8 @@ typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_State_t)(SilKit_Pa SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Status(SilKit_ParticipantStatus* outParticipantStatus, SilKit_LifecycleService* lifecycleService); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_Status_t)(SilKit_ParticipantStatus* outParticipantStatus, - SilKit_LifecycleService* lifecycleService); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_LifecycleService_Status_t)(SilKit_ParticipantStatus* outParticipantStatus, + SilKit_LifecycleService* lifecycleService); /* * @@ -459,10 +464,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_LifecycleService_Status_t)(SilKit_ * The object returned must not be deallocated using free()! */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_TimeSyncService_Create(SilKit_TimeSyncService** outTimeSyncService, - SilKit_LifecycleService* lifecycleService); + SilKit_LifecycleService* lifecycleService); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_Create_t)(SilKit_TimeSyncService** outTimeSyncService, - SilKit_Participant* lifecycleService); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_TimeSyncService_Create_t)(SilKit_TimeSyncService** outTimeSyncService, + SilKit_Participant* lifecycleService); /*! \brief The handler to be called if the simulation task is due * @@ -471,8 +476,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_Create_t)(SilKit_T * \param now The current simulation time * \param duration The duration of the simulation step */ -typedef void (SilKitFPTR *SilKit_TimeSyncService_SimulationStepHandler_t)(void* context, SilKit_TimeSyncService* timeSyncService, - SilKit_NanosecondsTime now, SilKit_NanosecondsTime duration); +typedef void(SilKitFPTR* SilKit_TimeSyncService_SimulationStepHandler_t)(void* context, + SilKit_TimeSyncService* timeSyncService, + SilKit_NanosecondsTime now, + SilKit_NanosecondsTime duration); /*! \brief Set the task to be executed with each grant / tick * * Can be changed at runtime. Execution context depends on the run type. @@ -483,9 +490,10 @@ typedef void (SilKitFPTR *SilKit_TimeSyncService_SimulationStepHandler_t)(void* * \param initialStepSize The initial size of the simulation step of this participant in nanoseconds */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_TimeSyncService_SetSimulationStepHandler( - SilKit_TimeSyncService* timeSyncService, void* context, SilKit_TimeSyncService_SimulationStepHandler_t handler, SilKit_NanosecondsTime initialStepSize); + SilKit_TimeSyncService* timeSyncService, void* context, SilKit_TimeSyncService_SimulationStepHandler_t handler, + SilKit_NanosecondsTime initialStepSize); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_SetSimulationStepHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_TimeSyncService_SetSimulationStepHandler_t)( SilKit_TimeSyncService* timeSyncService, void* context, SilKit_TimeSyncService_SimulationStepHandler_t handler, SilKit_NanosecondsTime initialStepSize); @@ -511,7 +519,7 @@ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_TimeSyncService_SetSimulationStepH SilKit_TimeSyncService* timeSyncService, void* context, SilKit_TimeSyncService_SimulationStepHandler_t handler, SilKit_NanosecondsTime initialStepSize); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_SetSimulationStepHandlerAsync_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_TimeSyncService_SetSimulationStepHandlerAsync_t)( SilKit_TimeSyncService* timeSyncService, void* context, SilKit_TimeSyncService_SimulationStepHandler_t handler, SilKit_NanosecondsTime initialStepSize); @@ -519,9 +527,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_SetSimulationStepH * * \param timeSyncService The time sync service */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_TimeSyncService_CompleteSimulationStep(SilKit_TimeSyncService* timeSyncService); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_TimeSyncService_CompleteSimulationStep(SilKit_TimeSyncService* timeSyncService); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_CompleteSimulationStep_t)(SilKit_TimeSyncService* timeSyncService); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_TimeSyncService_CompleteSimulationStep_t)( + SilKit_TimeSyncService* timeSyncService); /*! \brief Get the current simulation time * @@ -529,10 +539,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_CompleteSimulation * \param outNanosecondsTime The simulation time in nanoseconds. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_TimeSyncService_Now(SilKit_TimeSyncService* timeSyncService, - SilKit_NanosecondsTime* outNanosecondsTime); + SilKit_NanosecondsTime* outNanosecondsTime); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_Now_t)(SilKit_TimeSyncService* timeSyncService, - SilKit_NanosecondsTime* outNanosecondsTime); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_TimeSyncService_Now_t)(SilKit_TimeSyncService* timeSyncService, + SilKit_NanosecondsTime* outNanosecondsTime); /* @@ -549,30 +559,28 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_TimeSyncService_Now_t)(SilKit_Time * The object returned must not be deallocated using free()! */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_Create(SilKit_SystemMonitor** outSystemMonitor, - SilKit_Participant* participant); + SilKit_Participant* participant); typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_Create_t)(SilKit_SystemMonitor** outSystemMonitor, - SilKit_Participant* participant); + SilKit_Participant* participant); /*! \brief Get the current participant state of the participant given by participantName (UTF-8) */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_GetParticipantStatus(SilKit_ParticipantStatus* outParticipantState, - SilKit_SystemMonitor* systemMonitor, - const char* participantName); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_GetParticipantStatus( + SilKit_ParticipantStatus* outParticipantState, SilKit_SystemMonitor* systemMonitor, const char* participantName); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_GetParticipantStatus_t)(SilKit_ParticipantStatus* outParticipantState, - SilKit_SystemMonitor* systemMonitor, - const char* participantName); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_GetParticipantStatus_t)( + SilKit_ParticipantStatus* outParticipantState, SilKit_SystemMonitor* systemMonitor, const char* participantName); /*! \brief Get the current \ref SilKit_SystemState */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_GetSystemState(SilKit_SystemState* outSystemState, - SilKit_SystemMonitor* systemMonitor); + SilKit_SystemMonitor* systemMonitor); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_GetSystemState_t)(SilKit_SystemState* outSystemState, - SilKit_SystemMonitor* systemMonitor); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_GetSystemState_t)(SilKit_SystemState* outSystemState, + SilKit_SystemMonitor* systemMonitor); -typedef void (SilKitFPTR *SilKit_SystemStateHandler_t)(void* context, SilKit_SystemMonitor* systemMonitor, - SilKit_SystemState state); +typedef void(SilKitFPTR* SilKit_SystemStateHandler_t)(void* context, SilKit_SystemMonitor* systemMonitor, + SilKit_SystemState state); /*! \brief Register a callback for system state changes * @@ -585,27 +593,28 @@ typedef void (SilKitFPTR *SilKit_SystemStateHandler_t)(void* context, SilKit_Sys * \param outHandlerId The handler identifier that can be used to remove the callback. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_AddSystemStateHandler(SilKit_SystemMonitor* systemMonitor, - void* context, - SilKit_SystemStateHandler_t handler, - SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_AddSystemStateHandler_t)(SilKit_SystemMonitor* systemMonitor, - void* context, - SilKit_SystemStateHandler_t handler, - SilKit_HandlerId* outHandlerId); + void* context, + SilKit_SystemStateHandler_t handler, + SilKit_HandlerId* outHandlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_AddSystemStateHandler_t)(SilKit_SystemMonitor* systemMonitor, + void* context, + SilKit_SystemStateHandler_t handler, + SilKit_HandlerId* outHandlerId); /*! \brief Remove a \ref SilKit_SystemStateHandler_t by SilKit_HandlerId on this participant * * \param systemMonitor The system monitor obtained via \ref SilKit_SystemMonitor_Create. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_RemoveSystemStateHandler(SilKit_SystemMonitor* systemMonitor, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_SystemMonitor_RemoveSystemStateHandler(SilKit_SystemMonitor* systemMonitor, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_RemoveSystemStateHandler_t)(SilKit_SystemMonitor* systemMonitor, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_RemoveSystemStateHandler_t)( + SilKit_SystemMonitor* systemMonitor, SilKit_HandlerId handlerId); -typedef void (SilKitFPTR *SilKit_ParticipantStatusHandler_t)(void* context, SilKit_SystemMonitor* systemMonitor, - const char* participantName, SilKit_ParticipantStatus* status); +typedef void(SilKitFPTR* SilKit_ParticipantStatusHandler_t)(void* context, SilKit_SystemMonitor* systemMonitor, + const char* participantName, + SilKit_ParticipantStatus* status); /*! \brief Register a callback for status changes of participants. * @@ -617,12 +626,11 @@ typedef void (SilKitFPTR *SilKit_ParticipantStatusHandler_t)(void* context, SilK * \param handler The handler to be called to be called when the participant status changes. * \param outHandlerId The handler identifier that can be used to remove the callback. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_AddParticipantStatusHandler(SilKit_SystemMonitor* systemMonitor, - void* context, - SilKit_ParticipantStatusHandler_t handler, - SilKit_HandlerId* outHandlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_AddParticipantStatusHandler( + SilKit_SystemMonitor* systemMonitor, void* context, SilKit_ParticipantStatusHandler_t handler, + SilKit_HandlerId* outHandlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_AddParticipantStatusHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_AddParticipantStatusHandler_t)( SilKit_SystemMonitor* systemMonitor, void* context, SilKit_ParticipantStatusHandler_t handler, SilKit_HandlerId* outHandlerId); @@ -631,11 +639,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_AddParticipantStatus * \param systemMonitor The system monitor obtained via \ref SilKit_SystemMonitor_Create. * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_RemoveParticipantStatusHandler(SilKit_SystemMonitor* systemMonitor, - SilKit_HandlerId handlerId); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_SystemMonitor_RemoveParticipantStatusHandler(SilKit_SystemMonitor* systemMonitor, SilKit_HandlerId handlerId); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_RemoveParticipantStatusHandler_t)(SilKit_SystemMonitor* systemMonitor, - SilKit_HandlerId handlerId); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_RemoveParticipantStatusHandler_t)( + SilKit_SystemMonitor* systemMonitor, SilKit_HandlerId handlerId); /*! \brief Information about a participant connection in the \ref SilKit_SystemMonitor_ParticipantConnectedHandler_t. */ typedef struct SilKit_ParticipantConnectionInformation @@ -648,7 +656,7 @@ typedef struct SilKit_ParticipantConnectionInformation /*! Callback type to indicate that a participant has been connected. * Cf., \ref SilKit_SystemMonitor_SetParticipantConnectedHandler */ -typedef void (SilKitFPTR *SilKit_SystemMonitor_ParticipantConnectedHandler_t)( +typedef void(SilKitFPTR* SilKit_SystemMonitor_ParticipantConnectedHandler_t)( void* context, SilKit_SystemMonitor* systemMonitor, const SilKit_ParticipantConnectionInformation* participantConnectionInformation); @@ -661,13 +669,13 @@ typedef void (SilKitFPTR *SilKit_SystemMonitor_ParticipantConnectedHandler_t)( SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_SetParticipantConnectedHandler( SilKit_SystemMonitor* systemMonitor, void* context, SilKit_SystemMonitor_ParticipantConnectedHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_SetParticipantConnectedHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_SetParticipantConnectedHandler_t)( SilKit_SystemMonitor* systemMonitor, void* context, SilKit_SystemMonitor_ParticipantConnectedHandler_t handler); /*! Callback type to indicate that a participant has been disconnected. * Cf., \ref SilKit_SystemMonitor_SetParticipantDisconnectedHandler */ -typedef void (SilKitFPTR *SilKit_SystemMonitor_ParticipantDisconnectedHandler_t)( +typedef void(SilKitFPTR* SilKit_SystemMonitor_ParticipantDisconnectedHandler_t)( void* context, SilKit_SystemMonitor* systemMonitor, const SilKit_ParticipantConnectionInformation* participantConnectionInformation); @@ -680,7 +688,7 @@ typedef void (SilKitFPTR *SilKit_SystemMonitor_ParticipantDisconnectedHandler_t) SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_SetParticipantDisconnectedHandler( SilKit_SystemMonitor* systemMonitor, void* context, SilKit_SystemMonitor_ParticipantDisconnectedHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_SetParticipantDisconnectedHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_SetParticipantDisconnectedHandler_t)( SilKit_SystemMonitor* systemMonitor, void* context, SilKit_SystemMonitor_ParticipantDisconnectedHandler_t handler); /*! \brief Check if a participant identified by the participantName is present. @@ -693,7 +701,7 @@ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_IsParticipantConnect const char* participantName, SilKit_Bool* out); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_IsParticipantConnected_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_SystemMonitor_IsParticipantConnected_t)( SilKit_SystemMonitor* systemMonitor, const char* participantName, SilKit_Bool* out); /*! \brief Return the experimental ISystemController at a given SIL Kit participant. @@ -707,7 +715,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_SystemMonitor_IsParticipantConnect SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_SystemController_Create( SilKit_Experimental_SystemController** outSystemController, SilKit_Participant* participant); -typedef SilKit_ReturnCode(SilKitFPTR * SilKit_Experimental_SystemController_Create_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_SystemController_Create_t)( SilKit_Experimental_SystemController** outSystemController, SilKit_Participant* participant); /*! \brief Sends a SilKit::Services::Orchestration::SystemCommand::Kind::AbortSimulation to all participants @@ -722,8 +730,8 @@ typedef SilKit_ReturnCode(SilKitFPTR * SilKit_Experimental_SystemController_Crea * * @param systemController The system controller obtained via \ref SilKit_Experimental_SystemController_Create. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_SystemController_AbortSimulation( - SilKit_Experimental_SystemController* systemController); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_Experimental_SystemController_AbortSimulation(SilKit_Experimental_SystemController* systemController); typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_SystemController_AbortSimulation_t)( SilKit_Experimental_SystemController* systemController); @@ -744,12 +752,10 @@ typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_SystemController_Abort * @param workflowConfiguration The desired configuration, currently containing a list of required participants */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Experimental_SystemController_SetWorkflowConfiguration( - SilKit_Experimental_SystemController* systemController, - const SilKit_WorkflowConfiguration* workflowConfiguration); + SilKit_Experimental_SystemController* systemController, const SilKit_WorkflowConfiguration* workflowConfiguration); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Experimental_SystemController_SetWorkflowConfiguration_t)( - SilKit_Experimental_SystemController* systemController, - const SilKit_WorkflowConfiguration* workflowConfiguration); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Experimental_SystemController_SetWorkflowConfiguration_t)( + SilKit_Experimental_SystemController* systemController, const SilKit_WorkflowConfiguration* workflowConfiguration); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/Participant.h b/SilKit/include/silkit/capi/Participant.h old mode 100755 new mode 100644 index da126c560..f048b4294 --- a/SilKit/include/silkit/capi/Participant.h +++ b/SilKit/include/silkit/capi/Participant.h @@ -46,13 +46,13 @@ typedef uint64_t SilKit_NanosecondsWallclockTime; //!< Wall clock time since epo * \param registryUri The `silkit://` URI of the registry * */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Participant_Create(SilKit_Participant** outParticipant, - SilKit_ParticipantConfiguration* participantConfiguration, - const char* participantName, const char* registryUri); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Participant_Create( + SilKit_Participant** outParticipant, SilKit_ParticipantConfiguration* participantConfiguration, + const char* participantName, const char* registryUri); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Participant_Create_t)(SilKit_Participant** outParticipant, - SilKit_ParticipantConfiguration* participantConfiguration, - const char* participantName, const char* registryUri); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Participant_Create_t)( + SilKit_Participant** outParticipant, SilKit_ParticipantConfiguration* participantConfiguration, + const char* participantName, const char* registryUri); /*! \brief Destroy a simulation participant and its associated simulation elements. * @@ -63,7 +63,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Participant_Create_t)(SilKit_Parti */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Participant_Destroy(SilKit_Participant* participant); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Participant_Destroy_t)(SilKit_Participant* participant); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Participant_Destroy_t)(SilKit_Participant* participant); /*! \brief Obtain the logger of a particular simulation participant. * @@ -74,9 +74,11 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Participant_Destroy_t)(SilKit_Part * There is no futher cleanup necessary, except for destroying the simulation participant at the end of the * simulation. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Participant_GetLogger(SilKit_Logger** outLogger, SilKit_Participant* participant); +SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Participant_GetLogger(SilKit_Logger** outLogger, + SilKit_Participant* participant); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Participant_GetLogger_t)(SilKit_Logger** outLogger, SilKit_Participant* participant); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Participant_GetLogger_t)(SilKit_Logger** outLogger, + SilKit_Participant* participant); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/Rpc.h b/SilKit/include/silkit/capi/Rpc.h old mode 100755 new mode 100644 index a3d8f6040..159e05ec0 --- a/SilKit/include/silkit/capi/Rpc.h +++ b/SilKit/include/silkit/capi/Rpc.h @@ -52,9 +52,9 @@ typedef struct SilKit_RpcClient SilKit_RpcClient; /*! \brief The status of a RpcCallResultEvent. Informs whether a call was successful. */ typedef uint32_t SilKit_RpcCallStatus; -#define SilKit_RpcCallStatus_Success ((SilKit_RpcCallStatus)0) //!< Call was successful -#define SilKit_RpcCallStatus_ServerNotReachable ((SilKit_RpcCallStatus)1) //!< No server matching the RpcSpec was found -#define SilKit_RpcCallStatus_UndefinedError ((SilKit_RpcCallStatus)2) //!< An unidentified error occured +#define SilKit_RpcCallStatus_Success ((SilKit_RpcCallStatus)0) //!< Call was successful +#define SilKit_RpcCallStatus_ServerNotReachable ((SilKit_RpcCallStatus)1) //!< No server matching the RpcSpec was found +#define SilKit_RpcCallStatus_UndefinedError ((SilKit_RpcCallStatus)2) //!< An unidentified error occured /*! \brief The Call lead to an internal RpcServer error. * This might happen if no CallHandler was specified for the RpcServer. */ @@ -62,9 +62,10 @@ typedef uint32_t SilKit_RpcCallStatus; /*! \brief The Call did run into a timeout and was canceled. * This might happen if a corresponding server crashed, ran into an error or took too long to answer the call */ -#define SilKit_RpcCallStatus_Timeout ((SilKit_RpcCallStatus)4) +#define SilKit_RpcCallStatus_Timeout ((SilKit_RpcCallStatus)4) -typedef struct { +typedef struct +{ SilKit_StructHeader structHeader; //! Send timestamp of the event SilKit_NanosecondsTime timestamp; @@ -74,7 +75,8 @@ typedef struct { SilKit_ByteVector argumentData; } SilKit_RpcCallEvent; -typedef struct { +typedef struct +{ SilKit_StructHeader structHeader; //! Send timestamp of the event SilKit_NanosecondsTime timestamp; @@ -91,7 +93,8 @@ typedef struct { * \param server The RPC server that received the call. * \param event The event contains information about the call by the client. */ -typedef void (SilKitFPTR *SilKit_RpcCallHandler_t)(void* context, SilKit_RpcServer* server, const SilKit_RpcCallEvent* event); +typedef void(SilKitFPTR* SilKit_RpcCallHandler_t)(void* context, SilKit_RpcServer* server, + const SilKit_RpcCallEvent* event); /*! \brief A handler that is called on a RPC client when a RPC server submitted a result to an earlier call * of this client. @@ -99,7 +102,8 @@ typedef void (SilKitFPTR *SilKit_RpcCallHandler_t)(void* context, SilKit_RpcServ * \param client The RPC client that received the result/triggered the invocation. * \param event The event contains information about the results of an earlier call of this client. */ -typedef void (SilKitFPTR *SilKit_RpcCallResultHandler_t)(void* context, SilKit_RpcClient* client, const SilKit_RpcCallResultEvent* event); +typedef void(SilKitFPTR* SilKit_RpcCallResultHandler_t)(void* context, SilKit_RpcClient* client, + const SilKit_RpcCallResultEvent* event); /*! \brief Create a RPC server on a simulation participant with the provided properties. * \param outServer Pointer to which the resulting RPC server reference will be written. @@ -140,10 +144,10 @@ typedef SilKit_ReturnCode(SilKitFPTR* SilKit_RpcServer_SubmitResult_t)(SilKit_Rp * \param handler A callback function that is triggered on invocation of the server functionality. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_RpcServer_SetCallHandler(SilKit_RpcServer* self, void* context, - SilKit_RpcCallHandler_t handler); + SilKit_RpcCallHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_RpcServer_SetCallHandler_t)(SilKit_RpcServer* self, void* context, - SilKit_RpcCallHandler_t handler); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_RpcServer_SetCallHandler_t)(SilKit_RpcServer* self, void* context, + SilKit_RpcCallHandler_t handler); /*! \brief Create a RPC client on a simulation participant with the provided properties. * \param outClient Pointer to which the resulting RPC client reference will be written. @@ -171,10 +175,11 @@ typedef SilKit_ReturnCode(SilKitFPTR* SilKit_RpcClient_Create_t)(SilKit_RpcClien * \param userContext A user provided context pointer that is passed to the result handler when a result is received. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_RpcClient_Call(SilKit_RpcClient* self, - const SilKit_ByteVector* argumentData, void* userContext); + const SilKit_ByteVector* argumentData, void* userContext); -typedef SilKit_ReturnCode(SilKitFPTR *SilKit_RpcClient_Call_t)(SilKit_RpcClient* self, - const SilKit_ByteVector* argumentData, void* userContext); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_RpcClient_Call_t)(SilKit_RpcClient* self, + const SilKit_ByteVector* argumentData, + void* userContext); /*! \brief Initiate a remote procedure call with a specified timeout. * @@ -190,10 +195,14 @@ typedef SilKit_ReturnCode(SilKitFPTR *SilKit_RpcClient_Call_t)(SilKit_RpcClient* */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_RpcClient_CallWithTimeout(SilKit_RpcClient* self, - const SilKit_ByteVector* argumentData, SilKit_NanosecondsTime timeout, void* userContext); + const SilKit_ByteVector* argumentData, + SilKit_NanosecondsTime timeout, + void* userContext); typedef SilKit_ReturnCode(SilKitFPTR* SilKit_RpcClient_CallWithTimeout_t)(SilKit_RpcClient* self, - const SilKit_ByteVector* argumentData, SilKit_NanosecondsTime timeout, void* userContext); + const SilKit_ByteVector* argumentData, + SilKit_NanosecondsTime timeout, + void* userContext); /*! \brief Overwrite the call result handler of this client * \param self The RPC client that should trigger the remote procedure call. @@ -201,10 +210,10 @@ typedef SilKit_ReturnCode(SilKitFPTR* SilKit_RpcClient_CallWithTimeout_t)(SilKit * \param handler A callback that is called when a call result is received. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_RpcClient_SetCallResultHandler(SilKit_RpcClient* self, void* context, - SilKit_RpcCallResultHandler_t handler); + SilKit_RpcCallResultHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_RpcClient_SetCallResultHandler_t)(SilKit_RpcClient* self, void* context, - SilKit_RpcCallResultHandler_t handler); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_RpcClient_SetCallResultHandler_t)(SilKit_RpcClient* self, void* context, + SilKit_RpcCallResultHandler_t handler); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/SilKit.h b/SilKit/include/silkit/capi/SilKit.h index 87285db16..039021d99 100644 --- a/SilKit/include/silkit/capi/SilKit.h +++ b/SilKit/include/silkit/capi/SilKit.h @@ -35,6 +35,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "silkit/capi/Orchestration.h" #include "silkit/capi/Vendor.h" #include "silkit/capi/Version.h" +#include "silkit/capi/NetworkSimulator.h" +#include "silkit/capi/EventProducer.h" SILKIT_BEGIN_DECLS @@ -48,7 +50,8 @@ SILKIT_BEGIN_DECLS */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_ReturnCodeToString(const char** outString, SilKit_ReturnCode returnCode); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_ReturnCodeToString_t)(const char** outString, SilKit_ReturnCode returnCode); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_ReturnCodeToString_t)(const char** outString, + SilKit_ReturnCode returnCode); /*! \brief Get a human readable error description of the last error on the current thread. * @@ -60,7 +63,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_ReturnCodeToString_t)(const char* */ SilKitAPI const char* SilKitCALL SilKit_GetLastErrorString(); -typedef const char*(SilKitFPTR *SilKit_GetLastErrorString_t)(); +typedef const char*(SilKitFPTR* SilKit_GetLastErrorString_t)(); /*! \brief Create an opaque participant configuration from the configuration text. * @@ -70,12 +73,10 @@ typedef const char*(SilKitFPTR *SilKit_GetLastErrorString_t)(); * \param participantConfigurationString The configuration as a UTF-8 encoded string (e.g., read from a configuration file or a string constant). */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_ParticipantConfiguration_FromString( - SilKit_ParticipantConfiguration** outParticipantConfiguration, - const char* participantConfigurationString); + SilKit_ParticipantConfiguration** outParticipantConfiguration, const char* participantConfigurationString); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_ParticipantConfiguration_FromString_t)( - SilKit_ParticipantConfiguration** outParticipantConfiguration, - const char* participantConfigurationString); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_ParticipantConfiguration_FromString_t)( + SilKit_ParticipantConfiguration** outParticipantConfiguration, const char* participantConfigurationString); /*! \brief Create an opaque participant configuration from the contents of the UTF-8 encoded text file. @@ -86,22 +87,20 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_ParticipantConfiguration_FromStrin * \param participantConfigurationPath The path to the configuration file as a UTF-8 encoded string. */ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_ParticipantConfiguration_FromFile( - SilKit_ParticipantConfiguration** outParticipantConfiguration, - const char* participantConfigurationPath); + SilKit_ParticipantConfiguration** outParticipantConfiguration, const char* participantConfigurationPath); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_ParticipantConfiguration_FromFile_t)( - SilKit_ParticipantConfiguration** outParticipantConfiguration, - const char* participantConfigurationPath); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_ParticipantConfiguration_FromFile_t)( + SilKit_ParticipantConfiguration** outParticipantConfiguration, const char* participantConfigurationPath); /*! \brief Destroy a participant configuration. * * \param participantConfiguration The participant configuration to be destroyed. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_ParticipantConfiguration_Destroy( - SilKit_ParticipantConfiguration* participantConfiguration); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_ParticipantConfiguration_Destroy(SilKit_ParticipantConfiguration* participantConfiguration); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_ParticipantConfiguration_Destroy_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_ParticipantConfiguration_Destroy_t)( SilKit_ParticipantConfiguration* participantConfiguration); diff --git a/SilKit/include/silkit/capi/SilKitMacros.h b/SilKit/include/silkit/capi/SilKitMacros.h old mode 100755 new mode 100644 index ad5d4d342..ae6ee94fc --- a/SilKit/include/silkit/capi/SilKitMacros.h +++ b/SilKit/include/silkit/capi/SilKitMacros.h @@ -22,44 +22,44 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #ifdef __cplusplus -# include +#include #else -# include +#include #endif #ifdef __cplusplus -# define SILKIT_BEGIN_DECLS \ - extern "C" \ - { -# define SILKIT_END_DECLS } +#define SILKIT_BEGIN_DECLS \ + extern "C" \ + { +#define SILKIT_END_DECLS } #else -# define SILKIT_BEGIN_DECLS -# define SILKIT_END_DECLS +#define SILKIT_BEGIN_DECLS +#define SILKIT_END_DECLS #endif #ifdef SILKIT_BUILD_STATIC -# define SilKitAPI +#define SilKitAPI #elif defined(EXPORT_SilKitAPI) // define compiler specific export / import attributes // define SilKitAPI as EXPORT -# if defined(_WIN32) -# define SilKitAPI __declspec(dllexport) -# elif defined(__GNUC__) -# define SilKitAPI __attribute__((visibility("default"))) -# else -# define SilKitAPI -# pragma warning Unknown dynamic link export semantics. -# endif +#if defined(_WIN32) +#define SilKitAPI __declspec(dllexport) +#elif defined(__GNUC__) +#define SilKitAPI __attribute__((visibility("default"))) +#else +#define SilKitAPI +#pragma warning Unknown dynamic link export semantics. +#endif #else // declare SilKitAPI as IMPORT -# if defined(_WIN32) -# define SilKitAPI __declspec(dllimport) -# elif defined(__GNUC__) -# define SilKitAPI -# else -# define SilKitAPI -# pragma warning Unknown dynamic link import semantics. -# endif +#if defined(_WIN32) +#define SilKitAPI __declspec(dllimport) +#elif defined(__GNUC__) +#define SilKitAPI +#else +#define SilKitAPI +#pragma warning Unknown dynamic link import semantics. +#endif #endif #ifdef _WIN32 @@ -72,7 +72,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Utilities for more readable definitions #ifndef BIT -# define BIT(X) (UINTMAX_C(1) << (X)) +#define BIT(X) (UINTMAX_C(1) << (X)) #endif #define SILKIT_UNUSED_ARG(X) (void)(X) diff --git a/SilKit/include/silkit/capi/Types.h b/SilKit/include/silkit/capi/Types.h index 73b4e210f..19e129426 100644 --- a/SilKit/include/silkit/capi/Types.h +++ b/SilKit/include/silkit/capi/Types.h @@ -43,15 +43,15 @@ typedef struct SilKit_Experimental_SystemController SilKit_Experimental_SystemCo typedef int32_t SilKit_ReturnCode; -#define SilKit_ReturnCode_SUCCESS ((SilKit_ReturnCode) 0) -#define SilKit_ReturnCode_UNSPECIFIEDERROR ((SilKit_ReturnCode) 1) -#define SilKit_ReturnCode_NOTSUPPORTED ((SilKit_ReturnCode) 2) -#define SilKit_ReturnCode_NOTIMPLEMENTED ((SilKit_ReturnCode) 3) -#define SilKit_ReturnCode_BADPARAMETER ((SilKit_ReturnCode) 4) -#define SilKit_ReturnCode_BUFFERTOOSMALL ((SilKit_ReturnCode) 5) -#define SilKit_ReturnCode_TIMEOUT ((SilKit_ReturnCode) 6) -#define SilKit_ReturnCode_UNSUPPORTEDSERVICE ((SilKit_ReturnCode) 7) -#define SilKit_ReturnCode_WRONGSTATE ((SilKit_ReturnCode) 8) // Returned on exception SilKit::StateError (CapiImpl.h) +#define SilKit_ReturnCode_SUCCESS ((SilKit_ReturnCode)0) +#define SilKit_ReturnCode_UNSPECIFIEDERROR ((SilKit_ReturnCode)1) +#define SilKit_ReturnCode_NOTSUPPORTED ((SilKit_ReturnCode)2) +#define SilKit_ReturnCode_NOTIMPLEMENTED ((SilKit_ReturnCode)3) +#define SilKit_ReturnCode_BADPARAMETER ((SilKit_ReturnCode)4) +#define SilKit_ReturnCode_BUFFERTOOSMALL ((SilKit_ReturnCode)5) +#define SilKit_ReturnCode_TIMEOUT ((SilKit_ReturnCode)6) +#define SilKit_ReturnCode_UNSUPPORTEDSERVICE ((SilKit_ReturnCode)7) +#define SilKit_ReturnCode_WRONGSTATE ((SilKit_ReturnCode)8) // Returned on exception SilKit::StateError (CapiImpl.h) typedef uint64_t SilKit_NanosecondsTime; @@ -72,9 +72,9 @@ typedef struct SilKit_ByteVector SilKit_ByteVector; /*! \brief Information level of log messages */ typedef uint32_t SilKit_LabelKind; -#define SilKit_LabelKind_Undefined ((uint32_t) 0) //!< Undefined -#define SilKit_LabelKind_Optional ((uint32_t) 1) //!< If this label is available, its value must match -#define SilKit_LabelKind_Mandatory ((uint32_t) 2) //!< This label must be available and its value must match +#define SilKit_LabelKind_Undefined ((uint32_t)0) //!< Undefined +#define SilKit_LabelKind_Optional ((uint32_t)1) //!< If this label is available, its value must match +#define SilKit_LabelKind_Mandatory ((uint32_t)2) //!< This label must be available and its value must match /*! \brief Struct that contains a label as used in PubSub and RPC for matching publisher, subscribers, servers, and clients */ typedef struct SilKit_Label @@ -99,16 +99,16 @@ typedef struct SilKit_StringList } SilKit_StringList; typedef uint8_t SilKit_Bool; -#define SilKit_True ((SilKit_Bool)1) +#define SilKit_True ((SilKit_Bool)1) #define SilKit_False ((SilKit_Bool)0) // NB: Should map to SilKit::Services::TransmitDirection /*! \brief An enum type defining the transmit direction within the simulation */ typedef uint8_t SilKit_Direction; -#define SilKit_Direction_Undefined ((SilKit_Direction) 0) -#define SilKit_Direction_Send ((SilKit_Direction) 1) -#define SilKit_Direction_Receive ((SilKit_Direction) 2) -#define SilKit_Direction_SendReceive ((SilKit_Direction) 3) +#define SilKit_Direction_Undefined ((SilKit_Direction)0) +#define SilKit_Direction_Send ((SilKit_Direction)1) +#define SilKit_Direction_Receive ((SilKit_Direction)2) +#define SilKit_Direction_SendReceive ((SilKit_Direction)3) typedef uint64_t SilKit_HandlerId; diff --git a/SilKit/include/silkit/capi/Vendor.h b/SilKit/include/silkit/capi/Vendor.h index 66d494b37..56bea1319 100644 --- a/SilKit/include/silkit/capi/Vendor.h +++ b/SilKit/include/silkit/capi/Vendor.h @@ -38,17 +38,17 @@ SILKIT_BEGIN_DECLS SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Vendor_Vector_SilKitRegistry_Create( SilKit_Vendor_Vector_SilKitRegistry** outRegistry, SilKit_ParticipantConfiguration* participantConfiguration); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_Create_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Vendor_Vector_SilKitRegistry_Create_t)( SilKit_Vendor_Vector_SilKitRegistry** outRegistry, SilKit_ParticipantConfiguration* participantConfiguration); /*! \brief Destroy a registry. * * @param registry The registry to be destroyed. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Vendor_Vector_SilKitRegistry_Destroy( - SilKit_Vendor_Vector_SilKitRegistry* registry); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_Vendor_Vector_SilKitRegistry_Destroy(SilKit_Vendor_Vector_SilKitRegistry* registry); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_Destroy_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Vendor_Vector_SilKitRegistry_Destroy_t)( SilKit_Vendor_Vector_SilKitRegistry* registry); /*! \brief The handler to be called when all participants have disconnected. @@ -56,7 +56,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_Destr * \param context The user provided context passed in \ref SilKit_Vendor_Vector_SilKitRegistry_SetAllDisconnectedHandler. * \param registry The registry on which all participants have disconnected. */ -typedef void (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_AllDisconnectedHandler_t)( +typedef void(SilKitFPTR* SilKit_Vendor_Vector_SilKitRegistry_AllDisconnectedHandler_t)( void* context, SilKit_Vendor_Vector_SilKitRegistry* registry); /*! \brief Register the handler that is called when all participants are disconnected @@ -69,7 +69,7 @@ SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Vendor_Vector_SilKitRegistry_SetAl SilKit_Vendor_Vector_SilKitRegistry* registry, void* context, SilKit_Vendor_Vector_SilKitRegistry_AllDisconnectedHandler_t handler); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_SetAllDisconnectedHandler_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Vendor_Vector_SilKitRegistry_SetAllDisconnectedHandler_t)( SilKit_Vendor_Vector_SilKitRegistry* registry, void* context, SilKit_Vendor_Vector_SilKitRegistry_AllDisconnectedHandler_t handler); @@ -81,10 +81,10 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_SetAl * @param outLogger Pointer to the resulting logger instance (out parameter). * @param registry The registry whose logger should be returned. */ -SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Vendor_Vector_SilKitRegistry_GetLogger( - SilKit_Logger** outLogger, SilKit_Vendor_Vector_SilKitRegistry* registry); +SilKitAPI SilKit_ReturnCode SilKitCALL +SilKit_Vendor_Vector_SilKitRegistry_GetLogger(SilKit_Logger** outLogger, SilKit_Vendor_Vector_SilKitRegistry* registry); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_GetLogger_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Vendor_Vector_SilKitRegistry_GetLogger_t)( SilKit_Logger** outLogger, SilKit_Vendor_Vector_SilKitRegistry* registry); /*! \brief Start to listen on the URI with scheme silkit://, e.g. silkit://localhost:8500, and return the URI with the @@ -102,7 +102,7 @@ typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_GetLo SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Vendor_Vector_SilKitRegistry_StartListening( SilKit_Vendor_Vector_SilKitRegistry* registry, const char* listenUri, const char** outRegistryUri); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Vendor_Vector_SilKitRegistry_StartListening_t)( +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Vendor_Vector_SilKitRegistry_StartListening_t)( SilKit_Vendor_Vector_SilKitRegistry* registry, const char* listenUri, const char** outRegistryUri); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/capi/Version.h b/SilKit/include/silkit/capi/Version.h index b58c2848d..741826a21 100644 --- a/SilKit/include/silkit/capi/Version.h +++ b/SilKit/include/silkit/capi/Version.h @@ -30,31 +30,31 @@ SILKIT_BEGIN_DECLS //! \brief This release's major version number SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Version_Major(uint32_t* outVersionMajor); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Version_Major_t)(uint32_t* outVersionMajor); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Version_Major_t)(uint32_t* outVersionMajor); //! \brief This release's minor version number SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Version_Minor(uint32_t* outVersionMinor); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Version_Minor_t)(uint32_t* outVersionMinor); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Version_Minor_t)(uint32_t* outVersionMinor); //! \brief This release's patch version number SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Version_Patch(uint32_t* outVersionPatch); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Version_Patch_t)(uint32_t* outVersionPatch); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Version_Patch_t)(uint32_t* outVersionPatch); //! \brief Retrieve this release's build number on the master branch SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Version_BuildNumber(uint32_t* outVersionBuildNumber); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Version_BuildNumber_t)(uint32_t* outVersionBuildNumber); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Version_BuildNumber_t)(uint32_t* outVersionBuildNumber); //! \brief Retrieve the API version identifier ".." of this release SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Version_String(const char** outVersionString); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Version_String_t)(const char** outVersionString); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Version_String_t)(const char** outVersionString); //! \brief Retrieve additional version information of this release SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Version_VersionSuffix(const char** outVersionVersionSuffix); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Version_VersionSuffix_t)(const char** outVersionVersionSuffix); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Version_VersionSuffix_t)(const char** outVersionVersionSuffix); //! \brief Retrieve the full git hash of this release SilKitAPI SilKit_ReturnCode SilKitCALL SilKit_Version_GitHash(const char** outVersionGitHash); -typedef SilKit_ReturnCode (SilKitFPTR *SilKit_Version_GitHash_t)(const char** outVersionGitHash); +typedef SilKit_ReturnCode(SilKitFPTR* SilKit_Version_GitHash_t)(const char** outVersionGitHash); SILKIT_END_DECLS diff --git a/SilKit/include/silkit/detail/impl/HourglassConversions.hpp b/SilKit/include/silkit/detail/impl/HourglassConversions.hpp new file mode 100644 index 000000000..60a5c9bca --- /dev/null +++ b/SilKit/include/silkit/detail/impl/HourglassConversions.hpp @@ -0,0 +1,867 @@ +/* Copyright (c) 2022 Vector Informatik GmbH + +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. */ + +#pragma once + +#include "silkit/capi/Can.h" +#include "silkit/services/can/CanDatatypes.hpp" + +#include "silkit/capi/Flexray.h" +#include "silkit/services/flexray/FlexrayDatatypes.hpp" + +#include "silkit/capi/Ethernet.h" +#include "silkit/services/ethernet/EthernetDatatypes.hpp" + +#include "silkit/capi/Lin.h" +#include "silkit/services/lin/LinDatatypes.hpp" + +#include "silkit/capi/NetworkSimulator.h" +#include "silkit/experimental/netsim/NetworkSimulatorDatatypes.hpp" + +#include "silkit/capi/InterfaceIdentifiers.h" + +namespace { + +// ================================================================ +// Cxx to C +// ================================================================ + +// -------------------------------- +// Cxx Services::Can to C +// -------------------------------- + +inline void assignCxxToC(const SilKit::Services::Can::CanFrame& cxxIn, SilKit_CanFrame& cOut) +{ + cOut.id = cxxIn.canId; + cOut.flags = cxxIn.flags; + cOut.dlc = cxxIn.dlc; + cOut.sdt = cxxIn.sdt; + cOut.vcid = cxxIn.vcid; + cOut.af = cxxIn.af; + cOut.data = ToSilKitByteVector(cxxIn.dataField); +} + +inline void assignCxxToC(const SilKit::Services::Can::CanFrameEvent& cxxIn, SilKit_CanFrameEvent& cOut) +{ + assignCxxToC(cxxIn.frame, *cOut.frame); + cOut.direction = static_cast(cxxIn.direction); + cOut.timestamp = cxxIn.timestamp.count(); + cOut.userContext = cxxIn.userContext; +} + +inline void assignCxxToC(const SilKit::Services::Can::CanFrameTransmitEvent& cxxIn, SilKit_CanFrameTransmitEvent& cOut) +{ + cOut.userContext = cxxIn.userContext; + cOut.timestamp = cxxIn.timestamp.count(); + cOut.status = (SilKit_CanTransmitStatus)cxxIn.status; + cOut.canId = cxxIn.canId; +} + +inline void assignCxxToC(const SilKit::Services::Can::CanStateChangeEvent& cxxIn, SilKit_CanStateChangeEvent& cOut) +{ + cOut.timestamp = cxxIn.timestamp.count(); + cOut.state = (SilKit_CanControllerState)cxxIn.state; +} + +inline void assignCxxToC(const SilKit::Services::Can::CanErrorStateChangeEvent& cxxIn, + SilKit_CanErrorStateChangeEvent& cOut) +{ + cOut.timestamp = cxxIn.timestamp.count(); + cOut.errorState = (SilKit_CanErrorState)cxxIn.errorState; +} + +// -------------------------------- +// Cxx Experimental::NetworkSimulation::Can to C +// -------------------------------- + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Can::CanControllerMode& cxxIn, + SilKit_Experimental_NetSim_CanControllerMode& cOut) +{ + cOut.state = (SilKit_CanControllerState)cxxIn.state; + cOut.canControllerModeFlags = cxxIn.canControllerModeFlags; +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Can::CanConfigureBaudrate& cxxIn, + SilKit_Experimental_NetSim_CanConfigureBaudrate& cOut) +{ + cOut.rate = cxxIn.baudRate; + cOut.fdRate = cxxIn.fdBaudRate; + cOut.xlRate = cxxIn.xlBaudRate; +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Can::CanFrameRequest& cxxIn, + SilKit_Experimental_NetSim_CanFrameRequest& cOut) +{ + cOut.userContext = cxxIn.userContext; + assignCxxToC(cxxIn.frame, *cOut.frame); +} + +// -------------------------------- +// Cxx Services::Flexray to C +// -------------------------------- + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayHeader& cxxIn, SilKit_FlexrayHeader& cOut) +{ + cOut.cycleCount = cxxIn.cycleCount; + cOut.frameId = cxxIn.frameId; + cOut.flags = cxxIn.flags; + cOut.headerCrc = cxxIn.headerCrc; + cOut.payloadLength = cxxIn.payloadLength; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayFrame& cxxIn, SilKit_FlexrayFrame& cOut) +{ + assignCxxToC(cxxIn.header, *cOut.header); + cOut.payload.data = (uint8_t*)cxxIn.payload.data(); + cOut.payload.size = (uint32_t)cxxIn.payload.size(); +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayFrameEvent& cxxIn, SilKit_FlexrayFrameEvent& cOut) +{ + assignCxxToC(cxxIn.frame, *cOut.frame); + cOut.timestamp = cxxIn.timestamp.count(); + cOut.channel = (SilKit_FlexrayChannel)cxxIn.channel; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayFrameTransmitEvent& cxxIn, + SilKit_FlexrayFrameTransmitEvent& cOut) +{ + assignCxxToC(cxxIn.frame, *cOut.frame); + cOut.timestamp = cxxIn.timestamp.count(); + cOut.txBufferIndex = cxxIn.txBufferIndex; + cOut.channel = (SilKit_FlexrayChannel)cxxIn.channel; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexraySymbolEvent& cxxIn, SilKit_FlexraySymbolEvent& cOut) +{ + cOut.timestamp = cxxIn.timestamp.count(); + cOut.channel = (SilKit_FlexrayChannel)cxxIn.channel; + cOut.pattern = (SilKit_FlexraySymbolPattern)cxxIn.pattern; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexraySymbolTransmitEvent& cxxIn, + SilKit_FlexraySymbolTransmitEvent& cOut) +{ + cOut.timestamp = cxxIn.timestamp.count(); + cOut.channel = (SilKit_FlexrayChannel)cxxIn.channel; + cOut.pattern = (SilKit_FlexraySymbolPattern)cxxIn.pattern; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayCycleStartEvent& cxxIn, + SilKit_FlexrayCycleStartEvent& cOut) +{ + cOut.timestamp = cxxIn.timestamp.count(); + cOut.cycleCounter = cxxIn.cycleCounter; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayPocStatusEvent& cxxIn, + SilKit_FlexrayPocStatusEvent& cOut) +{ + cOut.timestamp = cxxIn.timestamp.count(); + cOut.state = (SilKit_FlexrayPocState)cxxIn.state; + cOut.chiHaltRequest = cxxIn.chiHaltRequest; + cOut.coldstartNoise = cxxIn.coldstartNoise; + cOut.freeze = cxxIn.freeze; + cOut.chiReadyRequest = cxxIn.chiReadyRequest; + cOut.errorMode = (SilKit_FlexrayErrorModeType)cxxIn.errorMode; + cOut.slotMode = (SilKit_FlexraySlotModeType)cxxIn.slotMode; + cOut.startupState = (SilKit_FlexrayStartupStateType)cxxIn.startupState; + cOut.wakeupStatus = (SilKit_FlexrayWakeupStatusType)cxxIn.wakeupStatus; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayClusterParameters& cxxIn, + SilKit_FlexrayClusterParameters& cOut) +{ + cOut.gColdstartAttempts = cxxIn.gColdstartAttempts; + cOut.gCycleCountMax = cxxIn.gCycleCountMax; + cOut.gdActionPointOffset = cxxIn.gdActionPointOffset; + cOut.gdDynamicSlotIdlePhase = cxxIn.gdDynamicSlotIdlePhase; + cOut.gdMiniSlot = cxxIn.gdMiniSlot; + cOut.gdMiniSlotActionPointOffset = cxxIn.gdMiniSlotActionPointOffset; + cOut.gdStaticSlot = cxxIn.gdStaticSlot; + cOut.gdSymbolWindow = cxxIn.gdSymbolWindow; + cOut.gdSymbolWindowActionPointOffset = cxxIn.gdSymbolWindowActionPointOffset; + cOut.gdTSSTransmitter = cxxIn.gdTSSTransmitter; + cOut.gdWakeupTxActive = cxxIn.gdWakeupTxActive; + cOut.gdWakeupTxIdle = cxxIn.gdWakeupTxIdle; + cOut.gListenNoise = cxxIn.gListenNoise; + cOut.gMacroPerCycle = cxxIn.gMacroPerCycle; + cOut.gMaxWithoutClockCorrectionFatal = cxxIn.gMaxWithoutClockCorrectionFatal; + cOut.gMaxWithoutClockCorrectionPassive = cxxIn.gMaxWithoutClockCorrectionPassive; + cOut.gNumberOfMiniSlots = cxxIn.gNumberOfMiniSlots; + cOut.gNumberOfStaticSlots = cxxIn.gNumberOfStaticSlots; + cOut.gPayloadLengthStatic = cxxIn.gPayloadLengthStatic; + cOut.gSyncFrameIDCountMax = cxxIn.gSyncFrameIDCountMax; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayNodeParameters& cxxIn, + SilKit_FlexrayNodeParameters& cOut) +{ + cOut.pAllowHaltDueToClock = cxxIn.pAllowHaltDueToClock; + cOut.pAllowPassiveToActive = cxxIn.pAllowPassiveToActive; + cOut.pChannels = static_cast(cxxIn.pChannels); + cOut.pClusterDriftDamping = cxxIn.pClusterDriftDamping; + cOut.pdAcceptedStartupRange = cxxIn.pdAcceptedStartupRange; + cOut.pdListenTimeout = cxxIn.pdListenTimeout; + cOut.pKeySlotId = cxxIn.pKeySlotId; + cOut.pKeySlotOnlyEnabled = cxxIn.pKeySlotOnlyEnabled; + cOut.pKeySlotUsedForStartup = cxxIn.pKeySlotUsedForStartup; + cOut.pKeySlotUsedForSync = cxxIn.pKeySlotUsedForSync; + cOut.pLatestTx = cxxIn.pLatestTx; + cOut.pMacroInitialOffsetA = cxxIn.pMacroInitialOffsetA; + cOut.pMacroInitialOffsetB = cxxIn.pMacroInitialOffsetB; + cOut.pMicroInitialOffsetA = cxxIn.pMicroInitialOffsetA; + cOut.pMicroInitialOffsetB = cxxIn.pMicroInitialOffsetB; + cOut.pMicroPerCycle = cxxIn.pMicroPerCycle; + cOut.pOffsetCorrectionOut = cxxIn.pOffsetCorrectionOut; + cOut.pOffsetCorrectionStart = cxxIn.pOffsetCorrectionStart; + cOut.pRateCorrectionOut = cxxIn.pRateCorrectionOut; + cOut.pWakeupChannel = static_cast(cxxIn.pWakeupChannel); + cOut.pWakeupPattern = cxxIn.pWakeupPattern; + cOut.pdMicrotick = static_cast(cxxIn.pdMicrotick); + cOut.pSamplesPerMicrotick = cxxIn.pSamplesPerMicrotick; +} + +inline void assignCxxToC(const SilKit::Services::Flexray::FlexrayTxBufferConfig& cxxIn, + SilKit_FlexrayTxBufferConfig& cOut) +{ + cOut.channels = static_cast(cxxIn.channels); + cOut.slotId = cxxIn.slotId; + cOut.offset = cxxIn.offset; + cOut.repetition = cxxIn.repetition; + cOut.hasPayloadPreambleIndicator = cxxIn.hasPayloadPreambleIndicator; + cOut.headerCrc = cxxIn.headerCrc; + cOut.transmissionMode = static_cast(cxxIn.transmissionMode); +} + +// ----------------------------------- +// Cxx Experimental::NetworkSimulation::Flexray to C +// ----------------------------------- + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayHostCommand& cxxIn, + SilKit_Experimental_NetSim_FlexrayHostCommand& cOut) +{ + cOut.chiCommand = (SilKit_FlexrayChiCommand)cxxIn.command; +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig& cxxIn, + SilKit_Experimental_NetSim_FlexrayControllerConfig& cOut) +{ + assignCxxToC(cxxIn.clusterParams, *cOut.clusterParams); + assignCxxToC(cxxIn.nodeParams, *cOut.nodeParams); + + cOut.numBufferConfigs = static_cast(cxxIn.bufferConfigs.size()); + size_t i = 0; + for (const auto& cxxTxBufferConfig : cxxIn.bufferConfigs) + { + assignCxxToC(cxxTxBufferConfig, cOut.bufferConfigs[i++]); + } +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferConfigUpdate& cxxIn, + SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate& cOut) +{ + cOut.txBufferIdx = cxxIn.txBufferIndex; + assignCxxToC(cxxIn.txBufferConfig, *cOut.txBufferConfig); +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate& cxxIn, + SilKit_Experimental_NetSim_FlexrayTxBufferUpdate& cOut) +{ + cOut.txBufferIndex = cxxIn.txBufferIndex; + cOut.payloadDataValid = cxxIn.payloadDataValid; + cOut.payload = ToSilKitByteVector(cxxIn.payload); +} + +// ----------------------------------- +// Cxx Services::Ethernet to C +// ----------------------------------- + +inline void assignCxxToC(const SilKit::Services::Ethernet::EthernetFrame& cxxIn, SilKit_EthernetFrame& cOut) +{ + auto* dataPointer = !cxxIn.raw.empty() ? cxxIn.raw.data() : nullptr; + cOut.raw = {dataPointer, cxxIn.raw.size()}; +} + +inline void assignCxxToC(const SilKit::Services::Ethernet::EthernetFrameEvent& cxxIn, SilKit_EthernetFrameEvent& cOut) +{ + assignCxxToC(cxxIn.frame, *cOut.ethernetFrame); + cOut.timestamp = cxxIn.timestamp.count(); + cOut.direction = static_cast(cxxIn.direction); + cOut.userContext = cxxIn.userContext; +} + + +inline void assignCxxToC(const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& cxxIn, + SilKit_EthernetFrameTransmitEvent& cOut) +{ + cOut.status = (SilKit_EthernetTransmitStatus)cxxIn.status; + cOut.timestamp = cxxIn.timestamp.count(); + cOut.userContext = cxxIn.userContext; +} + + +inline void assignCxxToC(const SilKit::Services::Ethernet::EthernetStateChangeEvent& cxxIn, + SilKit_EthernetStateChangeEvent& cOut) +{ + cOut.state = (SilKit_EthernetState)cxxIn.state; + cOut.timestamp = cxxIn.timestamp.count(); +} + +inline void assignCxxToC(const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& cxxIn, + SilKit_EthernetBitrateChangeEvent& cOut) +{ + cOut.bitrate = cxxIn.bitrate; + cOut.timestamp = cxxIn.timestamp.count(); +} + + +// ----------------------------------- +// Cxx Experimental::NetworkSimulation::Ethernet to C +// ----------------------------------- + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Ethernet::EthernetFrameRequest& cxxIn, + SilKit_Experimental_NetSim_EthernetFrameRequest& cOut) +{ + assignCxxToC(cxxIn.ethernetFrame, *cOut.ethernetFrame); + cOut.userContext = cxxIn.userContext; +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Ethernet::EthernetControllerMode& cxxIn, + SilKit_Experimental_NetSim_EthernetControllerMode& cOut) +{ + cOut.mode = (SilKit_EthernetControllerMode)cxxIn.mode; +} + +// ----------------------------------- +// Cxx Services::Lin to C +// ----------------------------------- + +inline void assignCxxToC(const SilKit::Services::Lin::LinFrame& cxxIn, SilKit_LinFrame& cOut) +{ + cOut.id = cxxIn.id; + cOut.checksumModel = static_cast(cxxIn.checksumModel); + cOut.dataLength = cxxIn.dataLength; + std::copy_n(cxxIn.data.data(), cxxIn.data.size(), cOut.data); +} + +inline void assignCxxToC(const SilKit::Services::Lin::LinFrameStatusEvent& cxxIn, SilKit_LinFrameStatusEvent& cOut) +{ + assignCxxToC(cxxIn.frame, *cOut.frame); + cOut.timestamp = (SilKit_NanosecondsTime)cxxIn.timestamp.count(); + cOut.status = (SilKit_LinFrameStatus)cxxIn.status; +} + +inline void assignCxxToC(const SilKit::Services::Lin::LinWakeupEvent& cxxIn, SilKit_LinWakeupEvent& cOut) +{ + cOut.timestamp = (SilKit_NanosecondsTime)cxxIn.timestamp.count(); + cOut.direction = (SilKit_Direction)cxxIn.direction; +} + +inline void assignCxxToC(const SilKit::Services::Lin::LinGoToSleepEvent& cxxIn, SilKit_LinGoToSleepEvent& cOut) +{ + cOut.timestamp = (SilKit_NanosecondsTime)cxxIn.timestamp.count(); +} + +inline void assignCxxToC(const SilKit::Services::Lin::LinFrameResponse& cxxIn, SilKit_LinFrameResponse& cOut) +{ + assignCxxToC(cxxIn.frame, *cOut.frame); + cOut.responseMode = (SilKit_LinFrameResponseMode)cxxIn.responseMode; +} + +inline void assignCxxToC(const SilKit::Services::Lin::LinSendFrameHeaderRequest& cxxIn, + SilKit_LinSendFrameHeaderRequest& cOut) +{ + cOut.id = cxxIn.id; + cOut.timestamp = (SilKit_NanosecondsTime)cxxIn.timestamp.count(); +} + +// ----------------------------------- +// Cxx Experimental::NetworkSimulation::Lin to C +// ----------------------------------- + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Lin::LinFrameRequest& cxxIn, + SilKit_Experimental_NetSim_LinFrameRequest& cOut) +{ + assignCxxToC(cxxIn.frame, *cOut.frame); + cOut.responseType = (SilKit_LinFrameResponseType)cxxIn.responseType; +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Lin::LinFrameHeaderRequest& cxxIn, + SilKit_Experimental_NetSim_LinFrameHeaderRequest& cOut) +{ + cOut.id = cxxIn.id; +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Lin::LinWakeupPulse& cxxIn, + SilKit_Experimental_NetSim_LinWakeupPulse& cOut) +{ + cOut.timestamp = (SilKit_NanosecondsTime)cxxIn.timestamp.count(); +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Lin::LinControllerConfig& cxxIn, + SilKit_Experimental_NetSim_LinControllerConfig& cOut) +{ + cOut.baudRate = cxxIn.baudRate; + cOut.controllerMode = static_cast(cxxIn.controllerMode); + size_t i = 0; + for (const auto& cxxFrameResponse : cxxIn.frameResponses) + { + assignCxxToC(cxxFrameResponse, cOut.frameResponses[i++]); + } + cOut.numFrameResponses = cxxIn.frameResponses.size(); + cOut.simulationMode = (SilKit_Experimental_NetSim_LinSimulationMode)cxxIn.simulationMode; +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Lin::LinFrameResponseUpdate& cxxIn, + SilKit_Experimental_NetSim_LinFrameResponseUpdate& cOut) +{ + size_t i = 0; + for (const auto& cxxFrameResponse : cxxIn.frameResponses) + { + assignCxxToC(cxxFrameResponse, cOut.frameResponses[i++]); + } + cOut.numFrameResponses = cxxIn.frameResponses.size(); +} + +inline void assignCxxToC(const SilKit::Experimental::NetworkSimulation::Lin::LinControllerStatusUpdate& cxxIn, + SilKit_Experimental_NetSim_LinControllerStatusUpdate& cOut) +{ + cOut.status = (SilKit_LinControllerStatus)cxxIn.status; +} + +// ================================================================ +// C to Cxx +// ================================================================ + +// -------------------------------- +// C to Cxx Services::Can +// -------------------------------- + +inline void assignCToCxx(const SilKit_CanFrame* cIn, SilKit::Services::Can::CanFrame& cxxOut) +{ + cxxOut.canId = cIn->id; + cxxOut.flags = cIn->flags; + cxxOut.dlc = cIn->dlc; + cxxOut.sdt = cIn->sdt; + cxxOut.vcid = cIn->vcid; + cxxOut.af = cIn->af; + cxxOut.dataField = SilKit::Util::ToSpan(cIn->data); +} + + +inline void assignCToCxx(const SilKit_CanFrameEvent* cIn, SilKit::Services::Can::CanFrameEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.frame.canId = cIn->frame->id; + cxxOut.frame.flags = cIn->frame->flags; + cxxOut.frame.dlc = cIn->frame->dlc; + cxxOut.frame.sdt = cIn->frame->sdt; + cxxOut.frame.vcid = cIn->frame->vcid; + cxxOut.frame.af = cIn->frame->af; + cxxOut.frame.dataField = SilKit::Util::ToSpan(cIn->frame->data); + cxxOut.direction = static_cast(cIn->direction); + cxxOut.userContext = cIn->userContext; +} + +inline void assignCToCxx(const SilKit_CanFrameTransmitEvent* cIn, SilKit::Services::Can::CanFrameTransmitEvent& cxxOut) +{ + cxxOut.userContext = cIn->userContext; + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.status = static_cast(cIn->status); + if (SK_ID_GET_VERSION(SilKit_Struct_GetId((*cIn))) >= 2) + { + cxxOut.canId = cIn->canId; + } +} + + +inline void assignCToCxx(const SilKit_CanStateChangeEvent* cIn, SilKit::Services::Can::CanStateChangeEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.state = static_cast(cIn->state); +} + +inline void assignCToCxx(const SilKit_CanErrorStateChangeEvent* cIn, + SilKit::Services::Can::CanErrorStateChangeEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.errorState = static_cast(cIn->errorState); +} + +// -------------------------------- +// C to Cxx Experimental::NetworkSimulation::Can +// -------------------------------- + +inline void assignCToCxx(const SilKit_Experimental_NetSim_CanFrameRequest* cIn, + SilKit::Experimental::NetworkSimulation::Can::CanFrameRequest& cxxOut) +{ + cxxOut.userContext = cIn->userContext; + assignCToCxx(cIn->frame, cxxOut.frame); +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_CanConfigureBaudrate* cIn, + SilKit::Experimental::NetworkSimulation::Can::CanConfigureBaudrate& cxxOut) +{ + cxxOut.baudRate = cIn->rate; + cxxOut.fdBaudRate = cIn->fdRate; + cxxOut.xlBaudRate = cIn->xlRate; +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_CanControllerMode* cIn, + SilKit::Experimental::NetworkSimulation::Can::CanControllerMode& cxxOut) +{ + cxxOut.state = static_cast(cIn->state); + cxxOut.canControllerModeFlags = cIn->canControllerModeFlags; +} + +// -------------------------------- +// C to Cxx Services::Flexray +// -------------------------------- + +inline void assignCToCxx(const SilKit_FlexrayHeader* cIn, SilKit::Services::Flexray::FlexrayHeader& cxxOut) +{ + cxxOut.cycleCount = cIn->cycleCount; + cxxOut.flags = cIn->flags; + cxxOut.frameId = cIn->frameId; + cxxOut.headerCrc = cIn->headerCrc; + cxxOut.payloadLength = cIn->payloadLength; +} + +inline void assignCToCxx(const SilKit_FlexrayFrame* cIn, SilKit::Services::Flexray::FlexrayFrame& cxxOut) +{ + cxxOut.payload = SilKit::Util::ToSpan(cIn->payload); + assignCToCxx(cIn->header, cxxOut.header); +} + +inline void assignCToCxx(const SilKit_FlexrayFrameEvent* cIn, SilKit::Services::Flexray::FlexrayFrameEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.channel = static_cast(cIn->channel); + assignCToCxx(cIn->frame, cxxOut.frame); +} + +inline void assignCToCxx(const SilKit_FlexrayFrameTransmitEvent* cIn, + SilKit::Services::Flexray::FlexrayFrameTransmitEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.channel = static_cast(cIn->channel); + cxxOut.txBufferIndex = cIn->txBufferIndex; + assignCToCxx(cIn->frame, cxxOut.frame); +} + +inline void assignCToCxx(const SilKit_FlexraySymbolEvent* cIn, SilKit::Services::Flexray::FlexraySymbolEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.channel = static_cast(cIn->channel); + cxxOut.pattern = static_cast(cIn->pattern); +} + +inline void assignCToCxx(const SilKit_FlexraySymbolTransmitEvent* cIn, + SilKit::Services::Flexray::FlexraySymbolTransmitEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.channel = static_cast(cIn->channel); + cxxOut.pattern = static_cast(cIn->pattern); +} + +inline void assignCToCxx(const SilKit_FlexrayCycleStartEvent* cIn, + SilKit::Services::Flexray::FlexrayCycleStartEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.cycleCounter = cIn->cycleCounter; +} + +inline void assignCToCxx(const SilKit_FlexrayPocStatusEvent* cIn, + SilKit::Services::Flexray::FlexrayPocStatusEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.state = static_cast(cIn->state); + cxxOut.chiHaltRequest = cIn->chiHaltRequest; + cxxOut.chiReadyRequest = cIn->chiReadyRequest; + cxxOut.coldstartNoise = cIn->coldstartNoise; + cxxOut.errorMode = static_cast(cIn->errorMode); + cxxOut.freeze = cIn->freeze; + cxxOut.slotMode = static_cast(cIn->slotMode); + cxxOut.startupState = static_cast(cIn->startupState); + cxxOut.wakeupStatus = static_cast(cIn->wakeupStatus); +} + +inline void assignCToCxx(const SilKit_FlexrayTxBufferConfig* cIn, + SilKit::Services::Flexray::FlexrayTxBufferConfig& cxxOut) +{ + cxxOut.channels = (SilKit::Services::Flexray::FlexrayChannel)cIn->channels; + cxxOut.slotId = cIn->slotId; + cxxOut.offset = cIn->offset; + cxxOut.repetition = cIn->repetition; + cxxOut.hasPayloadPreambleIndicator = cIn->hasPayloadPreambleIndicator == SilKit_True; + cxxOut.headerCrc = cIn->headerCrc; + cxxOut.transmissionMode = (SilKit::Services::Flexray::FlexrayTransmissionMode)cIn->transmissionMode; +} + +inline void assignCToCxx(const SilKit_FlexrayClusterParameters* cIn, + SilKit::Services::Flexray::FlexrayClusterParameters& cxxOut) +{ + cxxOut.gColdstartAttempts = cIn->gColdstartAttempts; + cxxOut.gCycleCountMax = cIn->gCycleCountMax; + cxxOut.gdActionPointOffset = cIn->gdActionPointOffset; + cxxOut.gdDynamicSlotIdlePhase = cIn->gdDynamicSlotIdlePhase; + cxxOut.gdMiniSlot = cIn->gdMiniSlot; + cxxOut.gdMiniSlotActionPointOffset = cIn->gdMiniSlotActionPointOffset; + cxxOut.gdStaticSlot = cIn->gdStaticSlot; + cxxOut.gdSymbolWindow = cIn->gdSymbolWindow; + cxxOut.gdSymbolWindowActionPointOffset = cIn->gdSymbolWindowActionPointOffset; + cxxOut.gdTSSTransmitter = cIn->gdTSSTransmitter; + cxxOut.gdWakeupTxActive = cIn->gdWakeupTxActive; + cxxOut.gdWakeupTxIdle = cIn->gdWakeupTxIdle; + cxxOut.gListenNoise = cIn->gListenNoise; + cxxOut.gMacroPerCycle = cIn->gMacroPerCycle; + cxxOut.gMaxWithoutClockCorrectionFatal = cIn->gMaxWithoutClockCorrectionFatal; + cxxOut.gMaxWithoutClockCorrectionPassive = cIn->gMaxWithoutClockCorrectionPassive; + cxxOut.gNumberOfMiniSlots = cIn->gNumberOfMiniSlots; + cxxOut.gNumberOfStaticSlots = cIn->gNumberOfStaticSlots; + cxxOut.gPayloadLengthStatic = cIn->gPayloadLengthStatic; + cxxOut.gSyncFrameIDCountMax = cIn->gSyncFrameIDCountMax; +} + +inline void assignCToCxx(const SilKit_FlexrayNodeParameters* cIn, + SilKit::Services::Flexray::FlexrayNodeParameters& cxxOut) +{ + cxxOut.pAllowHaltDueToClock = cIn->pAllowHaltDueToClock; + cxxOut.pAllowPassiveToActive = cIn->pAllowPassiveToActive; + cxxOut.pChannels = (SilKit::Services::Flexray::FlexrayChannel)cIn->pChannels; + cxxOut.pClusterDriftDamping = cIn->pClusterDriftDamping; + cxxOut.pdAcceptedStartupRange = cIn->pdAcceptedStartupRange; + cxxOut.pdListenTimeout = cIn->pdListenTimeout; + cxxOut.pKeySlotId = cIn->pKeySlotId; + cxxOut.pKeySlotOnlyEnabled = cIn->pKeySlotOnlyEnabled; + cxxOut.pKeySlotUsedForStartup = cIn->pKeySlotUsedForStartup; + cxxOut.pKeySlotUsedForSync = cIn->pKeySlotUsedForSync; + cxxOut.pLatestTx = cIn->pLatestTx; + cxxOut.pMacroInitialOffsetA = cIn->pMacroInitialOffsetA; + cxxOut.pMacroInitialOffsetB = cIn->pMacroInitialOffsetB; + cxxOut.pMicroInitialOffsetA = cIn->pMicroInitialOffsetA; + cxxOut.pMicroInitialOffsetB = cIn->pMicroInitialOffsetB; + cxxOut.pMicroPerCycle = cIn->pMicroPerCycle; + cxxOut.pOffsetCorrectionOut = cIn->pOffsetCorrectionOut; + cxxOut.pOffsetCorrectionStart = cIn->pOffsetCorrectionStart; + cxxOut.pRateCorrectionOut = cIn->pRateCorrectionOut; + cxxOut.pWakeupChannel = (SilKit::Services::Flexray::FlexrayChannel)cIn->pWakeupChannel; + cxxOut.pWakeupPattern = cIn->pWakeupPattern; + cxxOut.pdMicrotick = (SilKit::Services::Flexray::FlexrayClockPeriod)cIn->pdMicrotick; + cxxOut.pSamplesPerMicrotick = cIn->pSamplesPerMicrotick; +} + +// ----------------------------------- +// C to Cxx Experimental::NetworkSimulation::Flexray +// ----------------------------------- + +inline void assignCToCxx(const SilKit_Experimental_NetSim_FlexrayHostCommand* cIn, + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayHostCommand& cxxOut) +{ + cxxOut.command = static_cast(cIn->chiCommand); +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_FlexrayControllerConfig* cIn, + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig& cxxOut) +{ + assignCToCxx(cIn->clusterParams, cxxOut.clusterParams); + assignCToCxx(cIn->nodeParams, cxxOut.nodeParams); + + for (uint32_t i = 0; i < cIn->numBufferConfigs; i++) + { + SilKit::Services::Flexray::FlexrayTxBufferConfig txBufferConfig{}; + assignCToCxx(&cIn->bufferConfigs[i], txBufferConfig); + cxxOut.bufferConfigs.push_back(std::move(txBufferConfig)); + } +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate* cIn, + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferConfigUpdate& cxxOut) +{ + cxxOut.txBufferIndex = cIn->txBufferIdx; + assignCToCxx(cIn->txBufferConfig, cxxOut.txBufferConfig); +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_FlexrayTxBufferUpdate* cIn, + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate& cxxOut) +{ + cxxOut.txBufferIndex = cIn->txBufferIndex; + cxxOut.payloadDataValid = cIn->payloadDataValid == SilKit_True; + if (cIn->payloadDataValid) + { + cxxOut.payload = SilKit::Util::ToSpan(cIn->payload); + } +} + +// -------------------------------- +// C to Cxx Services::Ethernet +// -------------------------------- + +inline void assignCToCxx(const SilKit_EthernetFrame* cIn, SilKit::Services::Ethernet::EthernetFrame& cxxOut) +{ + cxxOut.raw = SilKit::Util::ToSpan(cIn->raw); +} + +inline void assignCToCxx(const SilKit_EthernetFrameEvent* cIn, SilKit::Services::Ethernet::EthernetFrameEvent& cxxOut) +{ + assignCToCxx(cIn->ethernetFrame, cxxOut.frame); + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.direction = static_cast(cIn->direction); + cxxOut.userContext = cIn->userContext; +} + +inline void assignCToCxx(const SilKit_EthernetFrameTransmitEvent* cIn, + SilKit::Services::Ethernet::EthernetFrameTransmitEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.status = static_cast(cIn->status); + cxxOut.userContext = cIn->userContext; +} + +inline void assignCToCxx(const SilKit_EthernetBitrateChangeEvent* cIn, + SilKit::Services::Ethernet::EthernetBitrateChangeEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.bitrate = static_cast(cIn->bitrate); +} + +inline void assignCToCxx(const SilKit_EthernetStateChangeEvent* cIn, + SilKit::Services::Ethernet::EthernetStateChangeEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.state = static_cast(cIn->state); +} + +// ----------------------------------- +// C to Cxx Experimental::NetworkSimulation::Ethernet +// ----------------------------------- + +inline void assignCToCxx(const SilKit_Experimental_NetSim_EthernetControllerMode* cIn, + SilKit::Experimental::NetworkSimulation::Ethernet::EthernetControllerMode& cxxOut) +{ + cxxOut.mode = static_cast(cIn->mode); +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_EthernetFrameRequest* cIn, + SilKit::Experimental::NetworkSimulation::Ethernet::EthernetFrameRequest& cxxOut) +{ + assignCToCxx(cIn->ethernetFrame, cxxOut.ethernetFrame); + cxxOut.userContext = cIn->userContext; +} + +// -------------------------------- +// C to Cxx Services::Lin +// -------------------------------- + +inline void assignCToCxx(const SilKit_LinFrame* cIn, SilKit::Services::Lin::LinFrame& cxxOut) +{ + cxxOut.id = static_cast(cIn->id); + cxxOut.checksumModel = static_cast(cIn->checksumModel); + cxxOut.dataLength = static_cast(cIn->dataLength); + memcpy(cxxOut.data.data(), cIn->data, 8); +} + +inline void assignCToCxx(const SilKit_LinFrameResponse* cIn, SilKit::Services::Lin::LinFrameResponse& cxxOut) +{ + assignCToCxx(cIn->frame, cxxOut.frame); + cxxOut.responseMode = static_cast(cIn->responseMode); +} + +inline void assignCToCxx(const SilKit_LinFrameStatusEvent* cIn, SilKit::Services::Lin::LinFrameStatusEvent& cxxOut) +{ + assignCToCxx(cIn->frame, cxxOut.frame); + cxxOut.status = static_cast(cIn->status); + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; +} + +inline void assignCToCxx(const SilKit_LinSendFrameHeaderRequest* cIn, + SilKit::Services::Lin::LinSendFrameHeaderRequest& cxxOut) +{ + cxxOut.id = cIn->id; + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; +} + +inline void assignCToCxx(const SilKit_LinWakeupEvent* cIn, SilKit::Services::Lin::LinWakeupEvent& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; + cxxOut.direction = static_cast(cIn->direction); +} + + +// ----------------------------------- +// C to Cxx Experimental::NetworkSimulation::Lin +// ----------------------------------- + +inline void assignCToCxx(const SilKit_Experimental_NetSim_LinFrameRequest* cIn, + SilKit::Experimental::NetworkSimulation::Lin::LinFrameRequest& cxxOut) +{ + assignCToCxx(cIn->frame, cxxOut.frame); + cxxOut.responseType = static_cast(cIn->responseType); +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_LinFrameHeaderRequest* cIn, + SilKit::Experimental::NetworkSimulation::Lin::LinFrameHeaderRequest& cxxOut) +{ + cxxOut.id = cIn->id; +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_LinWakeupPulse* cIn, + SilKit::Experimental::NetworkSimulation::Lin::LinWakeupPulse& cxxOut) +{ + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_LinControllerConfig* cIn, + SilKit::Experimental::NetworkSimulation::Lin::LinControllerConfig& cxxOut) +{ + cxxOut.baudRate = cIn->baudRate; + cxxOut.controllerMode = static_cast(cIn->controllerMode); + for (uint32_t i = 0; i < cIn->numFrameResponses; i++) + { + SilKit::Services::Lin::LinFrameResponse frameResponse{}; + assignCToCxx(&cIn->frameResponses[i], frameResponse); + cxxOut.frameResponses.push_back(std::move(frameResponse)); + } + cxxOut.simulationMode = + static_cast( + cIn->simulationMode); +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_LinFrameResponseUpdate* cIn, + SilKit::Experimental::NetworkSimulation::Lin::LinFrameResponseUpdate& cxxOut) +{ + for (uint32_t i = 0; i < cIn->numFrameResponses; i++) + { + SilKit::Services::Lin::LinFrameResponse frameResponse{}; + assignCToCxx(&cIn->frameResponses[i], frameResponse); + cxxOut.frameResponses.push_back(std::move(frameResponse)); + } +} + +inline void assignCToCxx(const SilKit_Experimental_NetSim_LinControllerStatusUpdate* cIn, + SilKit::Experimental::NetworkSimulation::Lin::LinControllerStatusUpdate& cxxOut) +{ + cxxOut.status = static_cast(cIn->status); + cxxOut.timestamp = std::chrono::nanoseconds{cIn->timestamp}; +} + +} //namespace \ No newline at end of file diff --git a/SilKit/include/silkit/detail/impl/SilKit.ipp b/SilKit/include/silkit/detail/impl/SilKit.ipp index c69ab939c..705e818f1 100644 --- a/SilKit/include/silkit/detail/impl/SilKit.ipp +++ b/SilKit/include/silkit/detail/impl/SilKit.ipp @@ -41,8 +41,8 @@ auto CreateParticipant(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri) - -> std::unique_ptr + const std::string& participantName, + const std::string& registryUri) -> std::unique_ptr { auto& config = dynamic_cast(*participantConfig.get()); diff --git a/SilKit/include/silkit/detail/impl/config/IParticipantConfiguration.ipp b/SilKit/include/silkit/detail/impl/config/IParticipantConfiguration.ipp index 3c7e757a2..9fd17631f 100644 --- a/SilKit/include/silkit/detail/impl/config/IParticipantConfiguration.ipp +++ b/SilKit/include/silkit/detail/impl/config/IParticipantConfiguration.ipp @@ -26,10 +26,6 @@ #include "silkit/detail/impl/ThrowOnError.hpp" #include "silkit/detail/impl/config/ParticipantConfiguration.hpp" -#include -#include - - namespace SilKit { DETAIL_SILKIT_DETAIL_VN_NAMESPACE_BEGIN namespace Config { diff --git a/SilKit/include/silkit/detail/impl/experimental/participant/ParticipantExtensions.ipp b/SilKit/include/silkit/detail/impl/experimental/participant/ParticipantExtensions.ipp index 2fe94ed6e..8a18bb3c8 100644 --- a/SilKit/include/silkit/detail/impl/experimental/participant/ParticipantExtensions.ipp +++ b/SilKit/include/silkit/detail/impl/experimental/participant/ParticipantExtensions.ipp @@ -24,6 +24,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "silkit/SilKitMacros.hpp" #include "silkit/participant/IParticipant.hpp" #include "silkit/experimental/services/orchestration/ISystemController.hpp" +#include "silkit/experimental/netsim/INetworkSimulator.hpp" #include "silkit/detail/impl/participant/Participant.hpp" #include "silkit/detail/impl/experimental/services/orchestration/SystemController.hpp" @@ -42,6 +43,14 @@ auto CreateSystemController(SilKit::IParticipant* cppIParticipant) return cppParticipant.ExperimentalCreateSystemController(); } +auto CreateNetworkSimulator(SilKit::IParticipant* cppIParticipant) + -> SilKit::Experimental::NetworkSimulation::INetworkSimulator* +{ + auto& cppParticipant = dynamic_cast(*cppIParticipant); + + return cppParticipant.ExperimentalCreateNetworkSimulator(); +} + } // namespace Participant } // namespace Experimental DETAIL_SILKIT_DETAIL_VN_NAMESPACE_CLOSE @@ -52,6 +61,7 @@ namespace SilKit { namespace Experimental { namespace Participant { using SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Experimental::Participant::CreateSystemController; +using SilKit::DETAIL_SILKIT_DETAIL_NAMESPACE_NAME::Experimental::Participant::CreateNetworkSimulator; } // namespace Participant } // namespace Experimental } // namespace SilKit diff --git a/SilKit/include/silkit/detail/impl/experimental/services/lin/LinControllerExtensions.ipp b/SilKit/include/silkit/detail/impl/experimental/services/lin/LinControllerExtensions.ipp index f904a76f2..9108b35ab 100644 --- a/SilKit/include/silkit/detail/impl/experimental/services/lin/LinControllerExtensions.ipp +++ b/SilKit/include/silkit/detail/impl/experimental/services/lin/LinControllerExtensions.ipp @@ -33,7 +33,7 @@ namespace Services { namespace Lin { auto AddLinSlaveConfigurationHandler(SilKit::Services::Lin::ILinController* cppILinController, - SilKit::Experimental::Services::Lin::LinSlaveConfigurationHandler handler) + SilKit::Experimental::Services::Lin::LinSlaveConfigurationHandler handler) -> SilKit::Util::HandlerId { auto& cppLinController = dynamic_cast(*cppILinController); @@ -42,7 +42,7 @@ auto AddLinSlaveConfigurationHandler(SilKit::Services::Lin::ILinController* cppI } void RemoveLinSlaveConfigurationHandler(SilKit::Services::Lin::ILinController* cppILinController, - SilKit::Util::HandlerId handlerId) + SilKit::Util::HandlerId handlerId) { auto& cppLinController = dynamic_cast(*cppILinController); @@ -57,28 +57,33 @@ auto GetSlaveConfiguration(SilKit::Services::Lin::ILinController* cppILinControl return cppLinController.ExperimentalGetSlaveConfiguration(); } -void InitDynamic(SilKit::Services::Lin::ILinController* linController, const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig) +void InitDynamic(SilKit::Services::Lin::ILinController* linController, + const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig) { auto& cppLinController = dynamic_cast(*linController); cppLinController.ExperimentalInitDynamic(dynamicConfig); } -auto AddFrameHeaderHandler(SilKit::Services::Lin::ILinController* linController, SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) -> SilKit::Services::HandlerId +auto AddFrameHeaderHandler(SilKit::Services::Lin::ILinController* linController, + SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) + -> SilKit::Services::HandlerId { auto& cppLinController = dynamic_cast(*linController); return cppLinController.ExperimentalAddFrameHeaderHandler(std::move(handler)); } -void RemoveFrameHeaderHandler(SilKit::Services::Lin::ILinController* linController, SilKit::Services::HandlerId handlerId) +void RemoveFrameHeaderHandler(SilKit::Services::Lin::ILinController* linController, + SilKit::Services::HandlerId handlerId) { auto& cppLinController = dynamic_cast(*linController); cppLinController.ExperimentalRemoveFrameHeaderHandler(handlerId); } -void SendDynamicResponse(SilKit::Services::Lin::ILinController* linController, const SilKit::Services::Lin::LinFrame& linFrame) +void SendDynamicResponse(SilKit::Services::Lin::ILinController* linController, + const SilKit::Services::Lin::LinFrame& linFrame) { auto& cppLinController = dynamic_cast(*linController); diff --git a/SilKit/include/silkit/detail/impl/netsim/EventProducer.hpp b/SilKit/include/silkit/detail/impl/netsim/EventProducer.hpp new file mode 100644 index 000000000..509bb953e --- /dev/null +++ b/SilKit/include/silkit/detail/impl/netsim/EventProducer.hpp @@ -0,0 +1,472 @@ +// SPDX-FileCopyrightText: 2023 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "silkit/capi/EventProducer.h" +#include "silkit/experimental/netsim/INetworkSimulator.hpp" + +#include "silkit/detail/impl/HourglassConversions.hpp" + +#include "silkit/capi/InterfaceIdentifiers.h" +#include "silkit/detail/impl/ThrowOnError.hpp" + +namespace SilKit { +DETAIL_SILKIT_DETAIL_VN_NAMESPACE_BEGIN +namespace Impl { +namespace Experimental { +namespace NetworkSimulation { + +// -------------------------------- +// CAN +// -------------------------------- + +class CanEventProducer : public SilKit::Experimental::NetworkSimulation::Can::ICanEventProducer +{ +public: + inline CanEventProducer(SilKit_Experimental_CanEventProducer* canEventProducer); + + inline ~CanEventProducer() override = default; + + inline void Produce(const SilKit::Services::Can::CanFrameEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + + inline void Produce(const SilKit::Services::Can::CanFrameTransmitEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + + inline void Produce(const SilKit::Services::Can::CanStateChangeEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + + inline void Produce(const SilKit::Services::Can::CanErrorStateChangeEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + +private: + SilKit_Experimental_CanEventProducer* _canEventProducer{nullptr}; +}; + +// -------------------------------- +// FlexRay +// -------------------------------- + +class FlexRayEventProducer : public SilKit::Experimental::NetworkSimulation::Flexray::IFlexRayEventProducer +{ +public: + inline FlexRayEventProducer(SilKit_Experimental_FlexRayEventProducer* flexRayEventProducer); + + inline ~FlexRayEventProducer() override = default; + + inline void Produce(const SilKit::Services::Flexray::FlexrayFrameEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + + inline void Produce(const SilKit::Services::Flexray::FlexrayFrameTransmitEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + + inline void Produce(const SilKit::Services::Flexray::FlexraySymbolEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + + inline void Produce(const SilKit::Services::Flexray::FlexraySymbolTransmitEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + + inline void Produce(const SilKit::Services::Flexray::FlexrayCycleStartEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + + inline void Produce(const SilKit::Services::Flexray::FlexrayPocStatusEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + +private: + SilKit_Experimental_FlexRayEventProducer* _flexRayEventProducer{nullptr}; +}; + +// -------------------------------- +// Ethernet +// -------------------------------- + +class EthernetEventProducer : public SilKit::Experimental::NetworkSimulation::Ethernet::IEthernetEventProducer +{ +public: + inline EthernetEventProducer(SilKit_Experimental_EthernetEventProducer* ethernetEventProducer); + + inline ~EthernetEventProducer() override = default; + + inline void Produce(const SilKit::Services::Ethernet::EthernetFrameEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + inline void Produce(const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + inline void Produce(const SilKit::Services::Ethernet::EthernetStateChangeEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + inline void Produce(const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + +private: + SilKit_Experimental_EthernetEventProducer* _ethernetEventProducer{nullptr}; +}; + +// -------------------------------- +// Lin +// -------------------------------- + +class LinEventProducer : public SilKit::Experimental::NetworkSimulation::Lin::ILinEventProducer +{ +public: + inline LinEventProducer(SilKit_Experimental_LinEventProducer* LinEventProducer); + + inline ~LinEventProducer() override = default; + + inline void Produce(const SilKit::Services::Lin::LinFrameStatusEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + inline void Produce(const SilKit::Services::Lin::LinSendFrameHeaderRequest& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + inline void Produce(const SilKit::Services::Lin::LinWakeupEvent& cxxEvent, + const SilKit::Util::Span& + cxxReceivers) override; + +private: + SilKit_Experimental_LinEventProducer* _linEventProducer{nullptr}; +}; + +// -------------------------------- +// Receivers +// -------------------------------- + +inline SilKit_Experimental_EventReceivers assignReceivers( + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_Experimental_EventReceivers receivers; + SilKit_Struct_Init(SilKit_Experimental_EventReceivers, receivers); + receivers.numReceivers = cxxReceivers.size(); + receivers.controllerDescriptors = cxxReceivers.data(); + return receivers; +} + +// -------------------------------- +// CAN +// -------------------------------- + +CanEventProducer::CanEventProducer(SilKit_Experimental_CanEventProducer* canEventProducer) + : _canEventProducer{canEventProducer} +{ +} + +void CanEventProducer::Produce( + const SilKit::Services::Can::CanFrameEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_CanFrameEvent cEvent; + SilKit_Struct_Init(SilKit_CanFrameEvent, cEvent); + SilKit_CanFrame canFrame; + SilKit_Struct_Init(SilKit_CanFrame, canFrame); + cEvent.frame = &canFrame; + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_CanEventProducer_Produce(_canEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void CanEventProducer::Produce( + const SilKit::Services::Can::CanFrameTransmitEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_CanFrameTransmitEvent cEvent; + SilKit_Struct_Init(SilKit_CanFrameTransmitEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_CanEventProducer_Produce(_canEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void CanEventProducer::Produce( + const SilKit::Services::Can::CanStateChangeEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_CanStateChangeEvent cEvent; + SilKit_Struct_Init(SilKit_CanStateChangeEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_CanEventProducer_Produce(_canEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void CanEventProducer::Produce( + const SilKit::Services::Can::CanErrorStateChangeEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_CanErrorStateChangeEvent cEvent; + SilKit_Struct_Init(SilKit_CanErrorStateChangeEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_CanEventProducer_Produce(_canEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +// -------------------------------- +// FlexRay +// -------------------------------- + +FlexRayEventProducer::FlexRayEventProducer(SilKit_Experimental_FlexRayEventProducer* flexRayEventProducer) + : _flexRayEventProducer{flexRayEventProducer} +{ +} + +void FlexRayEventProducer::Produce( + const SilKit::Services::Flexray::FlexrayFrameEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_FlexrayFrameEvent cEvent; + SilKit_Struct_Init(SilKit_FlexrayFrameEvent, cEvent); + SilKit_FlexrayFrame frame; + SilKit_Struct_Init(SilKit_FlexrayFrame, frame); + SilKit_FlexrayHeader header; + SilKit_Struct_Init(SilKit_FlexrayHeader, header); + cEvent.frame = &frame; + cEvent.frame->header = &header; + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_FlexRayEventProducer_Produce(_flexRayEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void FlexRayEventProducer::Produce( + const SilKit::Services::Flexray::FlexrayFrameTransmitEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_FlexrayFrameTransmitEvent cEvent; + SilKit_Struct_Init(SilKit_FlexrayFrameTransmitEvent, cEvent); + SilKit_FlexrayFrame frame; + SilKit_Struct_Init(SilKit_FlexrayFrame, frame); + SilKit_FlexrayHeader header; + SilKit_Struct_Init(SilKit_FlexrayHeader, header); + cEvent.frame = &frame; + cEvent.frame->header = &header; + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_FlexRayEventProducer_Produce(_flexRayEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void FlexRayEventProducer::Produce( + const SilKit::Services::Flexray::FlexraySymbolEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_FlexraySymbolEvent cEvent; + SilKit_Struct_Init(SilKit_FlexraySymbolEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_FlexRayEventProducer_Produce(_flexRayEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void FlexRayEventProducer::Produce( + const SilKit::Services::Flexray::FlexraySymbolTransmitEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_FlexraySymbolTransmitEvent cEvent; + SilKit_Struct_Init(SilKit_FlexraySymbolTransmitEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_FlexRayEventProducer_Produce(_flexRayEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void FlexRayEventProducer::Produce( + const SilKit::Services::Flexray::FlexrayCycleStartEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_FlexrayCycleStartEvent cEvent; + SilKit_Struct_Init(SilKit_FlexrayCycleStartEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_FlexRayEventProducer_Produce(_flexRayEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void FlexRayEventProducer::Produce( + const SilKit::Services::Flexray::FlexrayPocStatusEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_FlexrayPocStatusEvent cEvent; + SilKit_Struct_Init(SilKit_FlexrayPocStatusEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_FlexRayEventProducer_Produce(_flexRayEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +// -------------------------------- +// Ethernet +// -------------------------------- + +EthernetEventProducer::EthernetEventProducer(SilKit_Experimental_EthernetEventProducer* ethernetEventProducer) + : _ethernetEventProducer{ethernetEventProducer} +{ +} + +void EthernetEventProducer::Produce( + const SilKit::Services::Ethernet::EthernetFrameEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_EthernetFrameEvent cEvent; + SilKit_Struct_Init(SilKit_EthernetFrameEvent, cEvent); + + SilKit_EthernetFrame ethFrame; + SilKit_Struct_Init(SilKit_EthernetFrame, ethFrame); + cEvent.ethernetFrame = ðFrame; + + assignCxxToC(cxxEvent, cEvent); + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_EthernetEventProducer_Produce(_ethernetEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void EthernetEventProducer::Produce( + const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_EthernetFrameTransmitEvent cEvent; + SilKit_Struct_Init(SilKit_EthernetFrameTransmitEvent, cEvent); + + assignCxxToC(cxxEvent, cEvent); + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_EthernetEventProducer_Produce(_ethernetEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void EthernetEventProducer::Produce( + const SilKit::Services::Ethernet::EthernetStateChangeEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_EthernetStateChangeEvent cEvent; + SilKit_Struct_Init(SilKit_EthernetStateChangeEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_EthernetEventProducer_Produce(_ethernetEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void EthernetEventProducer::Produce( + const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_EthernetBitrateChangeEvent cEvent; + SilKit_Struct_Init(SilKit_EthernetBitrateChangeEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_EthernetEventProducer_Produce(_ethernetEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +// -------------------------------- +// Lin +// -------------------------------- + +LinEventProducer::LinEventProducer(SilKit_Experimental_LinEventProducer* linEventProducer) + : _linEventProducer{linEventProducer} +{ +} + +void LinEventProducer::Produce( + const SilKit::Services::Lin::LinFrameStatusEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_LinFrame cFrame; + SilKit_Struct_Init(SilKit_LinFrame, cFrame); + + SilKit_LinFrameStatusEvent cEvent; + SilKit_Struct_Init(SilKit_LinFrameStatusEvent, cEvent); + cEvent.frame = &cFrame; + + assignCxxToC(cxxEvent, cEvent); + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_LinEventProducer_Produce(_linEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void LinEventProducer::Produce( + const SilKit::Services::Lin::LinSendFrameHeaderRequest& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_LinSendFrameHeaderRequest cEvent; + SilKit_Struct_Init(SilKit_LinSendFrameHeaderRequest, cEvent); + assignCxxToC(cxxEvent, cEvent); + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_LinEventProducer_Produce(_linEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +void LinEventProducer::Produce( + const SilKit::Services::Lin::LinWakeupEvent& cxxEvent, + const SilKit::Util::Span& cxxReceivers) +{ + SilKit_LinWakeupEvent cEvent; + SilKit_Struct_Init(SilKit_LinWakeupEvent, cEvent); + assignCxxToC(cxxEvent, cEvent); + SilKit_Experimental_EventReceivers receivers = assignReceivers(cxxReceivers); + + const auto returnCode = + SilKit_Experimental_LinEventProducer_Produce(_linEventProducer, &cEvent.structHeader, &receivers); + ThrowOnError(returnCode); +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace Impl +DETAIL_SILKIT_DETAIL_VN_NAMESPACE_CLOSE +} // namespace SilKit diff --git a/SilKit/include/silkit/detail/impl/netsim/NetworkSimulator.hpp b/SilKit/include/silkit/detail/impl/netsim/NetworkSimulator.hpp new file mode 100644 index 000000000..7f7ddf461 --- /dev/null +++ b/SilKit/include/silkit/detail/impl/netsim/NetworkSimulator.hpp @@ -0,0 +1,414 @@ +// SPDX-FileCopyrightText: 2023 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "silkit/capi/NetworkSimulator.h" +#include "silkit/experimental/netsim/INetworkSimulator.hpp" +#include "silkit/experimental/netsim/string_utils.hpp" + +#include "silkit/detail/impl/HourglassConversions.hpp" +#include "silkit/detail/impl/ThrowOnError.hpp" + +#include "EventProducer.hpp" + +namespace SilKit { +DETAIL_SILKIT_DETAIL_VN_NAMESPACE_BEGIN +namespace Impl { +namespace Experimental { +namespace NetworkSimulation { + +// -------------------------------- +// CAN +// -------------------------------- + +inline auto MakeSimulatedCanControllerFunctions() -> SilKit_Experimental_SimulatedCanControllerFunctions +{ + SilKit_Experimental_SimulatedCanControllerFunctions functions; + SilKit_Struct_Init(SilKit_Experimental_SimulatedCanControllerFunctions, functions); + + functions.OnFrameRequest = [](void* controller, const SilKit_Experimental_NetSim_CanFrameRequest* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Can::CanFrameRequest cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnFrameRequest(std::move(cxxMsg)); + }; + + functions.OnSetBaudrate = [](void* controller, const SilKit_Experimental_NetSim_CanConfigureBaudrate* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Can::CanConfigureBaudrate cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnSetBaudrate(std::move(cxxMsg)); + }; + + functions.OnSetControllerMode = [](void* controller, const SilKit_Experimental_NetSim_CanControllerMode* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Can::CanControllerMode cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnSetControllerMode(std::move(cxxMsg)); + }; + + return functions; +} + +// -------------------------------- +// FlexRay +// -------------------------------- + +inline auto MakeSimulatedFlexRayControllerFunctions() -> SilKit_Experimental_SimulatedFlexRayControllerFunctions +{ + SilKit_Experimental_SimulatedFlexRayControllerFunctions functions; + SilKit_Struct_Init(SilKit_Experimental_SimulatedFlexRayControllerFunctions, functions); + + functions.OnHostCommand = [](void* controller, const SilKit_Experimental_NetSim_FlexrayHostCommand* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayHostCommand cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnHostCommand(std::move(cxxMsg)); + }; + + functions.OnControllerConfig = [](void* controller, + const SilKit_Experimental_NetSim_FlexrayControllerConfig* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayControllerConfig cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnControllerConfig(std::move(cxxMsg)); + }; + + functions.OnTxBufferConfigUpdate = [](void* controller, + const SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferConfigUpdate cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnTxBufferConfigUpdate(std::move(cxxMsg)); + }; + + functions.OnTxBufferUpdate = [](void* controller, const SilKit_Experimental_NetSim_FlexrayTxBufferUpdate* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Flexray::FlexrayTxBufferUpdate cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnTxBufferUpdate(std::move(cxxMsg)); + }; + + return functions; +} + +// -------------------------------- +// Ethernet +// -------------------------------- + +inline auto MakeSimulatedEthernetControllerFunctions() -> SilKit_Experimental_SimulatedEthernetControllerFunctions +{ + SilKit_Experimental_SimulatedEthernetControllerFunctions functions; + SilKit_Struct_Init(SilKit_Experimental_SimulatedEthernetControllerFunctions, functions); + + functions.OnFrameRequest = [](void* controller, const SilKit_Experimental_NetSim_EthernetFrameRequest* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Ethernet::EthernetFrameRequest cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnFrameRequest(std::move(cxxMsg)); + }; + + functions.OnSetControllerMode = [](void* controller, + const SilKit_Experimental_NetSim_EthernetControllerMode* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Ethernet::EthernetControllerMode cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnSetControllerMode(std::move(cxxMsg)); + }; + + return functions; +} + +// -------------------------------- +// Lin +// -------------------------------- + +inline auto MakeSimulatedLinControllerFunctions() -> SilKit_Experimental_SimulatedLinControllerFunctions +{ + SilKit_Experimental_SimulatedLinControllerFunctions functions; + SilKit_Struct_Init(SilKit_Experimental_SimulatedLinControllerFunctions, functions); + + functions.OnFrameRequest = [](void* controller, const SilKit_Experimental_NetSim_LinFrameRequest* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Lin::LinFrameRequest cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnFrameRequest(std::move(cxxMsg)); + }; + + functions.OnFrameHeaderRequest = [](void* controller, + const SilKit_Experimental_NetSim_LinFrameHeaderRequest* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Lin::LinFrameHeaderRequest cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnFrameHeaderRequest(std::move(cxxMsg)); + }; + + functions.OnWakeupPulse = [](void* controller, const SilKit_Experimental_NetSim_LinWakeupPulse* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Lin::LinWakeupPulse cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnWakeupPulse(std::move(cxxMsg)); + }; + + functions.OnControllerConfig = [](void* controller, const SilKit_Experimental_NetSim_LinControllerConfig* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Lin::LinControllerConfig cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnControllerConfig(std::move(cxxMsg)); + }; + + functions.OnFrameResponseUpdate = [](void* controller, + const SilKit_Experimental_NetSim_LinFrameResponseUpdate* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Lin::LinFrameResponseUpdate cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnFrameResponseUpdate(std::move(cxxMsg)); + }; + + functions.OnControllerStatusUpdate = [](void* controller, + const SilKit_Experimental_NetSim_LinControllerStatusUpdate* cMsg) { + auto cppSimulatedController = + static_cast(controller); + SilKit::Experimental::NetworkSimulation::Lin::LinControllerStatusUpdate cxxMsg{}; + assignCToCxx(cMsg, cxxMsg); + cppSimulatedController->OnControllerStatusUpdate(std::move(cxxMsg)); + }; + + return functions; +} + +// -------------------------------- +// SimulatedNetwork +// -------------------------------- + +inline auto MakeSimulatedNetworkFunctions(SilKit::Experimental::NetworkSimulation::SimulatedNetworkType networkType) + -> SilKit_Experimental_SimulatedNetworkFunctions +{ + SilKit_Experimental_SimulatedNetworkFunctions functions; + SilKit_Struct_Init(SilKit_Experimental_SimulatedNetworkFunctions, functions); + switch (networkType) + { + case SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::CAN: + functions.ProvideSimulatedController = + [](void** outSimulatedController, const void** outSimulatedControllerFunctions, + SilKit_Experimental_ControllerDescriptor controllerDescriptor, void* simulatedNetwork) { + static const auto userSimulatedCanControllerFunctions = MakeSimulatedCanControllerFunctions(); + *outSimulatedControllerFunctions = &userSimulatedCanControllerFunctions; + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + auto cppUserSimulatedController = cppUserSimulatedNetwork->ProvideSimulatedController(controllerDescriptor); + *outSimulatedController = static_cast(cppUserSimulatedController); + }; + functions.SetEventProducer = [](void* eventProducer, void* simulatedNetwork) { + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + auto cppEventProducer = + std::make_unique(static_cast(eventProducer)); + cppUserSimulatedNetwork->SetEventProducer(std::move(cppEventProducer)); + }; + break; + case SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::FlexRay: + functions.ProvideSimulatedController = + [](void** outSimulatedController, const void** outSimulatedControllerFunctions, + SilKit_Experimental_ControllerDescriptor controllerDescriptor, void* simulatedNetwork) { + static const auto userSimulatedFlexRayControllerFunctions = MakeSimulatedFlexRayControllerFunctions(); + *outSimulatedControllerFunctions = &userSimulatedFlexRayControllerFunctions; + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + auto cppUserSimulatedController = cppUserSimulatedNetwork->ProvideSimulatedController(controllerDescriptor); + *outSimulatedController = static_cast(cppUserSimulatedController); + }; + functions.SetEventProducer = [](void* eventProducer, void* simulatedNetwork) { + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + auto cppEventProducer = std::make_unique( + static_cast(eventProducer)); + cppUserSimulatedNetwork->SetEventProducer(std::move(cppEventProducer)); + }; + break; + case SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::Ethernet: + functions.ProvideSimulatedController = [](void** outSimulatedController, + const void** outSimulatedControllerFunctions, + SilKit_Experimental_ControllerDescriptor controllerDescriptor, + + void* simulatedNetwork) { + static const auto userSimulatedEthernetControllerFunctions = MakeSimulatedEthernetControllerFunctions(); + *outSimulatedControllerFunctions = &userSimulatedEthernetControllerFunctions; + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + auto cppUserSimulatedController = cppUserSimulatedNetwork->ProvideSimulatedController(controllerDescriptor); + *outSimulatedController = static_cast(cppUserSimulatedController); + }; + functions.SetEventProducer = [](void* eventProducer, void* simulatedNetwork) { + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + auto cppEventProducer = std::make_unique( + static_cast(eventProducer)); + cppUserSimulatedNetwork->SetEventProducer(std::move(cppEventProducer)); + }; + break; + case SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::LIN: + functions.ProvideSimulatedController = [](void** outSimulatedController, + const void** outSimulatedControllerFunctions, + SilKit_Experimental_ControllerDescriptor controllerDescriptor, + + void* simulatedNetwork) { + static const auto userSimulatedLinControllerFunctions = MakeSimulatedLinControllerFunctions(); + *outSimulatedControllerFunctions = &userSimulatedLinControllerFunctions; + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + auto cppUserSimulatedController = cppUserSimulatedNetwork->ProvideSimulatedController(controllerDescriptor); + *outSimulatedController = static_cast(cppUserSimulatedController); + }; + functions.SetEventProducer = [](void* eventProducer, void* simulatedNetwork) { + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + auto cppEventProducer = + std::make_unique(static_cast(eventProducer)); + cppUserSimulatedNetwork->SetEventProducer(std::move(cppEventProducer)); + }; + break; + default: + break; + } + + // Functions not depending on the network type + + functions.SimulatedControllerRemoved = [](SilKit_Experimental_ControllerDescriptor controllerDescriptor, + void* simulatedNetwork) { + auto* cppUserSimulatedNetwork = + static_cast(simulatedNetwork); + cppUserSimulatedNetwork->SimulatedControllerRemoved(controllerDescriptor); + }; + + return functions; +} + +// -------------------------------- +// NetworkSimulator +// -------------------------------- + +class NetworkSimulator : public SilKit::Experimental::NetworkSimulation::INetworkSimulator +{ +public: + inline explicit NetworkSimulator(SilKit_Participant* participant); + + // INetworkSimulator + inline void SimulateNetwork( + const std::string& networkName, SilKit::Experimental::NetworkSimulation::SimulatedNetworkType networkType, + std::unique_ptr simulatedNetwork) override; + + inline void Start() override; + +private: + SilKit_Experimental_NetworkSimulator* _networkSimulator{nullptr}; + + using SimulatedNetworksByNetworkName = + std::unordered_map>; + using SimulatedNetworksByTypeAndNetworkName = + std::unordered_map; + SimulatedNetworksByTypeAndNetworkName _simulatedNetworks; +}; + +NetworkSimulator::NetworkSimulator(SilKit_Participant* participant) +{ + const auto returnCode = SilKit_Experimental_NetworkSimulator_Create(&_networkSimulator, participant); + ThrowOnError(returnCode); +} + +void NetworkSimulator::SimulateNetwork( + const std::string& networkName, SilKit::Experimental::NetworkSimulation::SimulatedNetworkType networkType, + std::unique_ptr simulatedNetwork) +{ + if (simulatedNetwork == nullptr) + { + const std::string errorMsg = "NetworkSimulation: Provided simulated network must not be null."; + throw SilKitError{errorMsg}; + } + + auto userSimulatedNetwork = simulatedNetwork.get(); + + auto networksOfType_it = _simulatedNetworks.find(networkType); + if (networksOfType_it != _simulatedNetworks.end()) + { + auto simulatedNetwork_it = networksOfType_it->second.find(networkName); + if (simulatedNetwork_it != networksOfType_it->second.end()) + { + const std::string errorMsg = + "Network '" + networkName + "' of type " + to_string(networkType) + " is already simulated."; + throw SilKitError{errorMsg}; + } + } + _simulatedNetworks[networkType][networkName] = std::move(simulatedNetwork); + + auto returnCode = SilKit_ReturnCode_SUCCESS; + + switch (networkType) + { + case SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::CAN: + const static auto userSimulatedCanNetworkFunctions = + MakeSimulatedNetworkFunctions(SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::CAN); + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork( + _networkSimulator, networkName.c_str(), static_cast(networkType), + userSimulatedNetwork, &userSimulatedCanNetworkFunctions); + break; + case SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::FlexRay: + const static auto userSimulatedFlexRayNetworkFunctions = + MakeSimulatedNetworkFunctions(SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::FlexRay); + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork( + _networkSimulator, networkName.c_str(), static_cast(networkType), + userSimulatedNetwork, &userSimulatedFlexRayNetworkFunctions); + break; + case SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::Ethernet: + const static auto userSimulatedEthernetNetworkFunctions = + MakeSimulatedNetworkFunctions(SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::Ethernet); + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork( + _networkSimulator, networkName.c_str(), static_cast(networkType), + userSimulatedNetwork, &userSimulatedEthernetNetworkFunctions); + break; + case SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::LIN: + const static auto userSimulatedLinNetworkFunctions = + MakeSimulatedNetworkFunctions(SilKit::Experimental::NetworkSimulation::SimulatedNetworkType::LIN); + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork( + _networkSimulator, networkName.c_str(), static_cast(networkType), + userSimulatedNetwork, &userSimulatedLinNetworkFunctions); + break; + + default: + break; + } + + ThrowOnError(returnCode); +} + +void NetworkSimulator::Start() +{ + const auto returnCode = SilKit_Experimental_NetworkSimulator_Start(_networkSimulator); + ThrowOnError(returnCode); +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace Impl +DETAIL_SILKIT_DETAIL_VN_NAMESPACE_CLOSE +} // namespace SilKit diff --git a/SilKit/include/silkit/detail/impl/participant/Participant.hpp b/SilKit/include/silkit/detail/impl/participant/Participant.hpp index 239963004..a849ee248 100644 --- a/SilKit/include/silkit/detail/impl/participant/Participant.hpp +++ b/SilKit/include/silkit/detail/impl/participant/Participant.hpp @@ -51,6 +51,7 @@ #include "silkit/detail/impl/experimental/services/orchestration/SystemController.hpp" +#include "silkit/detail/impl/netsim/NetworkSimulator.hpp" namespace SilKit { DETAIL_SILKIT_DETAIL_VN_NAMESPACE_BEGIN @@ -63,8 +64,8 @@ class Participant : public SilKit::IParticipant inline ~Participant() override; - inline auto CreateCanController(const std::string& canonicalName, const std::string& networkName) - -> SilKit::Services::Can::ICanController* override; + inline auto CreateCanController(const std::string& canonicalName, + const std::string& networkName) -> SilKit::Services::Can::ICanController* override; inline auto CreateEthernetController(const std::string& canonicalName, const std::string& networkName) -> SilKit::Services::Ethernet::IEthernetController* override; @@ -72,22 +73,25 @@ class Participant : public SilKit::IParticipant inline auto CreateFlexrayController(const std::string& canonicalName, const std::string& networkName) -> SilKit::Services::Flexray::IFlexrayController* override; - inline auto CreateLinController(const std::string& canonicalName, const std::string& networkName) - -> SilKit::Services::Lin::ILinController* override; + inline auto CreateLinController(const std::string& canonicalName, + const std::string& networkName) -> SilKit::Services::Lin::ILinController* override; - inline auto CreateDataPublisher(const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, - size_t history) -> SilKit::Services::PubSub::IDataPublisher* override; + inline auto CreateDataPublisher(const std::string& canonicalName, + const SilKit::Services::PubSub::PubSubSpec& dataSpec, + size_t history) -> SilKit::Services::PubSub::IDataPublisher* override; - inline auto CreateDataSubscriber(const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, - SilKit::Services::PubSub::DataMessageHandler dataMessageHandler) + inline auto CreateDataSubscriber(const std::string& canonicalName, + const SilKit::Services::PubSub::PubSubSpec& dataSpec, + SilKit::Services::PubSub::DataMessageHandler dataMessageHandler) -> SilKit::Services::PubSub::IDataSubscriber* override; inline auto CreateRpcClient(const std::string& canonicalName, const SilKit::Services::Rpc::RpcSpec& dataSpec, - SilKit::Services::Rpc::RpcCallResultHandler handler) + SilKit::Services::Rpc::RpcCallResultHandler handler) -> SilKit::Services::Rpc::IRpcClient* override; inline auto CreateRpcServer(const std::string& canonicalName, const SilKit::Services::Rpc::RpcSpec& dataSpec, - SilKit::Services::Rpc::RpcCallHandler handler) -> SilKit::Services::Rpc::IRpcServer* override; + SilKit::Services::Rpc::RpcCallHandler handler) + -> SilKit::Services::Rpc::IRpcServer* override; inline auto CreateLifecycleService(SilKit::Services::Orchestration::LifecycleConfiguration startConfiguration) -> SilKit::Services::Orchestration::ILifecycleService* override; @@ -96,7 +100,8 @@ class Participant : public SilKit::IParticipant inline auto GetLogger() -> SilKit::Services::Logging::ILogger* override; -public: + inline auto ExperimentalCreateNetworkSimulator() -> SilKit::Experimental::NetworkSimulation::INetworkSimulator*; + inline auto ExperimentalCreateSystemController() -> SilKit::Experimental::Services::Orchestration::ISystemController*; @@ -134,6 +139,8 @@ class Participant : public SilKit::IParticipant std::unique_ptr _systemController; std::unique_ptr _logger; + + std::unique_ptr _networkSimulator; }; } // namespace Impl @@ -163,8 +170,8 @@ Participant::~Participant() } } -auto Participant::CreateCanController(const std::string& canonicalName, const std::string& networkName) - -> SilKit::Services::Can::ICanController* +auto Participant::CreateCanController(const std::string& canonicalName, + const std::string& networkName) -> SilKit::Services::Can::ICanController* { return _canControllers.Create(_participant, canonicalName, networkName); } @@ -181,23 +188,22 @@ auto Participant::CreateFlexrayController(const std::string& canonicalName, cons return _flexrayControllers.Create(_participant, canonicalName, networkName); } -auto Participant::CreateLinController(const std::string& canonicalName, const std::string& networkName) - -> SilKit::Services::Lin::ILinController* +auto Participant::CreateLinController(const std::string& canonicalName, + const std::string& networkName) -> SilKit::Services::Lin::ILinController* { return _linControllers.Create(_participant, canonicalName, networkName); } auto Participant::CreateDataPublisher(const std::string& canonicalName, - const SilKit::Services::PubSub::PubSubSpec& dataSpec, size_t history) - -> SilKit::Services::PubSub::IDataPublisher* + const SilKit::Services::PubSub::PubSubSpec& dataSpec, + size_t history) -> SilKit::Services::PubSub::IDataPublisher* { return _dataPublishers.Create(_participant, canonicalName, dataSpec, static_cast(history & 0xff)); } -auto Participant::CreateDataSubscriber(const std::string& canonicalName, - const SilKit::Services::PubSub::PubSubSpec& dataSpec, - SilKit::Services::PubSub::DataMessageHandler dataMessageHandler) - -> SilKit::Services::PubSub::IDataSubscriber* +auto Participant::CreateDataSubscriber( + const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, + SilKit::Services::PubSub::DataMessageHandler dataMessageHandler) -> SilKit::Services::PubSub::IDataSubscriber* { return _dataSubscribers.Create(_participant, canonicalName, dataSpec, std::move(dataMessageHandler)); } @@ -243,6 +249,13 @@ auto Participant::ExperimentalCreateSystemController() return _systemController.get(); } +auto Participant::ExperimentalCreateNetworkSimulator() -> SilKit::Experimental::NetworkSimulation::INetworkSimulator* +{ + _networkSimulator = std::make_unique(_participant); + + return _networkSimulator.get(); +} + auto Participant::Get() const -> SilKit_Participant* { return _participant; diff --git a/SilKit/include/silkit/detail/impl/services/can/CanController.hpp b/SilKit/include/silkit/detail/impl/services/can/CanController.hpp index a476d2963..676e8983d 100644 --- a/SilKit/include/silkit/detail/impl/services/can/CanController.hpp +++ b/SilKit/include/silkit/detail/impl/services/can/CanController.hpp @@ -54,8 +54,8 @@ class CanController : public SilKit::Services::Can::ICanController inline void SendFrame(const SilKit::Services::Can::CanFrame &msg, void *userContext) override; - inline auto AddFrameHandler(FrameHandler handler, SilKit::Services::DirectionMask directionMask) - -> Util::HandlerId override; + inline auto AddFrameHandler(FrameHandler handler, + SilKit::Services::DirectionMask directionMask) -> Util::HandlerId override; inline void RemoveFrameHandler(Util::HandlerId handlerId) override; @@ -171,8 +171,8 @@ void CanController::SendFrame(const SilKit::Services::Can::CanFrame &msg, void * ThrowOnError(returnCode); } -auto CanController::AddFrameHandler(FrameHandler handler, SilKit::Services::DirectionMask directionMask) - -> Util::HandlerId +auto CanController::AddFrameHandler(FrameHandler handler, + SilKit::Services::DirectionMask directionMask) -> Util::HandlerId { const auto cHandler = [](void *context, SilKit_CanController *controller, SilKit_CanFrameEvent *frameEvent) { SILKIT_UNUSED_ARG(controller); diff --git a/SilKit/include/silkit/detail/impl/services/ethernet/EthernetController.hpp b/SilKit/include/silkit/detail/impl/services/ethernet/EthernetController.hpp index d33132b71..99bb9ca38 100644 --- a/SilKit/include/silkit/detail/impl/services/ethernet/EthernetController.hpp +++ b/SilKit/include/silkit/detail/impl/services/ethernet/EthernetController.hpp @@ -46,8 +46,8 @@ class EthernetController : public SilKit::Services::Ethernet::IEthernetControlle inline void Deactivate() override; - inline auto AddFrameHandler(FrameHandler handler, SilKit::Services::DirectionMask directionMask) - -> Util::HandlerId override; + inline auto AddFrameHandler(FrameHandler handler, + SilKit::Services::DirectionMask directionMask) -> Util::HandlerId override; inline void RemoveFrameHandler(Util::HandlerId handlerId) override; @@ -127,8 +127,8 @@ void EthernetController::Deactivate() ThrowOnError(returnCode); } -auto EthernetController::AddFrameHandler(FrameHandler handler, SilKit::Services::DirectionMask directionMask) - -> Util::HandlerId +auto EthernetController::AddFrameHandler(FrameHandler handler, + SilKit::Services::DirectionMask directionMask) -> Util::HandlerId { const auto cHandler = [](void *context, SilKit_EthernetController *controller, SilKit_EthernetFrameEvent *frameEvent) { @@ -169,8 +169,8 @@ void EthernetController::RemoveFrameHandler(Util::HandlerId handlerId) } auto EthernetController::AddFrameTransmitHandler( - FrameTransmitHandler handler, SilKit::Services::Ethernet::EthernetTransmitStatusMask transmitStatusMask) - -> Util::HandlerId + FrameTransmitHandler handler, + SilKit::Services::Ethernet::EthernetTransmitStatusMask transmitStatusMask) -> Util::HandlerId { const auto cHandler = [](void *context, SilKit_EthernetController *controller, SilKit_EthernetFrameTransmitEvent *frameTransmitEvent) { diff --git a/SilKit/include/silkit/detail/impl/services/lin/LinController.hpp b/SilKit/include/silkit/detail/impl/services/lin/LinController.hpp index 7eca73dd4..bd2f1a220 100644 --- a/SilKit/include/silkit/detail/impl/services/lin/LinController.hpp +++ b/SilKit/include/silkit/detail/impl/services/lin/LinController.hpp @@ -85,13 +85,15 @@ class LinController : public SilKit::Services::Lin::ILinController inline auto ExperimentalGetSlaveConfiguration() -> SilKit::Experimental::Services::Lin::LinSlaveConfiguration; - inline void ExperimentalInitDynamic(const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig); + inline void ExperimentalInitDynamic( + const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig &dynamicConfig); - inline auto ExperimentalAddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) -> Util::HandlerId; + inline auto ExperimentalAddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) + -> Util::HandlerId; inline void ExperimentalRemoveFrameHeaderHandler(Util::HandlerId handlerId); - inline void ExperimentalSendDynamicResponse(const SilKit::Services::Lin::LinFrame& linFrame); + inline void ExperimentalSendDynamicResponse(const SilKit::Services::Lin::LinFrame &linFrame); private: template @@ -159,22 +161,21 @@ void LinController::Init(SilKit::Services::Lin::LinControllerConfig config) std::vector frameResponses; std::transform(config.frameResponses.begin(), config.frameResponses.end(), std::back_inserter(frameResponses), [&frames](const SilKit::Services::Lin::LinFrameResponse &frameResponse) -> SilKit_LinFrameResponse { - frames.emplace_back(); - - SilKit_LinFrame &cFrame = frames.back(); - SilKit_Struct_Init(SilKit_LinFrame, cFrame); - cFrame.id = frameResponse.frame.id; - cFrame.checksumModel = static_cast(frameResponse.frame.checksumModel); - cFrame.dataLength = frameResponse.frame.dataLength; - std::copy_n(frameResponse.frame.data.data(), frameResponse.frame.data.size(), cFrame.data); - - SilKit_LinFrameResponse cFrameResponse; - SilKit_Struct_Init(SilKit_LinFrameResponse, cFrameResponse); - cFrameResponse.frame = &cFrame; - cFrameResponse.responseMode = - static_cast(frameResponse.responseMode); - return cFrameResponse; - }); + frames.emplace_back(); + + SilKit_LinFrame &cFrame = frames.back(); + SilKit_Struct_Init(SilKit_LinFrame, cFrame); + cFrame.id = frameResponse.frame.id; + cFrame.checksumModel = static_cast(frameResponse.frame.checksumModel); + cFrame.dataLength = frameResponse.frame.dataLength; + std::copy_n(frameResponse.frame.data.data(), frameResponse.frame.data.size(), cFrame.data); + + SilKit_LinFrameResponse cFrameResponse; + SilKit_Struct_Init(SilKit_LinFrameResponse, cFrameResponse); + cFrameResponse.frame = &cFrame; + cFrameResponse.responseMode = static_cast(frameResponse.responseMode); + return cFrameResponse; + }); SilKit_LinControllerConfig linControllerConfig; SilKit_Struct_Init(SilKit_LinControllerConfig, linControllerConfig); @@ -417,8 +418,8 @@ auto LinController::ExperimentalAddLinSlaveConfigurationHandler( void LinController::ExperimentalRemoveLinSlaveConfigurationHandler(SilKit::Util::HandlerId handlerId) { - const auto returnCode = - SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler(_linController, static_cast(handlerId)); + const auto returnCode = SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler( + _linController, static_cast(handlerId)); ThrowOnError(returnCode); _wakeupHandlers.erase(handlerId); @@ -429,10 +430,12 @@ auto LinController::ExperimentalGetSlaveConfiguration() -> SilKit::Experimental: SilKit_Experimental_LinSlaveConfiguration cSlaveConfiguration; SilKit_Struct_Init(SilKit_Experimental_LinSlaveConfiguration, cSlaveConfiguration); - const auto returnCode = SilKit_Experimental_LinController_GetSlaveConfiguration(_linController, &cSlaveConfiguration); + const auto returnCode = + SilKit_Experimental_LinController_GetSlaveConfiguration(_linController, &cSlaveConfiguration); ThrowOnError(returnCode); - constexpr size_t count = sizeof(cSlaveConfiguration.isLinIdResponding) / sizeof(cSlaveConfiguration.isLinIdResponding[0]); + constexpr size_t count = + sizeof(cSlaveConfiguration.isLinIdResponding) / sizeof(cSlaveConfiguration.isLinIdResponding[0]); SilKit::Experimental::Services::Lin::LinSlaveConfiguration cppSlaveConfiguration{}; for (size_t index = 0; index != count; ++index) @@ -446,7 +449,8 @@ auto LinController::ExperimentalGetSlaveConfiguration() -> SilKit::Experimental: return cppSlaveConfiguration; } -void LinController::ExperimentalInitDynamic(const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig) +void LinController::ExperimentalInitDynamic( + const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig &dynamicConfig) { SilKit_Experimental_LinControllerDynamicConfig cConfig; SilKit_Struct_Init(SilKit_Experimental_LinControllerDynamicConfig, cConfig); @@ -457,7 +461,8 @@ void LinController::ExperimentalInitDynamic(const SilKit::Experimental::Services ThrowOnError(returnCode); } -auto LinController::ExperimentalAddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) -> Util::HandlerId +auto LinController::ExperimentalAddFrameHeaderHandler( + SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) -> Util::HandlerId { const auto cHandler = [](void *context, SilKit_LinController *controller, const SilKit_Experimental_LinFrameHeaderEvent *headerEvent) { @@ -467,7 +472,8 @@ auto LinController::ExperimentalAddFrameHeaderHandler(SilKit::Experimental::Serv event.timestamp = std::chrono::nanoseconds{headerEvent->timestamp}; event.id = static_cast(headerEvent->id); - const auto data = static_cast *>(context); + const auto data = + static_cast *>(context); data->handler(data->controller, event); }; @@ -477,8 +483,8 @@ auto LinController::ExperimentalAddFrameHeaderHandler(SilKit::Experimental::Serv handlerData->controller = this; handlerData->handler = std::move(handler); - const auto returnCode = - SilKit_Experimental_LinController_AddFrameHeaderHandler(_linController, handlerData.get(), cHandler, &handlerId); + const auto returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler(_linController, handlerData.get(), + cHandler, &handlerId); ThrowOnError(returnCode); _frameHeaderHandlers.emplace(static_cast(handlerId), std::move(handlerData)); @@ -488,14 +494,14 @@ auto LinController::ExperimentalAddFrameHeaderHandler(SilKit::Experimental::Serv void LinController::ExperimentalRemoveFrameHeaderHandler(Util::HandlerId handlerId) { - const auto returnCode = - SilKit_Experimental_LinController_RemoveFrameHeaderHandler(_linController, static_cast(handlerId)); + const auto returnCode = SilKit_Experimental_LinController_RemoveFrameHeaderHandler( + _linController, static_cast(handlerId)); ThrowOnError(returnCode); _frameHeaderHandlers.erase(handlerId); } -void LinController::ExperimentalSendDynamicResponse(const SilKit::Services::Lin::LinFrame& linFrame) +void LinController::ExperimentalSendDynamicResponse(const SilKit::Services::Lin::LinFrame &linFrame) { SilKit_LinFrame cLinFrame; CxxToC(linFrame, cLinFrame); diff --git a/SilKit/include/silkit/detail/impl/services/orchestration/LifecycleService.hpp b/SilKit/include/silkit/detail/impl/services/orchestration/LifecycleService.hpp index 9048e19f7..77ab17b95 100644 --- a/SilKit/include/silkit/detail/impl/services/orchestration/LifecycleService.hpp +++ b/SilKit/include/silkit/detail/impl/services/orchestration/LifecycleService.hpp @@ -47,13 +47,15 @@ class LifecycleService : public SilKit::Services::Orchestration::ILifecycleServi public: inline explicit LifecycleService(SilKit_Participant *participant, - SilKit::Services::Orchestration::LifecycleConfiguration startConfiguration); + SilKit::Services::Orchestration::LifecycleConfiguration startConfiguration); inline ~LifecycleService() override = default; - inline void SetCommunicationReadyHandler(SilKit::Services::Orchestration::CommunicationReadyHandler handler) override; + inline void SetCommunicationReadyHandler( + SilKit::Services::Orchestration::CommunicationReadyHandler handler) override; - inline void SetCommunicationReadyHandlerAsync(SilKit::Services::Orchestration::CommunicationReadyHandler handler) override; + inline void SetCommunicationReadyHandlerAsync( + SilKit::Services::Orchestration::CommunicationReadyHandler handler) override; inline void CompleteCommunicationReadyHandlerAsync() override; diff --git a/SilKit/include/silkit/detail/impl/services/orchestration/TimeSyncService.hpp b/SilKit/include/silkit/detail/impl/services/orchestration/TimeSyncService.hpp index 50c4f2982..9fb4681e4 100644 --- a/SilKit/include/silkit/detail/impl/services/orchestration/TimeSyncService.hpp +++ b/SilKit/include/silkit/detail/impl/services/orchestration/TimeSyncService.hpp @@ -42,7 +42,8 @@ class TimeSyncService : public SilKit::Services::Orchestration::ITimeSyncService inline void SetSimulationStepHandler(SimulationStepHandler task, std::chrono::nanoseconds initialStepSize) override; - inline void SetSimulationStepHandlerAsync(SimulationStepHandler task, std::chrono::nanoseconds initialStepSize) override; + inline void SetSimulationStepHandlerAsync(SimulationStepHandler task, + std::chrono::nanoseconds initialStepSize) override; inline void CompleteSimulationStep() override; diff --git a/SilKit/include/silkit/detail/impl/services/pubsub/MakePubSubSpecView.hpp b/SilKit/include/silkit/detail/impl/services/pubsub/MakePubSubSpecView.hpp index 09f0aa6a4..1adc7ac81 100644 --- a/SilKit/include/silkit/detail/impl/services/pubsub/MakePubSubSpecView.hpp +++ b/SilKit/include/silkit/detail/impl/services/pubsub/MakePubSubSpecView.hpp @@ -60,12 +60,12 @@ auto MakePubSubSpecView(const SilKit::Services::PubSub::PubSubSpec& pubSubSpec) std::vector labels; std::transform(pubSubSpec.Labels().begin(), pubSubSpec.Labels().end(), std::back_inserter(labels), [](const SilKit::Services::MatchingLabel& matchingLabel) -> SilKit_Label { - return { - matchingLabel.key.c_str(), - matchingLabel.value.c_str(), - static_cast(matchingLabel.kind), - }; - }); + return { + matchingLabel.key.c_str(), + matchingLabel.value.c_str(), + static_cast(matchingLabel.kind), + }; + }); return labels; } diff --git a/SilKit/include/silkit/detail/impl/services/rpc/MakeRpcSpecView.hpp b/SilKit/include/silkit/detail/impl/services/rpc/MakeRpcSpecView.hpp index 498759aaf..4e0cc7bce 100644 --- a/SilKit/include/silkit/detail/impl/services/rpc/MakeRpcSpecView.hpp +++ b/SilKit/include/silkit/detail/impl/services/rpc/MakeRpcSpecView.hpp @@ -60,12 +60,12 @@ inline auto MakeRpcSpecView(const SilKit::Services::Rpc::RpcSpec& rpcSpec) -> st std::vector labels; std::transform(rpcSpec.Labels().begin(), rpcSpec.Labels().end(), std::back_inserter(labels), [](const SilKit::Services::MatchingLabel& matchingLabel) -> SilKit_Label { - return { - matchingLabel.key.c_str(), - matchingLabel.value.c_str(), - static_cast(matchingLabel.kind), - }; - }); + return { + matchingLabel.key.c_str(), + matchingLabel.value.c_str(), + static_cast(matchingLabel.kind), + }; + }); return labels; } diff --git a/SilKit/include/silkit/detail/impl/services/rpc/RpcClient.hpp b/SilKit/include/silkit/detail/impl/services/rpc/RpcClient.hpp index a7b562451..55500073c 100644 --- a/SilKit/include/silkit/detail/impl/services/rpc/RpcClient.hpp +++ b/SilKit/include/silkit/detail/impl/services/rpc/RpcClient.hpp @@ -46,7 +46,7 @@ class RpcClient : public SilKit::Services::Rpc::IRpcClient inline void Call(SilKit::Util::Span data, void* userContext) override; inline void CallWithTimeout(SilKit::Util::Span data, std::chrono::nanoseconds timeout, - void* userContext) override; + void* userContext) override; inline void SetCallResultHandler(SilKit::Services::Rpc::RpcCallResultHandler handler) override; @@ -119,7 +119,8 @@ void RpcClient::Call(SilKit::Util::Span data, void* userContext) ThrowOnError(returnCode); } -void RpcClient::CallWithTimeout(SilKit::Util::Span data, std::chrono::nanoseconds duration, void* userContext) +void RpcClient::CallWithTimeout(SilKit::Util::Span data, std::chrono::nanoseconds duration, + void* userContext) { const auto cData = SilKit::Util::ToSilKitByteVector(data); diff --git a/SilKit/include/silkit/experimental/netsim/INetworkSimulator.hpp b/SilKit/include/silkit/experimental/netsim/INetworkSimulator.hpp new file mode 100644 index 000000000..5ee508f01 --- /dev/null +++ b/SilKit/include/silkit/experimental/netsim/INetworkSimulator.hpp @@ -0,0 +1,412 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include + +#include "NetworkSimulatorDatatypes.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +//! Base class of a simulated controller. +class ISimulatedController +{ +public: + virtual ~ISimulatedController() = default; +}; + +//! Base class of an event producer. +class IEventProducer +{ +public: + virtual ~IEventProducer() = default; +}; + +//! Interface for a simulated network. +//! An instance of a class inheriting from this interface is passed to the SIL Kit via \ref INetworkSimulator::SimulateNetwork. +//! The interface functions are then invoked by the SIL Kit. +class ISimulatedNetwork +{ +public: + virtual ~ISimulatedNetwork() = default; + + /*! \brief Called when the API requires the implementation of a simulated controller. + * This happens when a controller is created on a simulated network. + * The network must be registered via \ref SilKit::Experimental::NetworkSimulation::INetworkSimulator::SimulateNetwork beforehand. + * After a simulated controller is provided, messages sent by the original controller will triggers message specific callbacks on the simulated controller. + * \param controllerDescriptor The identifier of a remote controller. + * Used to address a specific controller as receiver when using the eventProducer. + * \return The implementation must return a valid pointer to a \ref SilKit::Experimental::NetworkSimulation::ISimulatedController. + * Note that this interface is abstract, the underlying class must inherit from the appropriate network-specific interface (e.g. \ref Can::ISimulatedCanController, \ref Flexray::ISimulatedFlexRayController, etc.). + */ + virtual auto ProvideSimulatedController(ControllerDescriptor controllerDescriptor) -> ISimulatedController* = 0; + + /*! \brief Deregistration of a simulated controller. + * Called when the participant that owns the controller leaves the simulation. + * \param controllerDescriptor The identifier of a remote controller. + */ + virtual void SimulatedControllerRemoved(ControllerDescriptor controllerDescriptor) = 0; + + /*! \brief Called once to provide an \ref SilKit::Experimental::NetworkSimulation::IEventProducer. + * This happens when the first controller appears on a simulated network. + * \param eventProducer Used to generate events for a given group of receivers. + Note that this interface is abstract, the object must be cast to the specific interface for the underlying network type (\ref Can::ICanEventProducer, \ref Flexray::IFlexRayEventProducer, etc.). + */ + virtual void SetEventProducer(std::unique_ptr eventProducer) = 0; +}; + +//! Network Simulator interface to register simulated networks and to start the network simulation. +//! A network simulator object can be obtained via \ref SilKit::Experimental::Participant::CreateNetworkSimulator. +//! Note that there can only be one network simulater per participant. +class INetworkSimulator +{ +public: + virtual ~INetworkSimulator() = default; + + /*! \brief Register a simulated network. + * The network of the given name and type is subject to a detailed simulation whose logic is provided by the custom network simulator. + * Controllers with the same network name and type will no longer broadcast their outgoing messages to other controllers. + * Instead, the traffic is routed to the network simulator participant and will arrive on a \ref ISimulatedController. + * Based on the incoming messages (e.g., a frame request), the simulation logic can be performed and outgoing events (e.g. acknowledgments, frames) can be produced. + * \param networkName The name of the simulated network. + * \param networkType The type of the simulated network. + * \param simulatedNetwork Provided \ref ISimulatedNetwork object to manage a simulated network. + When a controller appears on a simulated network, the \ref ISimulatedNetwork, which was passed as argument to this method, is informed with a call to \ref ISimulatedNetwork::ProvideSimulatedController. + * There, a specific \ref ISimulatedController (e.g. \ref Can::ISimulatedCanController, \ref Flexray::ISimulatedFlexRayController, etc.) can be provided to receive the messages sent by the original controller. + */ + virtual void SimulateNetwork(const std::string& networkName, SimulatedNetworkType networkType, + std::unique_ptr simulatedNetwork) = 0; + + /*! \brief Start the network simulation of all previously registered networks. + * Simulated networks registered via INetworkSimulator::SimulateNetwork will be informed about corresponding controllers in the simulation with calls to \ref ISimulatedNetwork::ProvideSimulatedController. + * This holds true for remote controllers that have been created before the call to \ref INetworkSimulator::Start. + * Internally, remote controllers are informed that they are now part of a detailed network simulation and will route their messages to the network simulator. + * See the documentation for further information about the usage within the SIL Kit Lifecyle in order not to miss any messages on the network simulator. + */ + virtual void Start() = 0; +}; + +namespace Can { + +/*! \brief API for simulated CAN controllers. + * If a new CAN controller is created on a simulated network, an implementation of this interface can be provided in \ref ISimulatedNetwork::ProvideSimulatedController. + * Messages generated by the original controller will be redirected to the simulated controller and trigger the On... callbacks. + */ +class ISimulatedCanController : public ISimulatedController +{ +public: + virtual ~ISimulatedCanController() = default; + + /*! \brief Incoming CAN controller message. + * Triggered when a CAN controller calls SilKit::Services::Can::ICanController::SetBaudRate(). + * \param canConfigureBaudrate The configured baud rate of the controller. + */ + virtual void OnSetBaudrate(const CanConfigureBaudrate& canConfigureBaudrate) = 0; + + /*! \brief Incoming CAN controller message. + * Triggered when a CAN controller calls \ref SilKit::Services::Can::ICanController::SendFrame(). + * \param canFrameRequest The CAN frame requested to be sent. + */ + virtual void OnFrameRequest(const CanFrameRequest& canFrameRequest) = 0; + + /*! \brief Incoming CAN controller message. + * Triggered when a CAN controller calls \ref SilKit::Services::Can::ICanController::Start(), \ref SilKit::Services::Can::ICanController::Stop(), \ref SilKit::Services::Can::ICanController::Sleep() or \ref SilKit::Services::Can::ICanController::Reset(). + * \param canControllerMode The new controller state. + */ + virtual void OnSetControllerMode(const CanControllerMode& canControllerMode) = 0; +}; + +//! Producer for CAN events. +//! Passed in \ref ISimulatedNetwork::SetEventProducer. +//! Messages can be produced for a given set of controllers, specified by a span of controller descriptors. +//! The individual controller descriptor of a remote controller is passed in \ref ISimulatedNetwork::ProvideSimulatedController. +class ICanEventProducer : public IEventProducer +{ +public: + virtual ~ICanEventProducer() = default; + + /*! \brief Produce a \ref SilKit::Services::Can::CanFrameEvent for a given set of receivers on this network. + * \param frameEvent The produced CAN event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Can::CanFrameEvent& frameEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Can::CanFrameTransmitEvent for a given set of receivers on this network. + * \param frameTransmitEvent The produced CAN event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Can::CanFrameTransmitEvent& frameTransmitEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Can::CanStateChangeEvent for a given set of receivers on this network. + * \param stateChangeEvent The produced CAN event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Can::CanStateChangeEvent& stateChangeEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Can::CanErrorStateChangeEvent for a given set of receivers on this network. + * \param errorStateChangeEvent The produced CAN event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Can::CanErrorStateChangeEvent& errorStateChangeEvent, + const SilKit::Util::Span& receivers) = 0; +}; + +} // namespace Can + +namespace Flexray { + +/*! \brief API for simulated FlexRay controllers. + * If a new FlexRay controller is created on a simulated network, an implementation of this interface can be provided in \ref ISimulatedNetwork::ProvideSimulatedController. + * Messages generated by the original controller will be redirected to the simulated controller and trigger the On... callbacks. + */ +class ISimulatedFlexRayController : public ISimulatedController +{ +public: + virtual ~ISimulatedFlexRayController() = default; + + /*! \brief Incoming FlexRay controller message. + * Triggered when a FlexRay controller calls SilKit::Services::Flexray::IFlexrayController::Run(), + SilKit::Services::Flexray::IFlexrayController::DeferredHalt(), + SilKit::Services::Flexray::IFlexrayController::Freeze(), + SilKit::Services::Flexray::IFlexrayController::AllowColdstart(), + SilKit::Services::Flexray::IFlexrayController::Wakeup() or + SilKit::Services::Flexray::IFlexrayController::AllSlots(). + * \param flexrayHostCommand An identifier of the host command. + */ + virtual void OnHostCommand(const FlexrayHostCommand& flexrayHostCommand) = 0; + + /*! \brief Incoming FlexRay controller message. + * Triggered when a FlexRay controller calls \ref SilKit::Services::Flexray::IFlexrayController::Configure. + * \param flexrayControllerConfig The FlexRay cluster parameters, node parameters and initial TX buffer configuration. + */ + virtual void OnControllerConfig(const FlexrayControllerConfig& flexrayControllerConfig) = 0; + + /*! \brief Incoming FlexRay controller message. + * Triggered when a FlexRay controller calls \ref SilKit::Services::Flexray::IFlexrayController::ReconfigureTxBuffer. + * \param flexrayTxBufferConfigUpdate The index and the new configuration of a TX buffer . + */ + virtual void OnTxBufferConfigUpdate(const FlexrayTxBufferConfigUpdate& flexrayTxBufferConfigUpdate) = 0; + + /*! \brief Incoming FlexRay controller message. + * Triggered when a FlexRay controller calls \ref SilKit::Services::Flexray::IFlexrayController::UpdateTxBuffer. + * \param flexrayTxBufferUpdate The index and the new payload of a TX buffer. + */ + virtual void OnTxBufferUpdate(const FlexrayTxBufferUpdate& flexrayTxBufferUpdate) = 0; +}; + +//! Producer for FlexRay events. +//! Passed in \ref ISimulatedNetwork::SetEventProducer. +//! Messages can be produced for a given set of controllers, specified by a span of controller descriptors. +//! The individual controller descriptor of a remote controller is passed in \ref ISimulatedNetwork::ProvideSimulatedController. +class IFlexRayEventProducer : public IEventProducer +{ +public: + virtual ~IFlexRayEventProducer() = default; + + /*! \brief Produce a \ref SilKit::Services::Flexray::FlexrayFrameEvent for a given set of receivers on this network. + * \param frameEvent The produced FlexRay event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Flexray::FlexrayFrameEvent& frameEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Flexray::FlexrayFrameTransmitEvent for a given set of receivers on this network. + * \param frameTransmitEvent The produced FlexRay event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Flexray::FlexrayFrameTransmitEvent& frameTransmitEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Flexray::FlexraySymbolEvent for a given set of receivers on this network. + * \param symbolEvent The produced FlexRay event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Flexray::FlexraySymbolEvent& symbolEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Flexray::FlexraySymbolTransmitEvent for a given set of receivers on this network. + * \param symbolTransmitEvent The produced FlexRay event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Flexray::FlexraySymbolTransmitEvent& symbolTransmitEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Flexray::FlexrayCycleStartEvent for a given set of receivers on this network. + * \param cycleStartEvent The produced FlexRay event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Flexray::FlexrayCycleStartEvent& cycleStartEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Flexray::FlexrayPocStatusEvent for a given set of receivers on this network. + * \param pocStatusEvent The produced FlexRay event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Flexray::FlexrayPocStatusEvent& pocStatusEvent, + const SilKit::Util::Span& receivers) = 0; +}; + +} // namespace Flexray + +namespace Ethernet { + +/*! \brief API for simulated Ethernet controllers. + * If a new Ethernet controller is created on a simulated network, an implementation of this interface can be provided in \ref ISimulatedNetwork::ProvideSimulatedController. + * Messages generated by the original controller will be redirected to the simulated controller and trigger the On... callbacks. + */ +class ISimulatedEthernetController : public ISimulatedController +{ +public: + virtual ~ISimulatedEthernetController() = default; + + /*! \brief Incoming Ethernet controller message. + * Triggered when a Ethernet controller calls \ref SilKit::Services::Ethernet::IEthernetController::SendFrame. + * \param ethernetFrameRequest The Ethernet frame requested to be sent. + */ + virtual void OnFrameRequest(const EthernetFrameRequest& ethernetFrameRequest) = 0; + + /*! \brief Incoming Ethernet controller message. + * Triggered when a Ethernet controller calls \ref SilKit::Services::Ethernet::IEthernetController::Activate or + . \ref SilKit::Services::Ethernet::IEthernetController::Deactivate + * \param ethernetControllerMode The current Ethernet controller mode. + */ + virtual void OnSetControllerMode(const EthernetControllerMode& ethernetControllerMode) = 0; +}; + +//! Producer for Ethernet events. +//! Passed in \ref ISimulatedNetwork::SetEventProducer. +//! Messages can be produced for a given set of controllers, specified by a span of controller descriptors. +//! The individual controller descriptor of a remote controller is passed in \ref ISimulatedNetwork::ProvideSimulatedController. +class IEthernetEventProducer : public IEventProducer +{ +public: + virtual ~IEthernetEventProducer() = default; + + /*! \brief Produce a \ref SilKit::Services::Ethernet::EthernetFrameEvent for a given set of receivers on this network. + * \param frameEvent The produced Ethernet event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Ethernet::EthernetFrameEvent& frameEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Ethernet::EthernetFrameTransmitEvent for a given set of receivers on this network. + * \param frameTransmitEvent The produced Ethernet event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& frameTransmitEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Ethernet::EthernetStateChangeEvent for a given set of receivers on this network. + * \param stateChangeEvent The produced Ethernet event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Ethernet::EthernetStateChangeEvent& stateChangeEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Ethernet::EthernetBitrateChangeEvent for a given set of receivers on this network. + * \param bitrateChangeEvent The produced Ethernet event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& bitrateChangeEvent, + const SilKit::Util::Span& receivers) = 0; +}; + +} // namespace Ethernet + +namespace Lin { + +/*! \brief API for simulated LIN controllers. + * If a new LIN controller is created on a simulated network, an implementation of this interface can be provided in \ref ISimulatedNetwork::ProvideSimulatedController. + * Messages generated by the original controller will be redirected to the simulated controller and trigger the On... callbacks. + */ +class ISimulatedLinController : public ISimulatedController +{ +public: + virtual ~ISimulatedLinController() = default; + + /*! \brief Incoming LIN controller message. + * Triggered when a LIN controller calls \ref SilKit::Services::Lin::ILinController::SendFrame. + * \param linFrameRequest The LIN frame requested to be sent. + */ + virtual void OnFrameRequest(const LinFrameRequest& linFrameRequest) = 0; + + /*! \brief Incoming LIN controller message. + * Triggered when a LIN controller calls \ref SilKit::Services::Lin::ILinController::SendFrameHeader. + * \param linFrameHeaderRequest A LIN frame header. + */ + virtual void OnFrameHeaderRequest(const LinFrameHeaderRequest& linFrameHeaderRequest) = 0; + + /*! \brief Incoming LIN controller message. + * Triggered when a LIN controller calls \ref SilKit::Services::Lin::ILinController::Wakeup. + * \param linWakeupPulse The Wakeup pulse without any further data except the event timestamp. + */ + virtual void OnWakeupPulse(const LinWakeupPulse& linWakeupPulse) = 0; + + /*! \brief Incoming LIN controller message. + * Triggered when a LIN controller calls \ref SilKit::Services::Lin::ILinController::Init. + * \param linControllerConfig The LIN controller configuration and frame response data. + */ + virtual void OnControllerConfig(const LinControllerConfig& linControllerConfig) = 0; + + /*! \brief Incoming LIN controller message. + * Triggered when a LIN controller calls \ref SilKit::Services::Lin::ILinController::UpdateTxBuffer + * or \ref SilKit::Services::Lin::ILinController::SendFrame. + * \param linFrameResponseUpdate An update for the frame response data. + */ + virtual void OnFrameResponseUpdate(const LinFrameResponseUpdate& linFrameResponseUpdate) = 0; + + /*! \brief Incoming LIN controller message. + * Triggered when a LIN controller calls \ref SilKit::Services::Lin::ILinController::Wakeup, + * \ref SilKit::Services::Lin::ILinController::WakeupInternal, + * \ref SilKit::Services::Lin::ILinController::GoToSleep or + * \ref SilKit::Services::Lin::ILinController::GoToSleepInternal + * \param linControllerStatusUpdate The new LIN controller status. + */ + virtual void OnControllerStatusUpdate(const LinControllerStatusUpdate& linControllerStatusUpdate) = 0; +}; + +//! Producer for LIN events. +//! Passed in \ref ISimulatedNetwork::SetEventProducer. +//! Messages can be produced for a given set of controllers, specified by a span of controller descriptors. +//! The individual controller descriptor of a remote controller is passed in \ref ISimulatedNetwork::ProvideSimulatedController. +class ILinEventProducer : public IEventProducer +{ +public: + virtual ~ILinEventProducer() = default; + + /*! \brief Produce a \ref SilKit::Services::Lin::LinFrameStatusEvent for a given set of receivers on this network. + * \param frameStatusEvent The produced Lin event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Lin::LinFrameStatusEvent& frameStatusEvent, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Lin::LinSendFrameHeaderRequest for a given set of receivers on this network. + * \param sendFrameHeaderRequest The produced Lin event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Lin::LinSendFrameHeaderRequest& sendFrameHeaderRequest, + const SilKit::Util::Span& receivers) = 0; + + /*! \brief Produce a \ref SilKit::Services::Lin::LinWakeupEvent for a given set of receivers on this network. + * \param wakeupEvent The produced Lin event. + * \param receivers The recipients of the event as a span of controller descriptors. + */ + virtual void Produce(const SilKit::Services::Lin::LinWakeupEvent& wakeupEvent, + const SilKit::Util::Span& receivers) = 0; +}; + +} // namespace Lin + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/include/silkit/experimental/netsim/NetworkSimulatorDatatypes.hpp b/SilKit/include/silkit/experimental/netsim/NetworkSimulatorDatatypes.hpp new file mode 100644 index 000000000..d1874481d --- /dev/null +++ b/SilKit/include/silkit/experimental/netsim/NetworkSimulatorDatatypes.hpp @@ -0,0 +1,199 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "silkit/SilKitMacros.hpp" +#include "silkit/capi/NetworkSimulator.h" +#include "silkit/services/datatypes.hpp" +#include "silkit/services/can/CanDatatypes.hpp" +#include "silkit/services/flexray/FlexrayDatatypes.hpp" +#include "silkit/services/ethernet/EthernetDatatypes.hpp" +#include "silkit/services/lin/LinDatatypes.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +//!< The identifier of a remote controller. +using ControllerDescriptor = SilKit_Experimental_ControllerDescriptor; + +//!< Types of bus networks. +enum class SimulatedNetworkType +{ + Undefined = SilKit_NetworkType_Undefined, + CAN = SilKit_NetworkType_CAN, + LIN = SilKit_NetworkType_LIN, + Ethernet = SilKit_NetworkType_Ethernet, + FlexRay = SilKit_NetworkType_FlexRay, +}; + +// -------------------------------- +// Can +// -------------------------------- + +namespace Can { + +struct CanFrameRequest +{ + SilKit::Services::Can::CanFrame frame; //!< The incoming CAN Frame + void* userContext; //!< Optional pointer provided by user when sending the frame +}; +struct CanConfigureBaudrate +{ + uint32_t baudRate; //!< Specifies the baud rate of the controller in bps (range 0..2000000). + uint32_t + fdBaudRate; //!< Specifies the data segment baud rate of the controller in bps for CAN FD (range 0..16000000). + uint32_t + xlBaudRate; //!< Specifies the data segment baud rate of the controller in bps for CAN XL (range 0..16000000). +}; +struct CanControllerMode +{ + SilKit_Experimental_NetSim_CanControllerModeFlags + canControllerModeFlags; //!< Flag for resetting the error handling and/or canceling all outstanding transmit requests + SilKit::Services::Can::CanControllerState state; //!< State that the CAN controller should reach. +}; + +} // namespace Can + +// -------------------------------- +// FlexRay +// -------------------------------- + +namespace Flexray { + +//! Update the content of a FlexRay TX-Buffer +struct FlexrayTxBufferUpdate +{ + //! Index of the TX Buffers according to the configured buffers (cf. FlexrayControllerConfig). + uint16_t txBufferIndex; + + //! Payload data valid flag + bool payloadDataValid; + + //! Raw payload containing 0 to 254 bytes. + Util::Span payload; +}; + +//! Update the configuration of a particular FlexRay TX-Buffer +struct FlexrayTxBufferConfigUpdate +{ + //! Index of the TX-Buffers according to the configured buffers (cf. FlexrayControllerConfig). + uint16_t txBufferIndex; + //! The new configuration of the Tx-Buffer + SilKit::Services::Flexray::FlexrayTxBufferConfig txBufferConfig; +}; + +//! Configure the communication parameters of the FlexRay controller. +struct FlexrayControllerConfig +{ + //! FlexRay cluster parameters + SilKit::Services::Flexray::FlexrayClusterParameters clusterParams; + //! FlexRay node parameters + SilKit::Services::Flexray::FlexrayNodeParameters nodeParams; + //! FlexRay buffer configs + std::vector bufferConfigs; +}; + +enum class FlexrayChiCommand : uint8_t +{ + RUN = SilKit_FlexrayChiCommand_RUN, //!< ChiCommand RUN + DEFERRED_HALT = SilKit_FlexrayChiCommand_DEFERRED_HALT, //!< ChiCommand DEFERRED_HALT + FREEZE = SilKit_FlexrayChiCommand_FREEZE, //!< ChiCommand FREEZE + ALLOW_COLDSTART = SilKit_FlexrayChiCommand_ALLOW_COLDSTART, //!< ChiCommand ALLOW_COLDSTART + ALL_SLOTS = SilKit_FlexrayChiCommand_ALL_SLOTS, //!< ChiCommand ALL_SLOTS + WAKEUP = SilKit_FlexrayChiCommand_WAKEUP //!< ChiCommand WAKEUP +}; + +struct FlexrayHostCommand +{ + FlexrayChiCommand command; +}; + +} // namespace Flexray + +namespace Ethernet { + +struct EthernetFrameRequest +{ + SilKit::Services::Ethernet::EthernetFrame ethernetFrame; //!< The Ethernet frame + void* userContext; //!< Optional pointer provided by user when sending the frame +}; + +//! \brief Mode for switching an Ethernet Controller on or off +enum class EthernetMode : uint8_t +{ + Inactive = SilKit_EthernetControllerMode_Inactive, //!< The controller is inactive (default after reset). + Active = SilKit_EthernetControllerMode_Active, //!< The controller is active. +}; + +struct EthernetControllerMode +{ + EthernetMode mode; //!< EthernetMode that the Ethernet controller should reach. +}; + +} // namespace Ethernet + +namespace Lin { + +struct LinFrameRequest +{ + SilKit::Services::Lin::LinFrame + frame; //!< Provide the LIN ID, checksum model, expected data length and optional data. + SilKit::Services::Lin::LinFrameResponseType + responseType; //!< Determines whether to provide a frame response or not. +}; + +struct LinFrameHeaderRequest +{ + SilKit::Services::Lin::LinId id; //!< The LinId of the header to be transmitted +}; + +struct LinWakeupPulse +{ + std::chrono::nanoseconds timestamp; //!< Time of the WakeUp pulse. Only valid in detailed Simulation. +}; + +struct LinControllerConfig +{ + //! Used to configure the simulation mode of the LinController. + enum class SimulationMode : uint8_t + { + //! The LIN controller sets frame responses using SetFrameResponses in advance. + Default = SilKit_Experimental_NetSim_LinSimulationMode_Default, + //! The LIN controller does not send frame responses automatically, users must call SendDynamicResponse. + Dynamic = SilKit_Experimental_NetSim_LinSimulationMode_Dynamic, + }; + + //! Configure as LIN master or LIN slave + SilKit::Services::Lin::LinControllerMode controllerMode{SilKit::Services::Lin::LinControllerMode::Inactive}; + //! The operational baud rate of the controller. Used in a detailed simulation. + SilKit::Services::Lin::LinBaudRate baudRate{0}; + //! Optional LinFrameResponse configuration. + //! + //! FrameResponses can also be configured at a later point using + //! ILinController::UpdateTxBuffer() and + //! ILinController::SetFrameResponses(). + std::vector frameResponses; + + //! The LinController's simulation mode. + SimulationMode simulationMode{SimulationMode::Default}; +}; + +struct LinFrameResponseUpdate +{ + std::vector frameResponses; //!< Vector of new FrameResponses. +}; + +struct LinControllerStatusUpdate +{ + std::chrono::nanoseconds timestamp; //!< Time of the controller status change. + SilKit::Services::Lin::LinControllerStatus status; //!< The new controller status +}; + +} // namespace Lin + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/include/silkit/experimental/netsim/all.hpp b/SilKit/include/silkit/experimental/netsim/all.hpp new file mode 100644 index 000000000..0592f4bef --- /dev/null +++ b/SilKit/include/silkit/experimental/netsim/all.hpp @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "NetworkSimulatorDatatypes.hpp" +#include "INetworkSimulator.hpp" diff --git a/SilKit/include/silkit/experimental/netsim/fwd_decl.hpp b/SilKit/include/silkit/experimental/netsim/fwd_decl.hpp new file mode 100644 index 000000000..58c9a8229 --- /dev/null +++ b/SilKit/include/silkit/experimental/netsim/fwd_decl.hpp @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +class INetworkSimulator; +class ISimulatedNetwork; +class ISimulatedController; +namespace Can { +class ISimulatedCanController; +} +namespace Flexray { +class ISimulatedFlexRayController; +} +namespace Ethernet { +class ISimulatedEthernetController; +} +namespace Lin { +class ISimulatedLinController; +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/include/silkit/experimental/netsim/string_utils.hpp b/SilKit/include/silkit/experimental/netsim/string_utils.hpp new file mode 100644 index 000000000..87c6ccd2c --- /dev/null +++ b/SilKit/include/silkit/experimental/netsim/string_utils.hpp @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "NetworkSimulatorDatatypes.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +inline std::string to_string(SimulatedNetworkType type); +inline std::ostream& operator<<(std::ostream& out, SimulatedNetworkType ftypelag); + +// ================================================================================ +// Inline Implementations +// ================================================================================ + +std::string to_string(SimulatedNetworkType type) +{ + std::stringstream outStream; + outStream << type; + return outStream.str(); +} + +std::ostream& operator<<(std::ostream& out, SimulatedNetworkType type) +{ + switch (type) + { + case SimulatedNetworkType::Undefined: + return out << "Undefined"; + case SimulatedNetworkType::CAN: + return out << "CAN"; + case SimulatedNetworkType::LIN: + return out << "LIN"; + case SimulatedNetworkType::FlexRay: + return out << "FlexRay"; + case SimulatedNetworkType::Ethernet: + return out << "Ethernet"; + } + + return out << "unknown(" << static_cast(type) << ")"; +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/include/silkit/experimental/participant/ParticipantExtensions.hpp b/SilKit/include/silkit/experimental/participant/ParticipantExtensions.hpp index 3b19e7d7e..3a31c0319 100644 --- a/SilKit/include/silkit/experimental/participant/ParticipantExtensions.hpp +++ b/SilKit/include/silkit/experimental/participant/ParticipantExtensions.hpp @@ -42,6 +42,10 @@ namespace Participant { DETAIL_SILKIT_CPP_API auto CreateSystemController(SilKit::IParticipant* participant) -> SilKit::Experimental::Services::Orchestration::ISystemController*; +DETAIL_SILKIT_CPP_API auto CreateNetworkSimulator(SilKit::IParticipant* participant) + -> SilKit::Experimental::NetworkSimulation::INetworkSimulator*; + + } // namespace Participant } // namespace Experimental DETAIL_SILKIT_DETAIL_VN_NAMESPACE_CLOSE diff --git a/SilKit/include/silkit/experimental/services/lin/LinControllerExtensions.hpp b/SilKit/include/silkit/experimental/services/lin/LinControllerExtensions.hpp index 9eea2254d..bbb598059 100644 --- a/SilKit/include/silkit/experimental/services/lin/LinControllerExtensions.hpp +++ b/SilKit/include/silkit/experimental/services/lin/LinControllerExtensions.hpp @@ -84,20 +84,25 @@ DETAIL_SILKIT_CPP_API auto GetSlaveConfiguration(SilKit::Services::Lin::ILinCont * \throws SilKit::StateError if the LIN Controller is configured with LinControllerMode::Inactive * \throws SilKit::StateError if Init() is called a second time on this LIN Controller. */ -DETAIL_SILKIT_CPP_API void InitDynamic(SilKit::Services::Lin::ILinController* linController, const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig); +DETAIL_SILKIT_CPP_API void InitDynamic( + SilKit::Services::Lin::ILinController* linController, + const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig); /*! \brief The FrameHeaderHandler is called whenever a LIN frame header is received. * * \return Returns a \ref SilKit::Util::HandlerId that can be used to remove the callback. */ -DETAIL_SILKIT_CPP_API auto AddFrameHeaderHandler(SilKit::Services::Lin::ILinController* linController, SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) -> SilKit::Services::HandlerId; +DETAIL_SILKIT_CPP_API auto AddFrameHeaderHandler(SilKit::Services::Lin::ILinController* linController, + SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) + -> SilKit::Services::HandlerId; /*! \brief Remove a FrameHeaderHandler by \ref SilKit::Util::HandlerId on this controller * * \param linController The controller to act upon * \param handlerId Identifier of the callback to be removed. Obtained upon adding to respective handler. */ -DETAIL_SILKIT_CPP_API void RemoveFrameHeaderHandler(SilKit::Services::Lin::ILinController* linController, SilKit::Services::HandlerId handlerId); +DETAIL_SILKIT_CPP_API void RemoveFrameHeaderHandler(SilKit::Services::Lin::ILinController* linController, + SilKit::Services::HandlerId handlerId); /*! \brief Send a response for the previously received LIN header, but only when the controller was initialized using \ref InitDynamic. * @@ -105,7 +110,8 @@ DETAIL_SILKIT_CPP_API void RemoveFrameHeaderHandler(SilKit::Services::Lin::ILinC * \throws SilKit::StateError if the LIN controller was not initialized using \ref InitDynamic. * \throws SilKit::StateError if no prior LinFrameHeaderEvent was received before the call. */ -DETAIL_SILKIT_CPP_API void SendDynamicResponse(SilKit::Services::Lin::ILinController* linController, const SilKit::Services::Lin::LinFrame& linFrame); +DETAIL_SILKIT_CPP_API void SendDynamicResponse(SilKit::Services::Lin::ILinController* linController, + const SilKit::Services::Lin::LinFrame& linFrame); } // namespace Lin } // namespace Services diff --git a/SilKit/include/silkit/experimental/services/lin/string_utils.hpp b/SilKit/include/silkit/experimental/services/lin/string_utils.hpp index bb886ad90..bc714a5f5 100644 --- a/SilKit/include/silkit/experimental/services/lin/string_utils.hpp +++ b/SilKit/include/silkit/experimental/services/lin/string_utils.hpp @@ -35,7 +35,8 @@ namespace Lin { inline std::string to_string(const Experimental::Services::Lin::LinSlaveConfiguration& linSlaveConfiguration); -inline std::ostream& operator<<(std::ostream& out, const Experimental::Services::Lin::LinSlaveConfiguration& linSlaveConfiguration); +inline std::ostream& operator<<(std::ostream& out, + const Experimental::Services::Lin::LinSlaveConfiguration& linSlaveConfiguration); // ================================================================================ // Inline Implementations @@ -65,7 +66,7 @@ std::ostream& operator<<(std::ostream& out, out << "]}"; return out; } - + } // namespace Lin } // namespace Services } // namespace Experimental diff --git a/SilKit/include/silkit/experimental/services/orchestration/ISystemController.hpp b/SilKit/include/silkit/experimental/services/orchestration/ISystemController.hpp index 663d73a30..0d15b0a15 100644 --- a/SilKit/include/silkit/experimental/services/orchestration/ISystemController.hpp +++ b/SilKit/include/silkit/experimental/services/orchestration/ISystemController.hpp @@ -1,62 +1,62 @@ -/* Copyright (c) 2022 Vector Informatik GmbH - -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. */ - -#pragma once - -#include "silkit/services/orchestration/OrchestrationDatatypes.hpp" - -namespace SilKit { -namespace Experimental { -namespace Services { -namespace Orchestration { - -//! SystemController interface for configuration of the simulation flow and system-wide commands. -class ISystemController -{ -public: - virtual ~ISystemController() = default; - - /*! \brief Sends a SilKit::Services::Orchestration::SystemCommand::Kind::AbortSimulation to all participants - * - * The abort simulation command signals all participants to terminate their - * lifecycle, regardless of their current state. - * - * The command is allowed at any time. - */ - virtual void AbortSimulation() const = 0; - - /*! \brief Configures details of the simulation workflow regarding lifecycle and participant coordination. - * - * Only the required participant defined in the \ref SilKit::Services::Orchestration::WorkflowConfiguration are taken into account to define the - * system state. Further, the simulation time propagation also relies on the required participants. - * The \ref SilKit::Services::Orchestration::WorkflowConfiguration is distributed to other participants, so it must only be set once by a single - * member of the simulation. - * - * \param workflowConfiguration The desired configuration, currently containing a list of required participants - */ - virtual void SetWorkflowConfiguration( - const SilKit::Services::Orchestration::WorkflowConfiguration& workflowConfiguration) = 0; -}; - -} // namespace Orchestration -} // namespace Services -} // namespace Experimental -} // namespace SilKit +/* Copyright (c) 2022 Vector Informatik GmbH + +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. */ + +#pragma once + +#include "silkit/services/orchestration/OrchestrationDatatypes.hpp" + +namespace SilKit { +namespace Experimental { +namespace Services { +namespace Orchestration { + +//! SystemController interface for configuration of the simulation flow and system-wide commands. +class ISystemController +{ +public: + virtual ~ISystemController() = default; + + /*! \brief Sends a SilKit::Services::Orchestration::SystemCommand::Kind::AbortSimulation to all participants + * + * The abort simulation command signals all participants to terminate their + * lifecycle, regardless of their current state. + * + * The command is allowed at any time. + */ + virtual void AbortSimulation() const = 0; + + /*! \brief Configures details of the simulation workflow regarding lifecycle and participant coordination. + * + * Only the required participant defined in the \ref SilKit::Services::Orchestration::WorkflowConfiguration are taken into account to define the + * system state. Further, the simulation time propagation also relies on the required participants. + * The \ref SilKit::Services::Orchestration::WorkflowConfiguration is distributed to other participants, so it must only be set once by a single + * member of the simulation. + * + * \param workflowConfiguration The desired configuration, currently containing a list of required participants + */ + virtual void SetWorkflowConfiguration( + const SilKit::Services::Orchestration::WorkflowConfiguration& workflowConfiguration) = 0; +}; + +} // namespace Orchestration +} // namespace Services +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/include/silkit/participant/IParticipant.hpp b/SilKit/include/silkit/participant/IParticipant.hpp index ae4eb10d2..bedb8ecfd 100644 --- a/SilKit/include/silkit/participant/IParticipant.hpp +++ b/SilKit/include/silkit/participant/IParticipant.hpp @@ -28,6 +28,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "silkit/services/fwd_decl.hpp" #include "silkit/services/orchestration/fwd_decl.hpp" +#include "silkit/experimental/netsim/fwd_decl.hpp" #include "silkit/services/pubsub/PubSubDatatypes.hpp" #include "silkit/services/pubsub/PubSubSpec.hpp" @@ -56,29 +57,30 @@ class IParticipant */ //! \brief Create a CAN controller at this SIL Kit participant. - virtual auto CreateCanController(const std::string& canonicalName, const std::string& networkName) - -> Services::Can::ICanController* = 0; + virtual auto CreateCanController(const std::string& canonicalName, + const std::string& networkName) -> Services::Can::ICanController* = 0; //! \brief Create an Ethernet controller at this SIL Kit participant. virtual auto CreateEthernetController(const std::string& canonicalName, const std::string& networkName) -> Services::Ethernet::IEthernetController* = 0; //! \brief Create an FlexRay controller at this SIL Kit participant. - virtual auto CreateFlexrayController(const std::string& canonicalName, const std::string& networkName) - -> Services::Flexray::IFlexrayController* = 0; + virtual auto CreateFlexrayController(const std::string& canonicalName, + const std::string& networkName) -> Services::Flexray::IFlexrayController* = 0; //! \brief Create a LIN controller at this SIL Kit participant. - virtual auto CreateLinController(const std::string& canonicalName, const std::string& networkName) - -> Services::Lin::ILinController* = 0; + virtual auto CreateLinController(const std::string& canonicalName, + const std::string& networkName) -> Services::Lin::ILinController* = 0; //! \brief Create a data publisher at this SIL Kit participant. - virtual auto CreateDataPublisher(const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, size_t history = 0) - -> Services::PubSub::IDataPublisher* = 0; + virtual auto CreateDataPublisher(const std::string& canonicalName, + const SilKit::Services::PubSub::PubSubSpec& dataSpec, + size_t history = 0) -> Services::PubSub::IDataPublisher* = 0; //! \brief Create a data subscriber at this SIL Kit participant. - virtual auto CreateDataSubscriber(const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, - Services::PubSub::DataMessageHandler dataMessageHandler) - -> Services::PubSub::IDataSubscriber* = 0; + virtual auto CreateDataSubscriber( + const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, + Services::PubSub::DataMessageHandler dataMessageHandler) -> Services::PubSub::IDataSubscriber* = 0; //! \brief Create a Rpc client at this SIL Kit participant. virtual auto CreateRpcClient(const std::string& canonicalName, const SilKit::Services::Rpc::RpcSpec& dataSpec, diff --git a/SilKit/include/silkit/participant/exception.hpp b/SilKit/include/silkit/participant/exception.hpp old mode 100755 new mode 100644 index 6c1a5530f..5966ca581 --- a/SilKit/include/silkit/participant/exception.hpp +++ b/SilKit/include/silkit/participant/exception.hpp @@ -27,19 +27,19 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SilKit { //! \brief Base class of all SilKit exceptions -class SilKitError: public std::exception +class SilKitError : public std::exception { protected: std::string _what; -public: +public: SilKitError(std::string message) - :_what{std::move(message)} + : _what{std::move(message)} { } SilKitError(const char* message) - :_what{message} + : _what{message} { } @@ -54,7 +54,10 @@ class TypeConversionError : public SilKitError public: using SilKitError::SilKitError; - TypeConversionError() : SilKitError("SilKit: Invalid type conversion.") { } + TypeConversionError() + : SilKitError("SilKit: Invalid type conversion.") + { + } }; class ConfigurationError : public SilKitError @@ -62,7 +65,10 @@ class ConfigurationError : public SilKitError public: using SilKitError::SilKitError; - ConfigurationError() : ConfigurationError("SilKit: Configuration has syntactical or semantical errors.") { } + ConfigurationError() + : ConfigurationError("SilKit: Configuration has syntactical or semantical errors.") + { + } }; class StateError : public SilKitError @@ -78,12 +84,12 @@ class ProtocolError : public SilKitError }; //! \brief Error thrown as a replacement for cassert's assert. -class AssertionError: public SilKitError +class AssertionError : public SilKitError { public: using SilKitError::SilKitError; }; - + //! \brief Error thrown when an extension could not be loaded. class ExtensionError : public SilKitError { diff --git a/SilKit/include/silkit/services/can/CanDatatypes.hpp b/SilKit/include/silkit/services/can/CanDatatypes.hpp index f270278d4..0ea120620 100644 --- a/SilKit/include/silkit/services/can/CanDatatypes.hpp +++ b/SilKit/include/silkit/services/can/CanDatatypes.hpp @@ -80,17 +80,17 @@ struct CanFrameEvent */ enum class CanControllerState : SilKit_CanControllerState { - //! CAN controller is not initialized (initial state after reset). - Uninit = SilKit_CanControllerState_Uninit, + //! CAN controller is not initialized (initial state after reset). + Uninit = SilKit_CanControllerState_Uninit, - //! CAN controller is initialized but does not participate on the CAN bus. - Stopped = SilKit_CanControllerState_Stopped, + //! CAN controller is initialized but does not participate on the CAN bus. + Stopped = SilKit_CanControllerState_Stopped, - //! CAN controller is in normal operation mode. - Started = SilKit_CanControllerState_Started, + //! CAN controller is in normal operation mode. + Started = SilKit_CanControllerState_Started, - //! CAN controller is in sleep mode which is similar to the Stopped state. - Sleep = SilKit_CanControllerState_Sleep, + //! CAN controller is in sleep mode which is similar to the Stopped state. + Sleep = SilKit_CanControllerState_Sleep, }; @@ -98,25 +98,25 @@ enum class CanControllerState : SilKit_CanControllerState */ enum class CanErrorState : SilKit_CanErrorState { - /*! Error State is Not Available, because CAN controller is in state Uninit. + /*! Error State is Not Available, because CAN controller is in state Uninit. * * *AUTOSAR Doc:* Successful transmission. */ - NotAvailable = SilKit_CanErrorState_NotAvailable, + NotAvailable = SilKit_CanErrorState_NotAvailable, - /*! Error Active Mode, the CAN controller is allowed to send messages and active error flags. + /*! Error Active Mode, the CAN controller is allowed to send messages and active error flags. */ - ErrorActive = SilKit_CanErrorState_ErrorActive, + ErrorActive = SilKit_CanErrorState_ErrorActive, - /*! Error Passive Mode, the CAN controller is still allowed to send messages, but must not send active error flags. + /*! Error Passive Mode, the CAN controller is still allowed to send messages, but must not send active error flags. */ - ErrorPassive = SilKit_CanErrorState_ErrorPassive, + ErrorPassive = SilKit_CanErrorState_ErrorPassive, - /*! (currently not in use) + /*! (currently not in use) * * *AUTOSAR Doc:* Bus Off Mode, the CAN controller does not take part in communication. */ - BusOff = SilKit_CanErrorState_BusOff, + BusOff = SilKit_CanErrorState_BusOff, }; using CanTransmitStatusMask = SilKit_CanTransmitStatus; diff --git a/SilKit/include/silkit/services/can/ICanController.hpp b/SilKit/include/silkit/services/can/ICanController.hpp index 75e5628a8..ac3419b3a 100644 --- a/SilKit/include/silkit/services/can/ICanController.hpp +++ b/SilKit/include/silkit/services/can/ICanController.hpp @@ -36,7 +36,7 @@ class ICanController public: /*! \brief Generic CAN callback method */ - template + template using CallbackT = std::function; /*! Callback type to indicate that a CanFrameEvent has been received. @@ -131,7 +131,7 @@ class ICanController * \return Returns a \ref SilKit::Util::HandlerId that can be used to remove the callback. */ virtual auto AddFrameHandler(FrameHandler handler, - DirectionMask directionMask = (DirectionMask)TransmitDirection::RX) -> HandlerId = 0; + DirectionMask directionMask = (DirectionMask)TransmitDirection::RX) -> HandlerId = 0; /*! \brief Remove a FrameHandler by \ref SilKit::Util::HandlerId on this controller * diff --git a/SilKit/include/silkit/services/can/string_utils.hpp b/SilKit/include/silkit/services/can/string_utils.hpp index d76986651..44b6edada 100644 --- a/SilKit/include/silkit/services/can/string_utils.hpp +++ b/SilKit/include/silkit/services/can/string_utils.hpp @@ -134,13 +134,20 @@ std::ostream& operator<<(std::ostream& out, CanFrameFlag flag) { switch (flag) { - case CanFrameFlag::Ide: return out << "ide"; - case CanFrameFlag::Rtr: return out << "rtr"; - case CanFrameFlag::Fdf: return out << "fdf"; - case CanFrameFlag::Brs: return out << "brs"; - case CanFrameFlag::Esi: return out << "esi"; - case CanFrameFlag::Xlf: return out << "xlf"; - case CanFrameFlag::Sec: return out << "sec"; + case CanFrameFlag::Ide: + return out << "ide"; + case CanFrameFlag::Rtr: + return out << "rtr"; + case CanFrameFlag::Fdf: + return out << "fdf"; + case CanFrameFlag::Brs: + return out << "brs"; + case CanFrameFlag::Esi: + return out << "esi"; + case CanFrameFlag::Xlf: + return out << "xlf"; + case CanFrameFlag::Sec: + return out << "sec"; } return out << "unknown(" << static_cast(flag) << ")"; @@ -164,8 +171,7 @@ std::ostream& operator<<(std::ostream& out, CanTransmitStatus status) std::ostream& operator<<(std::ostream& out, const CanFrame& msg) { out << "Can::CanFrame{" - << ", canId=" << msg.canId - << ", flags="; + << ", canId=" << msg.canId << ", flags="; auto printFlag = [firstFlag = true, &out, &msg](const CanFrameFlag flag) mutable { if (!(msg.flags & static_cast(flag))) @@ -193,31 +199,23 @@ std::ostream& operator<<(std::ostream& out, const CanFrame& msg) } out << ']'; - return out - << ", dlc=" << static_cast(msg.dlc) - << ", sdt=" << static_cast(msg.sdt) - << ", vcid=" << static_cast(msg.vcid) - << ", af=" << static_cast(msg.af) - << ", data=[" << Util::AsHexString(msg.dataField).WithSeparator(" ").WithMaxLength(8) - << "], data.size=" << msg.dataField.size() << "}"; + return out << ", dlc=" << static_cast(msg.dlc) << ", sdt=" << static_cast(msg.sdt) + << ", vcid=" << static_cast(msg.vcid) << ", af=" << static_cast(msg.af) << ", data=[" + << Util::AsHexString(msg.dataField).WithSeparator(" ").WithMaxLength(8) + << "], data.size=" << msg.dataField.size() << "}"; } std::ostream& operator<<(std::ostream& out, const CanFrameEvent& msg) { auto timestamp = std::chrono::duration_cast>(msg.timestamp); - return out - << "Can::CanFrameEvent{userContext=" << msg.userContext - << ", direction=" << msg.direction - << ", frame=" << msg.frame - << " @" << timestamp.count() << "ms}"; + return out << "Can::CanFrameEvent{userContext=" << msg.userContext << ", direction=" << msg.direction + << ", frame=" << msg.frame << " @" << timestamp.count() << "ms}"; } std::ostream& operator<<(std::ostream& out, const CanFrameTransmitEvent& status) { auto timestamp = std::chrono::duration_cast>(status.timestamp); - return out - << "Can::CanTtransmitAcknowledge{status=" << status.status - << " @" << timestamp.count() << "ms}"; + return out << "Can::CanTtransmitAcknowledge{status=" << status.status << " @" << timestamp.count() << "ms}"; } } // namespace Can diff --git a/SilKit/include/silkit/services/ethernet/IEthernetController.hpp b/SilKit/include/silkit/services/ethernet/IEthernetController.hpp index 39ad1614e..102dd51d4 100644 --- a/SilKit/include/silkit/services/ethernet/IEthernetController.hpp +++ b/SilKit/include/silkit/services/ethernet/IEthernetController.hpp @@ -36,7 +36,7 @@ class IEthernetController public: /*! \brief Generic Ethernet callback method */ - template + template using CallbackT = std::function; /*! Callback type to indicate that an EthernetFrameEvent has been received. @@ -86,8 +86,8 @@ class IEthernetController * * \return Returns a \ref SilKit::Util::HandlerId that can be used to remove the callback. */ - virtual auto AddFrameHandler( - FrameHandler handler, DirectionMask directionMask = static_cast(TransmitDirection::RX)) -> HandlerId = 0; + virtual auto AddFrameHandler(FrameHandler handler, DirectionMask directionMask = static_cast( + TransmitDirection::RX)) -> HandlerId = 0; /*! \brief Remove a FrameHandler by \ref SilKit::Util::HandlerId on this controller * @@ -107,9 +107,9 @@ class IEthernetController * * \return Returns a \ref SilKit::Util::HandlerId that can be used to remove the callback. */ - virtual auto AddFrameTransmitHandler(FrameTransmitHandler handler, EthernetTransmitStatusMask transmitStatusMask = - SilKit_EthernetTransmitStatus_DefaultMask) - -> HandlerId = 0; + virtual auto AddFrameTransmitHandler( + FrameTransmitHandler handler, + EthernetTransmitStatusMask transmitStatusMask = SilKit_EthernetTransmitStatus_DefaultMask) -> HandlerId = 0; /*! \brief Remove a FrameTransmitHandler by \ref SilKit::Util::HandlerId on this controller * diff --git a/SilKit/include/silkit/services/ethernet/string_utils.hpp b/SilKit/include/silkit/services/ethernet/string_utils.hpp old mode 100755 new mode 100644 index 6d8208f79..eae745e69 --- a/SilKit/include/silkit/services/ethernet/string_utils.hpp +++ b/SilKit/include/silkit/services/ethernet/string_utils.hpp @@ -56,15 +56,15 @@ std::string to_string(EthernetTransmitStatus value) { switch (value) { - case EthernetTransmitStatus::Transmitted: + case EthernetTransmitStatus::Transmitted: return "Transmitted"; - case EthernetTransmitStatus::ControllerInactive: + case EthernetTransmitStatus::ControllerInactive: return "ControllerInactive"; - case EthernetTransmitStatus::LinkDown: + case EthernetTransmitStatus::LinkDown: return "LinkDown"; - case EthernetTransmitStatus::Dropped: + case EthernetTransmitStatus::Dropped: return "Dropped"; - case EthernetTransmitStatus::InvalidFrameFormat: + case EthernetTransmitStatus::InvalidFrameFormat: return "InvalidFrameFormat"; }; throw SilKit::TypeConversionError{}; @@ -119,8 +119,7 @@ std::ostream& operator<<(std::ostream& out, const EthernetFrame& msg) { if (msg.raw.size() == 0) { - return out - << "EthernetFrame{size=0}"; + return out << "EthernetFrame{size=0}"; } else { @@ -131,40 +130,30 @@ std::ostream& operator<<(std::ostream& out, const EthernetFrame& msg) { EthernetMac destinationMac; EthernetMac sourceMac; - std::copy( - msg.raw.begin(), - msg.raw.begin() + sizeof(EthernetMac), destinationMac.begin()); - std::copy( - msg.raw.begin() + sizeof(EthernetMac), - msg.raw.begin() + 2 * sizeof(EthernetMac), sourceMac.begin()); + std::copy(msg.raw.begin(), msg.raw.begin() + sizeof(EthernetMac), destinationMac.begin()); + std::copy(msg.raw.begin() + sizeof(EthernetMac), msg.raw.begin() + 2 * sizeof(EthernetMac), + sourceMac.begin()); out << ", src = " << Util::AsHexString(sourceMac).WithSeparator(":") << ", dst=" << Util::AsHexString(destinationMac).WithSeparator(":"); } - return out - << ", data=[" << Util::AsHexString(msg.raw).WithSeparator(" ").WithMaxLength(8) - << "]}"; + return out << ", data=[" << Util::AsHexString(msg.raw).WithSeparator(" ").WithMaxLength(8) << "]}"; } } std::ostream& operator<<(std::ostream& out, const EthernetFrameEvent& msg) { auto timestamp = std::chrono::duration_cast>(msg.timestamp); - return out - << "EthernetFrameEvent{" << msg.frame - << ", direction=" << msg.direction - << ", userContext=" << msg.userContext - << " @" << timestamp.count() << "ms" - << "}"; + return out << "EthernetFrameEvent{" << msg.frame << ", direction=" << msg.direction + << ", userContext=" << msg.userContext << " @" << timestamp.count() << "ms" + << "}"; } std::ostream& operator<<(std::ostream& out, const EthernetFrameTransmitEvent& msg) { auto timestamp = std::chrono::duration_cast>(msg.timestamp); - out - << "EthernetFrameTransmitEvent{status=" << msg.status - << ", userContext=" << msg.userContext - << " @" << timestamp.count() << "ms" + out << "EthernetFrameTransmitEvent{status=" << msg.status << ", userContext=" << msg.userContext << " @" + << timestamp.count() << "ms" << "}"; return out; diff --git a/SilKit/include/silkit/services/flexray/FlexrayDatatypes.hpp b/SilKit/include/silkit/services/flexray/FlexrayDatatypes.hpp old mode 100755 new mode 100644 index 7ee39236b..c9a84b600 --- a/SilKit/include/silkit/services/flexray/FlexrayDatatypes.hpp +++ b/SilKit/include/silkit/services/flexray/FlexrayDatatypes.hpp @@ -42,17 +42,17 @@ using FlexrayMicroTick = SilKit_FlexrayMicroTick; //!< FlexRay micro tick enum class FlexrayChannel : SilKit_FlexrayChannel { None = SilKit_FlexrayChannel_None, //!< Invalid Channel - A = SilKit_FlexrayChannel_A, //!< Channel A - B = SilKit_FlexrayChannel_B, //!< Channel B - AB = SilKit_FlexrayChannel_AB, //!< Channel AB + A = SilKit_FlexrayChannel_A, //!< Channel A + B = SilKit_FlexrayChannel_B, //!< Channel B + AB = SilKit_FlexrayChannel_AB, //!< Channel AB }; //! \brief Period of the clock (used for micro tick period and sample clock period). enum class FlexrayClockPeriod : SilKit_FlexrayClockPeriod { T12_5NS = SilKit_FlexrayClockPeriod_T12_5NS, //!< 12.5ns / 80MHz - T25NS = SilKit_FlexrayClockPeriod_T25NS, //!< 25ns / 40MHz - T50NS = SilKit_FlexrayClockPeriod_T50NS, //!< 50ns / 20MHz + T25NS = SilKit_FlexrayClockPeriod_T25NS, //!< 25ns / 40MHz + T50NS = SilKit_FlexrayClockPeriod_T50NS, //!< 50ns / 20MHz }; /*! @@ -72,7 +72,7 @@ struct FlexrayClusterParameters uint16_t gdActionPointOffset; ////! Not used by network simulator - //gdCASRxLowMax + //gdCASRxLowMax //! Duration of the idle phase within a dynamic slot in gdMiniSlots (range 0-2). uint16_t gdDynamicSlotIdlePhase; @@ -198,7 +198,7 @@ struct FlexrayNodeParameters //! Key slot is used for startup (range 0, 1). uint8_t pKeySlotUsedForStartup; - + //! Key slot is used for sync (range 0, 1). uint8_t pKeySlotUsedForSync; @@ -239,7 +239,7 @@ struct FlexrayNodeParameters FlexrayChannel pWakeupChannel; //! Number of repetitions of the wakeup symbol (range 0-63, value 0 or 1 prevents sending of WUP). - uint8_t pWakeupPattern; + uint8_t pWakeupPattern; // ---------------------------------------------------------------------- // Parameters according to B.3.2.2 @@ -373,9 +373,10 @@ struct FlexrayFrameTransmitEvent */ enum class FlexraySymbolPattern : SilKit_FlexraySymbolPattern { - CasMts = SilKit_FlexraySymbolPattern_CasMts, //!< Collision avoidance symbol (CAS) OR media access test symbol (MTS). - Wus = SilKit_FlexraySymbolPattern_Wus, //!< Wakeup symbol (WUS). - Wudop = SilKit_FlexraySymbolPattern_Wudop, //!< Wakeup During Operation Pattern (WUDOP). + CasMts = + SilKit_FlexraySymbolPattern_CasMts, //!< Collision avoidance symbol (CAS) OR media access test symbol (MTS). + Wus = SilKit_FlexraySymbolPattern_Wus, //!< Wakeup symbol (WUS). + Wudop = SilKit_FlexraySymbolPattern_Wudop, //!< Wakeup During Operation Pattern (WUDOP). }; /*! @@ -422,13 +423,14 @@ struct FlexrayCycleStartEvent enum class FlexrayPocState : SilKit_FlexrayPocState { DefaultConfig = SilKit_FlexrayPocState_DefaultConfig, //!< CC expects configuration. Initial state after reset. - Config = SilKit_FlexrayPocState_Config, //!< CC is in configuration mode for setting communication parameters - Ready = SilKit_FlexrayPocState_Ready, //!< intermediate state for initialization process (after Config). - Startup = SilKit_FlexrayPocState_Startup, //!< FlexRay startup phase - Wakeup = SilKit_FlexrayPocState_Wakeup, //!< FlexRay wakeup phase - NormalActive = SilKit_FlexrayPocState_NormalActive, //!< Normal operating mode + Config = SilKit_FlexrayPocState_Config, //!< CC is in configuration mode for setting communication parameters + Ready = SilKit_FlexrayPocState_Ready, //!< intermediate state for initialization process (after Config). + Startup = SilKit_FlexrayPocState_Startup, //!< FlexRay startup phase + Wakeup = SilKit_FlexrayPocState_Wakeup, //!< FlexRay wakeup phase + NormalActive = SilKit_FlexrayPocState_NormalActive, //!< Normal operating mode NormalPassive = SilKit_FlexrayPocState_NormalPassive, //!< Operating mode with transient or tolerable errors - Halt = SilKit_FlexrayPocState_Halt, //!< CC is halted (caused by the application (FlexrayChiCommand::DEFERRED_HALT) or by a fatal error). + Halt = + SilKit_FlexrayPocState_Halt, //!< CC is halted (caused by the application (FlexrayChiCommand::DEFERRED_HALT) or by a fatal error). }; /*! @@ -503,9 +505,10 @@ struct FlexrayPocStatusEvent FlexrayPocState state; //!< Status of the Protocol Operation Control (POC). bool chiHaltRequest; //!< indicates whether a halt request was received from the CHI - bool coldstartNoise; //!< indicates noisy channel conditions during coldstart + bool coldstartNoise; //!< indicates noisy channel conditions during coldstart bool freeze; //!< indicates that the POC entered a halt state due to an error condition requiring immediate halt. - bool chiReadyRequest; //!< indicates that the CHI requested to enter ready state at the end of the communication cycle. + bool + chiReadyRequest; //!< indicates that the CHI requested to enter ready state at the end of the communication cycle. FlexrayErrorModeType errorMode; //!< indicates the error mode of the POC FlexraySlotModeType slotMode; //!< indicates the slot mode of the POC FlexrayStartupStateType startupState; //!< indicates states within the STARTUP mechanism @@ -518,64 +521,47 @@ struct FlexrayPocStatusEvent inline bool operator==(const FlexrayClusterParameters& lhs, const FlexrayClusterParameters& rhs) { - return lhs.gColdstartAttempts == rhs.gColdstartAttempts - && lhs.gCycleCountMax == rhs.gCycleCountMax - && lhs.gdActionPointOffset == rhs.gdActionPointOffset - && lhs.gdDynamicSlotIdlePhase == rhs.gdDynamicSlotIdlePhase - && lhs.gdMiniSlot == rhs.gdMiniSlot - && lhs.gdMiniSlotActionPointOffset == rhs.gdMiniSlotActionPointOffset - && lhs.gdStaticSlot == rhs.gdStaticSlot - && lhs.gdSymbolWindow == rhs.gdSymbolWindow - && lhs.gdSymbolWindowActionPointOffset == rhs.gdSymbolWindowActionPointOffset - && lhs.gdTSSTransmitter == rhs.gdTSSTransmitter - && lhs.gdWakeupTxActive == rhs.gdWakeupTxActive - && lhs.gdWakeupTxIdle == rhs.gdWakeupTxIdle - && lhs.gListenNoise == rhs.gListenNoise - && lhs.gMacroPerCycle == rhs.gMacroPerCycle - && lhs.gMaxWithoutClockCorrectionFatal == rhs.gMaxWithoutClockCorrectionFatal - && lhs.gMaxWithoutClockCorrectionPassive == rhs.gMaxWithoutClockCorrectionPassive - && lhs.gNumberOfMiniSlots == rhs.gNumberOfMiniSlots - && lhs.gNumberOfStaticSlots == rhs.gNumberOfStaticSlots - && lhs.gPayloadLengthStatic == rhs.gPayloadLengthStatic - && lhs.gSyncFrameIDCountMax == rhs.gSyncFrameIDCountMax; + return lhs.gColdstartAttempts == rhs.gColdstartAttempts && lhs.gCycleCountMax == rhs.gCycleCountMax + && lhs.gdActionPointOffset == rhs.gdActionPointOffset + && lhs.gdDynamicSlotIdlePhase == rhs.gdDynamicSlotIdlePhase && lhs.gdMiniSlot == rhs.gdMiniSlot + && lhs.gdMiniSlotActionPointOffset == rhs.gdMiniSlotActionPointOffset && lhs.gdStaticSlot == rhs.gdStaticSlot + && lhs.gdSymbolWindow == rhs.gdSymbolWindow + && lhs.gdSymbolWindowActionPointOffset == rhs.gdSymbolWindowActionPointOffset + && lhs.gdTSSTransmitter == rhs.gdTSSTransmitter && lhs.gdWakeupTxActive == rhs.gdWakeupTxActive + && lhs.gdWakeupTxIdle == rhs.gdWakeupTxIdle && lhs.gListenNoise == rhs.gListenNoise + && lhs.gMacroPerCycle == rhs.gMacroPerCycle + && lhs.gMaxWithoutClockCorrectionFatal == rhs.gMaxWithoutClockCorrectionFatal + && lhs.gMaxWithoutClockCorrectionPassive == rhs.gMaxWithoutClockCorrectionPassive + && lhs.gNumberOfMiniSlots == rhs.gNumberOfMiniSlots && lhs.gNumberOfStaticSlots == rhs.gNumberOfStaticSlots + && lhs.gPayloadLengthStatic == rhs.gPayloadLengthStatic + && lhs.gSyncFrameIDCountMax == rhs.gSyncFrameIDCountMax; } inline bool operator==(const FlexrayNodeParameters& lhs, const FlexrayNodeParameters& rhs) { return lhs.pAllowHaltDueToClock == rhs.pAllowHaltDueToClock - && lhs.pAllowPassiveToActive == rhs.pAllowPassiveToActive - && lhs.pChannels == rhs.pChannels - && lhs.pClusterDriftDamping == rhs.pClusterDriftDamping - && lhs.pdAcceptedStartupRange == rhs.pdAcceptedStartupRange - && lhs.pdListenTimeout == rhs.pdListenTimeout - && lhs.pKeySlotId == rhs.pKeySlotId - && lhs.pKeySlotOnlyEnabled == rhs.pKeySlotOnlyEnabled - && lhs.pKeySlotUsedForStartup == rhs.pKeySlotUsedForStartup - && lhs.pKeySlotUsedForSync == rhs.pKeySlotUsedForSync - && lhs.pLatestTx == rhs.pLatestTx - && lhs.pMacroInitialOffsetA == rhs.pMacroInitialOffsetA - && lhs.pMacroInitialOffsetB == rhs.pMacroInitialOffsetB - && lhs.pMicroInitialOffsetA == rhs.pMicroInitialOffsetA - && lhs.pMicroInitialOffsetB == rhs.pMicroInitialOffsetB - && lhs.pMicroPerCycle == rhs.pMicroPerCycle - && lhs.pOffsetCorrectionOut == rhs.pOffsetCorrectionOut - && lhs.pOffsetCorrectionStart == rhs.pOffsetCorrectionStart - && lhs.pRateCorrectionOut == rhs.pRateCorrectionOut - && lhs.pWakeupChannel == rhs.pWakeupChannel - && lhs.pWakeupPattern == rhs.pWakeupPattern - && lhs.pdMicrotick == rhs.pdMicrotick - && lhs.pSamplesPerMicrotick == rhs.pSamplesPerMicrotick; + && lhs.pAllowPassiveToActive == rhs.pAllowPassiveToActive && lhs.pChannels == rhs.pChannels + && lhs.pClusterDriftDamping == rhs.pClusterDriftDamping + && lhs.pdAcceptedStartupRange == rhs.pdAcceptedStartupRange && lhs.pdListenTimeout == rhs.pdListenTimeout + && lhs.pKeySlotId == rhs.pKeySlotId && lhs.pKeySlotOnlyEnabled == rhs.pKeySlotOnlyEnabled + && lhs.pKeySlotUsedForStartup == rhs.pKeySlotUsedForStartup + && lhs.pKeySlotUsedForSync == rhs.pKeySlotUsedForSync && lhs.pLatestTx == rhs.pLatestTx + && lhs.pMacroInitialOffsetA == rhs.pMacroInitialOffsetA + && lhs.pMacroInitialOffsetB == rhs.pMacroInitialOffsetB + && lhs.pMicroInitialOffsetA == rhs.pMicroInitialOffsetA + && lhs.pMicroInitialOffsetB == rhs.pMicroInitialOffsetB && lhs.pMicroPerCycle == rhs.pMicroPerCycle + && lhs.pOffsetCorrectionOut == rhs.pOffsetCorrectionOut + && lhs.pOffsetCorrectionStart == rhs.pOffsetCorrectionStart + && lhs.pRateCorrectionOut == rhs.pRateCorrectionOut && lhs.pWakeupChannel == rhs.pWakeupChannel + && lhs.pWakeupPattern == rhs.pWakeupPattern && lhs.pdMicrotick == rhs.pdMicrotick + && lhs.pSamplesPerMicrotick == rhs.pSamplesPerMicrotick; } inline bool operator==(const FlexrayTxBufferConfig& lhs, const FlexrayTxBufferConfig& rhs) { - return lhs.channels == rhs.channels - && lhs.slotId == rhs.slotId - && lhs.offset == rhs.offset - && lhs.repetition == rhs.repetition - && lhs.hasPayloadPreambleIndicator == rhs.hasPayloadPreambleIndicator - && lhs.headerCrc == rhs.headerCrc - && lhs.transmissionMode == rhs.transmissionMode; + return lhs.channels == rhs.channels && lhs.slotId == rhs.slotId && lhs.offset == rhs.offset + && lhs.repetition == rhs.repetition && lhs.hasPayloadPreambleIndicator == rhs.hasPayloadPreambleIndicator + && lhs.headerCrc == rhs.headerCrc && lhs.transmissionMode == rhs.transmissionMode; } inline FlexrayWakeupEvent::FlexrayWakeupEvent(const FlexraySymbolEvent& flexraySymbolEvent) diff --git a/SilKit/include/silkit/services/flexray/IFlexrayController.hpp b/SilKit/include/silkit/services/flexray/IFlexrayController.hpp index d8f16f89e..76c3ba43b 100644 --- a/SilKit/include/silkit/services/flexray/IFlexrayController.hpp +++ b/SilKit/include/silkit/services/flexray/IFlexrayController.hpp @@ -38,7 +38,7 @@ class IFlexrayController public: /*! \brief Generic FleyRay callback method */ - template + template using CallbackT = std::function; /*! Callback type to indicate that a FlexRay message has been received. diff --git a/SilKit/include/silkit/services/flexray/string_utils.hpp b/SilKit/include/silkit/services/flexray/string_utils.hpp old mode 100755 new mode 100644 index 754f781e0..459c290e4 --- a/SilKit/include/silkit/services/flexray/string_utils.hpp +++ b/SilKit/include/silkit/services/flexray/string_utils.hpp @@ -73,7 +73,7 @@ inline std::ostream& operator<<(std::ostream& out, FlexraySlotModeType msg); inline std::ostream& operator<<(std::ostream& out, FlexrayErrorModeType msg); inline std::ostream& operator<<(std::ostream& out, FlexrayStartupStateType msg); inline std::ostream& operator<<(std::ostream& out, FlexrayWakeupStatusType msg); - + // ================================================================================ // Inline Implementations @@ -286,52 +286,40 @@ std::ostream& operator<<(std::ostream& out, const FlexrayHeader& header) { using FlagMask = FlexrayHeader::FlagMask; using Flag = FlexrayHeader::Flag; - return out - << "Flexray::FlexrayHeader{f=[" - << ((header.flags & static_cast(Flag::SuFIndicator)) ? "U" : "-") - << ((header.flags & static_cast(Flag::SyFIndicator)) ? "Y" : "-") - << ((header.flags & static_cast(Flag::NFIndicator)) ? "-" : "N") - << ((header.flags & static_cast(Flag::PPIndicator)) ? "P" : "-") - << "],s=" << header.frameId - << ",l=" << (uint32_t)header.payloadLength - << ",crc=" << std::hex << header.headerCrc << std::dec - << ",c=" << (uint32_t)header.cycleCount - << "}"; + return out << "Flexray::FlexrayHeader{f=[" + << ((header.flags & static_cast(Flag::SuFIndicator)) ? "U" : "-") + << ((header.flags & static_cast(Flag::SyFIndicator)) ? "Y" : "-") + << ((header.flags & static_cast(Flag::NFIndicator)) ? "-" : "N") + << ((header.flags & static_cast(Flag::PPIndicator)) ? "P" : "-") << "],s=" << header.frameId + << ",l=" << (uint32_t)header.payloadLength << ",crc=" << std::hex << header.headerCrc << std::dec + << ",c=" << (uint32_t)header.cycleCount << "}"; } std::ostream& operator<<(std::ostream& out, const FlexraySymbolEvent& symbol) { auto timestamp = std::chrono::duration_cast>(symbol.timestamp); - return out - << "Flexray::FlexraySymbolEvent{pattern=" << symbol.pattern - << ", channel=" << symbol.channel - << " @ " << timestamp.count() << "ms}"; + return out << "Flexray::FlexraySymbolEvent{pattern=" << symbol.pattern << ", channel=" << symbol.channel << " @ " + << timestamp.count() << "ms}"; } std::ostream& operator<<(std::ostream& out, const FlexraySymbolTransmitEvent& symbol) { auto timestamp = std::chrono::duration_cast>(symbol.timestamp); - return out - << "Flexray::FlexraySymbolTransmitEvent{pattern=" << symbol.pattern - << ", channel=" << symbol.channel - << " @ " << timestamp.count() << "ms}"; + return out << "Flexray::FlexraySymbolTransmitEvent{pattern=" << symbol.pattern << ", channel=" << symbol.channel + << " @ " << timestamp.count() << "ms}"; } std::ostream& operator<<(std::ostream& out, const FlexrayCycleStartEvent& cycleStart) { auto timestamp = std::chrono::duration_cast>(cycleStart.timestamp); - return out - << "Flexray::FlexrayCycleStartEvent{t=" << timestamp.count() - << "ms, cycleCounter=" << static_cast(cycleStart.cycleCounter) - << "}"; + return out << "Flexray::FlexrayCycleStartEvent{t=" << timestamp.count() + << "ms, cycleCounter=" << static_cast(cycleStart.cycleCounter) << "}"; } std::ostream& operator<<(std::ostream& out, const FlexrayFrameEvent& msg) { auto timestamp = std::chrono::duration_cast>(msg.timestamp); out << "Flexray::FlexrayFrameEvent{" - << "ch=" << msg.channel - << ", " << msg.frame.header - << " @" << timestamp.count() << "ms"; + << "ch=" << msg.channel << ", " << msg.frame.header << " @" << timestamp.count() << "ms"; if (msg.frame.header.flags & static_cast(FlexrayHeader::Flag::NFIndicator)) { // if payload is valid, provide it as hex dump @@ -344,11 +332,8 @@ std::ostream& operator<<(std::ostream& out, const FlexrayFrameEvent& msg) std::ostream& operator<<(std::ostream& out, const FlexrayFrameTransmitEvent& msg) { auto timestamp = std::chrono::duration_cast>(msg.timestamp); - return out << "Flexray::FlexrayFrameTransmitEvent{" - << msg.frame.header - << ", ch=" << msg.channel - << ", txBuffer=" << msg.txBufferIndex - << " @" << timestamp.count() << "ms}"; + return out << "Flexray::FlexrayFrameTransmitEvent{" << msg.frame.header << ", ch=" << msg.channel + << ", txBuffer=" << msg.txBufferIndex << " @" << timestamp.count() << "ms}"; } std::ostream& operator<<(std::ostream& out, const FlexrayControllerConfig& /*msg*/) @@ -359,26 +344,19 @@ std::ostream& operator<<(std::ostream& out, const FlexrayControllerConfig& /*msg std::ostream& operator<<(std::ostream& out, const FlexrayTxBufferConfig& msg) { return out << "Flexray::FlexrayTxBufferConfig{" - << "ch=" << msg.channels - << ", slot=" << msg.slotId - << (msg.hasPayloadPreambleIndicator ? ", PP" : "") - << ", crc=" << msg.headerCrc - << ", off=" << msg.offset - << ", rep=" << msg.repetition - << ", txMode=" << msg.transmissionMode - << "}"; + << "ch=" << msg.channels << ", slot=" << msg.slotId << (msg.hasPayloadPreambleIndicator ? ", PP" : "") + << ", crc=" << msg.headerCrc << ", off=" << msg.offset << ", rep=" << msg.repetition + << ", txMode=" << msg.transmissionMode << "}"; } std::ostream& operator<<(std::ostream& out, const FlexrayTxBufferUpdate& msg) { out << "Flexray::FlexrayTxBufferUpdate{" - << "idx=" << msg.txBufferIndex - << ", payloadValid="; + << "idx=" << msg.txBufferIndex << ", payloadValid="; if (msg.payloadDataValid) { - out << "t, payload=[" - << Util::AsHexString(msg.payload).WithSeparator(" ").WithMaxLength(8) + out << "t, payload=[" << Util::AsHexString(msg.payload).WithSeparator(" ").WithMaxLength(8) << "], payloadSize=" << msg.payload.size(); } else @@ -392,23 +370,24 @@ std::ostream& operator<<(std::ostream& out, const FlexrayPocStatusEvent& msg) { auto timestamp = std::chrono::duration_cast>(msg.timestamp); return out << "Flexray::POCStatus{" - << "State=" << msg.state - << ", Freeze=" << msg.freeze - << " @" << timestamp.count() << "ms}"; + << "State=" << msg.state << ", Freeze=" << msg.freeze << " @" << timestamp.count() << "ms}"; } std::ostream& operator<<(std::ostream& out, FlexraySlotModeType msg) { - switch(msg) + switch (msg) { case FlexraySlotModeType::KeySlot: - out << "KeySlot"; break; + out << "KeySlot"; + break; case FlexraySlotModeType::AllPending: - out << "AllPending"; break; + out << "AllPending"; + break; case FlexraySlotModeType::All: - out << "All"; break; + out << "All"; + break; default: throw SilKit::TypeConversionError{}; @@ -421,13 +400,16 @@ std::ostream& operator<<(std::ostream& out, FlexrayErrorModeType msg) switch (msg) { case FlexrayErrorModeType::Active: - out << "Active"; break; + out << "Active"; + break; case FlexrayErrorModeType::Passive: - out << "Passive"; break; + out << "Passive"; + break; case FlexrayErrorModeType::CommHalt: - out << "CommHalt"; break; + out << "CommHalt"; + break; default: @@ -441,37 +423,48 @@ std::ostream& operator<<(std::ostream& out, FlexrayStartupStateType msg) switch (msg) { case FlexrayStartupStateType::Undefined: - out << "Undefined"; break; + out << "Undefined"; + break; case FlexrayStartupStateType::ColdStartListen: - out << "ColdStartListen"; break; + out << "ColdStartListen"; + break; case FlexrayStartupStateType::IntegrationColdstartCheck: - out << "IntegrationColdstartCheck"; break; + out << "IntegrationColdstartCheck"; + break; case FlexrayStartupStateType::ColdStartJoin: - out << "ColdStartJoin"; break; + out << "ColdStartJoin"; + break; case FlexrayStartupStateType::ColdStartCollisionResolution: - out << "ColdStartCollisionResolution"; break; + out << "ColdStartCollisionResolution"; + break; case FlexrayStartupStateType::ColdStartConsistencyCheck: - out << "ColdStartConsistencyCheck"; break; + out << "ColdStartConsistencyCheck"; + break; case FlexrayStartupStateType::IntegrationListen: - out << "IntegrationListen"; break; + out << "IntegrationListen"; + break; case FlexrayStartupStateType::InitializeSchedule: - out << "InitializeSchedule"; break; + out << "InitializeSchedule"; + break; case FlexrayStartupStateType::IntegrationConsistencyCheck: - out << "IntegrationConsistencyCheck"; break; + out << "IntegrationConsistencyCheck"; + break; case FlexrayStartupStateType::ColdStartGap: - out << "ColdStartGap"; break; + out << "ColdStartGap"; + break; case FlexrayStartupStateType::ExternalStartup: - out << "ExternalStartup"; break; + out << "ExternalStartup"; + break; default: throw SilKit::TypeConversionError{}; @@ -485,25 +478,32 @@ std::ostream& operator<<(std::ostream& out, FlexrayWakeupStatusType msg) switch (msg) { case FlexrayWakeupStatusType::Undefined: - out << "Undefined"; break; + out << "Undefined"; + break; case FlexrayWakeupStatusType::ReceivedHeader: - out << "ReceivedHeader"; break; + out << "ReceivedHeader"; + break; case FlexrayWakeupStatusType::ReceivedWup: - out << "ReceivedWup"; break; + out << "ReceivedWup"; + break; case FlexrayWakeupStatusType::CollisionHeader: - out << "CollisionHeader"; break; + out << "CollisionHeader"; + break; case FlexrayWakeupStatusType::CollisionWup: - out << "CollisionWup"; break; + out << "CollisionWup"; + break; case FlexrayWakeupStatusType::CollisionUnknown: - out << "CollisionUnknown"; break; + out << "CollisionUnknown"; + break; case FlexrayWakeupStatusType::Transmitted: - out << "Transmitted"; break; + out << "Transmitted"; + break; default: throw SilKit::TypeConversionError{}; } @@ -512,8 +512,6 @@ std::ostream& operator<<(std::ostream& out, FlexrayWakeupStatusType msg) } - - } // namespace Flexray } // namespace Services } // namespace SilKit diff --git a/SilKit/include/silkit/services/lin/ILinController.hpp b/SilKit/include/silkit/services/lin/ILinController.hpp old mode 100755 new mode 100644 index 298de6a56..0615fa158 --- a/SilKit/include/silkit/services/lin/ILinController.hpp +++ b/SilKit/include/silkit/services/lin/ILinController.hpp @@ -52,7 +52,6 @@ namespace Lin { class ILinController { public: - /*! \brief Generic LIN callback method */ template @@ -240,5 +239,3 @@ class ILinController } // namespace Lin } // namespace Services } // namespace SilKit - - diff --git a/SilKit/include/silkit/services/lin/LinDatatypes.hpp b/SilKit/include/silkit/services/lin/LinDatatypes.hpp old mode 100755 new mode 100644 index 07c006d79..0d5259c2e --- a/SilKit/include/silkit/services/lin/LinDatatypes.hpp +++ b/SilKit/include/silkit/services/lin/LinDatatypes.hpp @@ -95,15 +95,15 @@ inline auto GoToSleepFrame() -> LinFrame; * from a slave. * * *AUTOSAR Name:* Lin_FrameResponseType - */ + */ enum class LinFrameResponseType : SilKit_LinFrameResponseType { - //! Response is generated from this master node + //! Response is generated from this master node MasterResponse = SilKit_LinFrameResponseType_MasterResponse, - + //! Response is generated from a remote slave node SlaveResponse = SilKit_LinFrameResponseType_SlaveResponse, - + /*! Response is generated from one slave to and received by * another slave, for the master the response will be anonymous, * it does not have to receive the response. @@ -135,7 +135,7 @@ struct LinFrameResponse * If responseMode is LinFrameResponseMode::TxUnconditional, the frame data is used for the transaction. */ LinFrame frame; - //! Determines if the LinFrameResponse is used for transmission (TxUnconditional), reception (Rx) or + //! Determines if the LinFrameResponse is used for transmission (TxUnconditional), reception (Rx) or //! ignored (Unused). LinFrameResponseMode responseMode{LinFrameResponseMode::Unused}; }; @@ -264,7 +264,6 @@ struct LinControllerConfig * ILinController::SetFrameResponses(). */ std::vector frameResponses; - }; /*! The operational state of the controller, i.e., operational or @@ -310,6 +309,14 @@ struct LinGoToSleepEvent std::chrono::nanoseconds timestamp; //!< Time of the event. }; +/*! \brief Data type representing a request to perform an non-AUTOSAR send operation. +*/ +struct LinSendFrameHeaderRequest +{ + std::chrono::nanoseconds timestamp; //!< Time of the header request. + LinId id; //!< The LinId of the header to be transmitted +}; + // ================================================================================ // Inline Implementations // ================================================================================ @@ -327,23 +334,19 @@ inline auto GoToSleepFrame() -> LinFrame //! \brief Comparison operator for LinFrame inline bool operator==(const LinFrame& lhs, const LinFrame& rhs) { - return lhs.id == rhs.id - && lhs.checksumModel == rhs.checksumModel - && lhs.dataLength == rhs.dataLength - && lhs.data == rhs.data; + return lhs.id == rhs.id && lhs.checksumModel == rhs.checksumModel && lhs.dataLength == rhs.dataLength + && lhs.data == rhs.data; } //! \brief Comparison operator for LinFrameResponse inline bool operator==(const LinFrameResponse& lhs, const LinFrameResponse& rhs) { - return lhs.frame == rhs.frame - && lhs.responseMode == rhs.responseMode; + return lhs.frame == rhs.frame && lhs.responseMode == rhs.responseMode; } //! \brief Comparison operator for LinControllerConfig inline bool operator==(const LinControllerConfig& lhs, const LinControllerConfig& rhs) { - return lhs.controllerMode == rhs.controllerMode - && lhs.baudRate == rhs.baudRate - && lhs.frameResponses == rhs.frameResponses; + return lhs.controllerMode == rhs.controllerMode && lhs.baudRate == rhs.baudRate + && lhs.frameResponses == rhs.frameResponses; } } // namespace Lin diff --git a/SilKit/include/silkit/services/lin/fwd_decl.hpp b/SilKit/include/silkit/services/lin/fwd_decl.hpp old mode 100755 new mode 100644 index ed6661715..0428fa36a --- a/SilKit/include/silkit/services/lin/fwd_decl.hpp +++ b/SilKit/include/silkit/services/lin/fwd_decl.hpp @@ -23,7 +23,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SilKit { namespace Services { -namespace Lin { +namespace Lin { struct LinFrame; struct LinFrameResponse; diff --git a/SilKit/include/silkit/services/lin/string_utils.hpp b/SilKit/include/silkit/services/lin/string_utils.hpp old mode 100755 new mode 100644 index f1d4e823a..5cb8ecabb --- a/SilKit/include/silkit/services/lin/string_utils.hpp +++ b/SilKit/include/silkit/services/lin/string_utils.hpp @@ -184,7 +184,7 @@ std::ostream& operator<<(std::ostream& out, LinChecksumModel model) } std::ostream& operator<<(std::ostream& out, LinFrameResponseType responseType) - { +{ try { return out << to_string(responseType); @@ -196,7 +196,7 @@ std::ostream& operator<<(std::ostream& out, LinFrameResponseType responseType) } std::ostream& operator<<(std::ostream& out, LinFrameResponseMode responseMode) - { +{ try { return out << to_string(responseMode); @@ -247,19 +247,15 @@ std::ostream& operator<<(std::ostream& out, const LinFrame& frame) { //instead of ios::copyfmt (which set badbit) we use a temporary stream std::stringstream buf; - buf - << "Lin::LinFrame{id=" << static_cast(frame.id) - << ", cs=" << to_string(frame.checksumModel) - << ", dl=" << static_cast(frame.dataLength) - << ", d={" << Util::AsHexString(frame.data).WithSeparator(" ") - << "}}"; + buf << "Lin::LinFrame{id=" << static_cast(frame.id) << ", cs=" << to_string(frame.checksumModel) + << ", dl=" << static_cast(frame.dataLength) << ", d={" + << Util::AsHexString(frame.data).WithSeparator(" ") << "}}"; return out << buf.str(); } std::ostream& operator<<(std::ostream& out, const LinControllerConfig& controllerConfig) { - out << "Lin::LinControllerConfig{br=" << controllerConfig.baudRate - << ", mode=" << controllerConfig.controllerMode + out << "Lin::LinControllerConfig{br=" << controllerConfig.baudRate << ", mode=" << controllerConfig.controllerMode << ", responses=["; if (controllerConfig.frameResponses.size() > 0) { diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index 6c7dce2f5..ff17626cb 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -52,14 +52,29 @@ std::ostream& operator<<(std::ostream& outStream, const Level& level) { switch (level) { - case Level::Trace: outStream << "Trace"; break; - case Level::Debug: outStream << "Debug"; break; - case Level::Info: outStream << "Info"; break; - case Level::Warn: outStream << "Warn"; break; - case Level::Error: outStream << "Error"; break; - case Level::Critical: outStream << "Critical"; break; - case Level::Off: outStream << "Off"; break; - default: outStream << "Invalid Logging::Level"; + case Level::Trace: + outStream << "Trace"; + break; + case Level::Debug: + outStream << "Debug"; + break; + case Level::Info: + outStream << "Info"; + break; + case Level::Warn: + outStream << "Warn"; + break; + case Level::Error: + outStream << "Error"; + break; + case Level::Critical: + outStream << "Critical"; + break; + case Level::Off: + outStream << "Off"; + break; + default: + outStream << "Invalid Logging::Level"; } return outStream; } @@ -67,10 +82,7 @@ std::ostream& operator<<(std::ostream& outStream, const Level& level) inline Level from_string(const std::string& levelStr) { auto lowerCase = [](auto s) { - std::transform(s.begin(), - s.end(), - s.begin(), - [](unsigned char c){ return (unsigned char)std::tolower(c);}); + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (unsigned char)std::tolower(c); }); return s; }; auto logLevel = lowerCase(levelStr); diff --git a/SilKit/include/silkit/services/orchestration/ILifecycleService.hpp b/SilKit/include/silkit/services/orchestration/ILifecycleService.hpp index 16a524a6c..efac7059e 100644 --- a/SilKit/include/silkit/services/orchestration/ILifecycleService.hpp +++ b/SilKit/include/silkit/services/orchestration/ILifecycleService.hpp @@ -68,7 +68,6 @@ class ILifecycleService virtual ~ILifecycleService() = default; public: - /*! \brief Register a callback that is executed once all communication channels between participants * with a lifecycle have been set up and are ready for communication. * @@ -87,7 +86,7 @@ class ILifecycleService * CompleteCommunicationReadyHandlerAsync() method is called. Only then will the participant switch to the ParticipantState::ReadyToRun. * Note that CompleteCommunicationReadyHandlerAsync may not be called from within any CommunicationReadyHandler. * The CommunicationReadyHandler is executed in an internal thread and must not be blocked by the user. - */ + */ virtual void SetCommunicationReadyHandlerAsync(CommunicationReadyHandler handler) = 0; /*! \brief Notify that the async CommunicationReadyHandler is completed. diff --git a/SilKit/include/silkit/services/orchestration/ITimeSyncService.hpp b/SilKit/include/silkit/services/orchestration/ITimeSyncService.hpp old mode 100755 new mode 100644 index 0f10004c7..42e4796b1 --- a/SilKit/include/silkit/services/orchestration/ITimeSyncService.hpp +++ b/SilKit/include/silkit/services/orchestration/ITimeSyncService.hpp @@ -55,7 +55,8 @@ class ITimeSyncService * Throwing an error inside the handler will cause a call to * ReportError(). */ - virtual void SetSimulationStepHandlerAsync(SimulationStepHandler task, std::chrono::nanoseconds initialStepSize) = 0; + virtual void SetSimulationStepHandlerAsync(SimulationStepHandler task, + std::chrono::nanoseconds initialStepSize) = 0; /*! \brief Signal that the current simulation task is finished and the next simulation step can be processed. * * This method should only be used after calling SetSimulationStepHandlerAsync. diff --git a/SilKit/include/silkit/services/orchestration/OrchestrationDatatypes.hpp b/SilKit/include/silkit/services/orchestration/OrchestrationDatatypes.hpp old mode 100755 new mode 100644 index 1da9ee78e..b273285b3 --- a/SilKit/include/silkit/services/orchestration/OrchestrationDatatypes.hpp +++ b/SilKit/include/silkit/services/orchestration/OrchestrationDatatypes.hpp @@ -38,31 +38,31 @@ namespace Orchestration { enum class ParticipantState : SilKit_ParticipantState { //! An invalid participant state - Invalid = SilKit_ParticipantState_Invalid, + Invalid = SilKit_ParticipantState_Invalid, //! The controllers created state - ServicesCreated = SilKit_ParticipantState_ServicesCreated, + ServicesCreated = SilKit_ParticipantState_ServicesCreated, //! The communication initializing state - CommunicationInitializing = SilKit_ParticipantState_CommunicationInitializing, + CommunicationInitializing = SilKit_ParticipantState_CommunicationInitializing, //! The communication initialized state - CommunicationInitialized = SilKit_ParticipantState_CommunicationInitialized, + CommunicationInitialized = SilKit_ParticipantState_CommunicationInitialized, //! The initialized state - ReadyToRun = SilKit_ParticipantState_ReadyToRun, + ReadyToRun = SilKit_ParticipantState_ReadyToRun, //! The running state - Running = SilKit_ParticipantState_Running, + Running = SilKit_ParticipantState_Running, //! The paused state - Paused = SilKit_ParticipantState_Paused, + Paused = SilKit_ParticipantState_Paused, //! The stopping state - Stopping = SilKit_ParticipantState_Stopping, + Stopping = SilKit_ParticipantState_Stopping, //! The stopped state - Stopped = SilKit_ParticipantState_Stopped, + Stopped = SilKit_ParticipantState_Stopped, //! The error state - Error = SilKit_ParticipantState_Error, + Error = SilKit_ParticipantState_Error, //! The shutting down state - ShuttingDown = SilKit_ParticipantState_ShuttingDown, + ShuttingDown = SilKit_ParticipantState_ShuttingDown, //! The shutdown state - Shutdown = SilKit_ParticipantState_Shutdown, + Shutdown = SilKit_ParticipantState_Shutdown, //! The aborting state - Aborting = SilKit_ParticipantState_Aborting, + Aborting = SilKit_ParticipantState_Aborting, }; //! \brief Details about a participant state change. @@ -80,31 +80,31 @@ struct ParticipantStatus enum class SystemState : SilKit_SystemState { //! An invalid participant state - Invalid = SilKit_SystemState_Invalid, + Invalid = SilKit_SystemState_Invalid, //! The controllers created state - ServicesCreated = SilKit_SystemState_ServicesCreated, + ServicesCreated = SilKit_SystemState_ServicesCreated, //! The communication initializing state - CommunicationInitializing = SilKit_SystemState_CommunicationInitializing, + CommunicationInitializing = SilKit_SystemState_CommunicationInitializing, //! The communication initialized state - CommunicationInitialized = SilKit_SystemState_CommunicationInitialized, + CommunicationInitialized = SilKit_SystemState_CommunicationInitialized, //! The initialized state - ReadyToRun = SilKit_SystemState_ReadyToRun, + ReadyToRun = SilKit_SystemState_ReadyToRun, //! The running state - Running = SilKit_SystemState_Running, + Running = SilKit_SystemState_Running, //! The paused state - Paused = SilKit_SystemState_Paused, + Paused = SilKit_SystemState_Paused, //! The stopping state - Stopping = SilKit_SystemState_Stopping, + Stopping = SilKit_SystemState_Stopping, //! The stopped state - Stopped = SilKit_SystemState_Stopped, + Stopped = SilKit_SystemState_Stopped, //! The error state - Error = SilKit_SystemState_Error, + Error = SilKit_SystemState_Error, //! The shutting down state - ShuttingDown = SilKit_SystemState_ShuttingDown, + ShuttingDown = SilKit_SystemState_ShuttingDown, //! The shutdown state - Shutdown = SilKit_SystemState_Shutdown, + Shutdown = SilKit_SystemState_Shutdown, //! The aborting state - Aborting = SilKit_SystemState_Aborting, + Aborting = SilKit_SystemState_Aborting, }; //! \brief Details of the simulation workflow regarding lifecycle and participant coordination. @@ -118,11 +118,11 @@ struct WorkflowConfiguration enum class OperationMode : SilKit_OperationMode { //! An invalid operation mode - Invalid = SilKit_OperationMode_Invalid, + Invalid = SilKit_OperationMode_Invalid, //! The coordinated operation mode Coordinated = SilKit_OperationMode_Coordinated, //! The autonomous operation mode - Autonomous = SilKit_OperationMode_Autonomous, + Autonomous = SilKit_OperationMode_Autonomous, }; //! The lifecycle start configuration. diff --git a/SilKit/include/silkit/services/orchestration/string_utils.hpp b/SilKit/include/silkit/services/orchestration/string_utils.hpp index 69a92b4c9..d6e11d55b 100644 --- a/SilKit/include/silkit/services/orchestration/string_utils.hpp +++ b/SilKit/include/silkit/services/orchestration/string_utils.hpp @@ -83,7 +83,7 @@ std::string to_string(ParticipantState state) } throw SilKit::TypeConversionError{}; } - + std::string to_string(SystemState state) { switch (state) @@ -159,11 +159,8 @@ std::ostream& operator<<(std::ostream& out, const ParticipantStatus& status) localtime_r(&enterTime, &tmBuffer); #endif - out << "Orchestration::ParticipantStatus{" << status.participantName - << ", State=" << status.state - << ", Reason=" << status.enterReason - << ", Time=" << std::put_time(&tmBuffer, "%FT%T") - << "}"; + out << "Orchestration::ParticipantStatus{" << status.participantName << ", State=" << status.state + << ", Reason=" << status.enterReason << ", Time=" << std::put_time(&tmBuffer, "%FT%T") << "}"; return out; } @@ -181,7 +178,8 @@ std::ostream& operator<<(std::ostream& out, const WorkflowConfiguration& workflo bool first = true; for (auto&& p : workflowConfiguration.requiredParticipantNames) { - if (!first) out << ", "; + if (!first) + out << ", "; out << p; first = false; } diff --git a/SilKit/include/silkit/services/pubsub/PubSubDatatypes.hpp b/SilKit/include/silkit/services/pubsub/PubSubDatatypes.hpp index 75ce57f3e..3795c2ee7 100644 --- a/SilKit/include/silkit/services/pubsub/PubSubDatatypes.hpp +++ b/SilKit/include/silkit/services/pubsub/PubSubDatatypes.hpp @@ -43,10 +43,9 @@ struct DataMessageEvent }; //! \brief Callback type for new data reception callbacks -using DataMessageHandler = - std::function; +using DataMessageHandler = std::function; } // namespace PubSub } // namespace Services } // namespace SilKit - diff --git a/SilKit/include/silkit/services/pubsub/PubSubSpec.hpp b/SilKit/include/silkit/services/pubsub/PubSubSpec.hpp index 074d197e5..717fc8df9 100644 --- a/SilKit/include/silkit/services/pubsub/PubSubSpec.hpp +++ b/SilKit/include/silkit/services/pubsub/PubSubSpec.hpp @@ -57,11 +57,20 @@ class PubSubSpec inline void AddLabel(const std::string& key, const std::string& value, SilKit::Services::MatchingLabel::Kind kind); //! Get the topic of the PubSubSpec. - auto Topic() const -> const std::string& { return _topic; } + auto Topic() const -> const std::string& + { + return _topic; + } //! Get the media type of the PubSubSpec. - auto MediaType() const -> const std::string& { return _mediaType; } + auto MediaType() const -> const std::string& + { + return _mediaType; + } //! Get the labels of the PubSubSpec. - auto Labels() const -> const std::vector& { return _labels; } + auto Labels() const -> const std::vector& + { + return _labels; + } }; void PubSubSpec::AddLabel(const SilKit::Services::MatchingLabel& label) diff --git a/SilKit/include/silkit/services/pubsub/string_utils.hpp b/SilKit/include/silkit/services/pubsub/string_utils.hpp index 9fafffde6..e7c2bdb42 100644 --- a/SilKit/include/silkit/services/pubsub/string_utils.hpp +++ b/SilKit/include/silkit/services/pubsub/string_utils.hpp @@ -48,10 +48,8 @@ std::string to_string(const DataMessageEvent& msg) std::ostream& operator<<(std::ostream& out, const DataMessageEvent& msg) { - return out << "PubSub::DataMessageEvent{data=" - << Util::AsHexString(msg.data).WithSeparator(" ").WithMaxLength(16) - << ", size=" << msg.data.size() - << "}"; + return out << "PubSub::DataMessageEvent{data=" << Util::AsHexString(msg.data).WithSeparator(" ").WithMaxLength(16) + << ", size=" << msg.data.size() << "}"; } } // namespace PubSub diff --git a/SilKit/include/silkit/services/rpc/IRpcClient.hpp b/SilKit/include/silkit/services/rpc/IRpcClient.hpp index c18b54c73..6d80c0da1 100644 --- a/SilKit/include/silkit/services/rpc/IRpcClient.hpp +++ b/SilKit/include/silkit/services/rpc/IRpcClient.hpp @@ -62,8 +62,8 @@ class IRpcClient * \param userContext An optional user provided pointer that is * reobtained when receiving the call result. */ - virtual void CallWithTimeout(Util::Span data, - std::chrono::nanoseconds timeout, void* userContext = nullptr) = 0; + virtual void CallWithTimeout(Util::Span data, std::chrono::nanoseconds timeout, + void* userContext = nullptr) = 0; }; } // namespace Rpc diff --git a/SilKit/include/silkit/services/rpc/RpcDatatypes.hpp b/SilKit/include/silkit/services/rpc/RpcDatatypes.hpp index 604c2ffed..5de816312 100644 --- a/SilKit/include/silkit/services/rpc/RpcDatatypes.hpp +++ b/SilKit/include/silkit/services/rpc/RpcDatatypes.hpp @@ -45,7 +45,7 @@ enum class RpcCallStatus : SilKit_RpcCallStatus /*! \brief The Call lead to an internal RpcServer error. * This might happen if no CallHandler was specified for the RpcServer. */ - InternalServerError = SilKit_RpcCallStatus_InternalServerError, + InternalServerError = SilKit_RpcCallStatus_InternalServerError, /*! \brief The Call did run into a timeout and was canceled. * This might happen if a corresponding server crashed, ran into an error or took too long to answer the call */ diff --git a/SilKit/include/silkit/services/rpc/RpcSpec.hpp b/SilKit/include/silkit/services/rpc/RpcSpec.hpp index cbaba4447..f3c1b052c 100644 --- a/SilKit/include/silkit/services/rpc/RpcSpec.hpp +++ b/SilKit/include/silkit/services/rpc/RpcSpec.hpp @@ -40,11 +40,20 @@ class RpcSpec inline void AddLabel(const std::string& key, const std::string& value, SilKit::Services::MatchingLabel::Kind kind); //! Get the topic of the RpcSpec. - auto FunctionName() const -> const std::string& { return _functionName; } + auto FunctionName() const -> const std::string& + { + return _functionName; + } //! Get the media type of the RpcSpec. - auto MediaType() const -> const std::string& { return _mediaType; } + auto MediaType() const -> const std::string& + { + return _mediaType; + } //! Get the labels of the RpcSpec. - auto Labels() const -> const std::vector& { return _labels; } + auto Labels() const -> const std::vector& + { + return _labels; + } }; void RpcSpec::AddLabel(const SilKit::Services::MatchingLabel& label) diff --git a/SilKit/include/silkit/services/string_utils.hpp b/SilKit/include/silkit/services/string_utils.hpp index 3860d3205..71dae4822 100644 --- a/SilKit/include/silkit/services/string_utils.hpp +++ b/SilKit/include/silkit/services/string_utils.hpp @@ -64,6 +64,6 @@ std::ostream& operator<<(std::ostream& out, TransmitDirection direction) return out << "TransmitDirection{" << static_cast(direction) << "}"; } } - + } // namespace Services } // namespace SilKit diff --git a/SilKit/include/silkit/util/PrintableHexString.hpp b/SilKit/include/silkit/util/PrintableHexString.hpp old mode 100755 new mode 100644 index 18af1a9d1..7c1f38b87 --- a/SilKit/include/silkit/util/PrintableHexString.hpp +++ b/SilKit/include/silkit/util/PrintableHexString.hpp @@ -44,7 +44,8 @@ class PrintableHexString inline auto WithMaxLength(int64_t length) -> PrintableHexString& { - _maxLength = std::min(static_cast(length),_iterable.end() - _iterable.begin()); + _maxLength = + std::min(static_cast(length), _iterable.end() - _iterable.begin()); return *this; } @@ -65,18 +66,12 @@ class PrintableHexString //NB, we use a temporary stream because we don't want to modify the internal format state of out std::ostringstream oss; - oss << std::hex << std::setfill('0') - << std::setw(2) << static_cast(*begin); + oss << std::hex << std::setfill('0') << std::setw(2) << static_cast(*begin); if (_maxLength > 1) { - std::for_each(begin + 1, - end, - [&oss, this](auto chr) - { - oss << _separator << std::setw(2) << static_cast(chr); - } - ); + std::for_each(begin + 1, end, + [&oss, this](auto chr) { oss << _separator << std::setw(2) << static_cast(chr); }); } if (_maxLength < _iterable.end() - _iterable.begin()) { @@ -86,8 +81,7 @@ class PrintableHexString } private: - using difference_type = decltype(std::declval().end() - - std::declval().begin()); + using difference_type = decltype(std::declval().end() - std::declval().begin()); const IterableT& _iterable; difference_type _maxLength = (std::numeric_limits::max)(); diff --git a/SilKit/include/silkit/util/Span.hpp b/SilKit/include/silkit/util/Span.hpp index 81ef6849b..85e89640d 100644 --- a/SilKit/include/silkit/util/Span.hpp +++ b/SilKit/include/silkit/util/Span.hpp @@ -309,7 +309,7 @@ auto Span::size() const -> size_t template void Span::trim_front(size_t len) { - if(!(len <= _size)) + if (!(len <= _size)) { throw AssertionError("Span::trim_front assertion 'len <= _size' failed"); } @@ -320,7 +320,7 @@ void Span::trim_front(size_t len) template void Span::trim_back(size_t len) { - if(!(len <= _size)) + if (!(len <= _size)) { throw AssertionError("Span::trim_back assertion 'len <= _size' failed"); } diff --git a/SilKit/include/silkit/util/serdes/Deserializer.hpp b/SilKit/include/silkit/util/serdes/Deserializer.hpp index 502e509be..034f14f13 100644 --- a/SilKit/include/silkit/util/serdes/Deserializer.hpp +++ b/SilKit/include/silkit/util/serdes/Deserializer.hpp @@ -125,7 +125,10 @@ class Deserializer } /*! \brief Deserializes the start of a struct. */ - void BeginStruct() { Align(); } + void BeginStruct() + { + Align(); + } /*! \brief Deserializes the end of a struct. */ void EndStruct() {} @@ -134,7 +137,10 @@ class Deserializer * Note: Because the array size is serialized as well, dynamic arrays aka. lists are also supported. * \returns The size of the array (in elements). */ - auto BeginArray() -> std::size_t { return DeserializeAligned(sizeof(uint32_t)); } + auto BeginArray() -> std::size_t + { + return DeserializeAligned(sizeof(uint32_t)); + } /*! \brief Deserializes the end of an array or list. */ @@ -143,13 +149,22 @@ class Deserializer /*! \brief Deserializes the start of an optional value. * \returns `true` if the value is set, otherwise `false`. */ - auto BeginOptional() -> bool { return Deserialize(); } + auto BeginOptional() -> bool + { + return Deserialize(); + } /*! \brief Deserializes the end of an optional value. */ void EndOptional() {} - auto BeginUnion() -> int { throw SilKitError("Unions are currently not supported."); } - void EndUnion() { throw SilKitError("Unions are currently not supported."); } + auto BeginUnion() -> int + { + throw SilKitError("Unions are currently not supported."); + } + void EndUnion() + { + throw SilKitError("Unions are currently not supported."); + } /*! \brief Resets the buffer and replaces it with another one. * \param buffer The new data buffer. diff --git a/SilKit/include/silkit/util/serdes/Serializer.hpp b/SilKit/include/silkit/util/serdes/Serializer.hpp index 6f3202db6..c6b3b6d1e 100644 --- a/SilKit/include/silkit/util/serdes/Serializer.hpp +++ b/SilKit/include/silkit/util/serdes/Serializer.hpp @@ -54,7 +54,8 @@ class Serializer * \param bitSize The number of bits which shall be serialized. */ template ::value - && !std::is_same::type>::value, int>::type = 0> + && !std::is_same::type>::value, + int>::type = 0> void Serialize(T data, std::size_t bitSize) { auto byteSize = bitSize / 8; @@ -114,7 +115,10 @@ class Serializer } /*! \brief Serializes the start of a struct. */ - void BeginStruct() { Align(); } + void BeginStruct() + { + Align(); + } /*! \brief Serializes the end of a struct. */ void EndStruct() {} @@ -139,13 +143,22 @@ class Serializer * \param isAvailable `true` if the optional value is set, otherwise `false`. * If `true`, the optional value must be serialized afterwards. */ - void BeginOptional(bool isAvailable) { Serialize(isAvailable); } + void BeginOptional(bool isAvailable) + { + Serialize(isAvailable); + } /*! \brief Serializes the end of an optional value. */ void EndOptional() {} - void BeginUnion(int) { throw SilKitError("Unions are currently not supported."); } - void EndUnion() { throw SilKitError("Unions are currently not supported."); } + void BeginUnion(int) + { + throw SilKitError("Unions are currently not supported."); + } + void EndUnion() + { + throw SilKitError("Unions are currently not supported."); + } /*! \brief Resets the buffer. */ void Reset() diff --git a/SilKit/include/silkit/vendor/ISilKitRegistry.hpp b/SilKit/include/silkit/vendor/ISilKitRegistry.hpp old mode 100755 new mode 100644 index c87cd7014..77d6f8dcd --- a/SilKit/include/silkit/vendor/ISilKitRegistry.hpp +++ b/SilKit/include/silkit/vendor/ISilKitRegistry.hpp @@ -50,6 +50,6 @@ class ISilKitRegistry }; -}//end namespace Vector -}//end namespace Vendor -}//end namespace SilKit +} //end namespace Vector +} //end namespace Vendor +} //end namespace SilKit diff --git a/SilKit/source/CMakeLists.txt b/SilKit/source/CMakeLists.txt index 3e709e006..513a35526 100644 --- a/SilKit/source/CMakeLists.txt +++ b/SilKit/source/CMakeLists.txt @@ -41,10 +41,8 @@ set(GIT_DIR "${PROJECT_SOURCE_DIR}/../.git") set(GIT_HEAD_FILE "${GIT_DIR}/HEAD") set(VERSION_MACROS_HPP ${CMAKE_CURRENT_BINARY_DIR}/version_macros.hpp) if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/version_macros.hpp) - message(STATUS "SILKIT re-using deployed version_macros.hpp") - set(VERSION_MACROS_HPP ${CMAKE_CURRENT_LIST_DIR}/version_macros.hpp - CreateSilKitRegistryWithDashboard.cpp - CreateSilKitRegistryWithDashboard.hpp) + message(STATUS "SILKIT: using deployed version_macros.hpp") + set(VERSION_MACROS_HPP ${CMAKE_CURRENT_LIST_DIR}/version_macros.hpp) elseif(EXISTS "${GIT_HEAD_FILE}") configure_file( "MakeVersionMacros.cmake.in" @@ -60,7 +58,7 @@ elseif(EXISTS "${GIT_HEAD_FILE}") ) endif() else() - message(WARNING "Cannot determine hash of current git head!") + message(STATUS "SILKIT: Cannot determine hash of current git head! GIT_HEAD_HASH will be set to UNKNOWN") set(GIT_HEAD_HASH "UNKNOWN") configure_file( version_macros.hpp.in @@ -176,6 +174,7 @@ list(APPEND SilKitImplObjectLibraries O_SilKit_Core_VAsio O_SilKit_Experimental O_SilKit_Extensions + O_SilKit_Experimental_NetworkSimulatorInternals O_SilKit_Services_Can O_SilKit_Services_Ethernet O_SilKit_Services_Flexray @@ -188,6 +187,7 @@ list(APPEND SilKitImplObjectLibraries O_SilKit_Util_FileHelpers O_SilKit_Util_Filesystem O_SilKit_Util_SetThreadName + O_SilKit_Util_SignalHandler O_SilKit_Util_Uuid O_SilKit_Util_Uri O_SilKit_Util_LabelMatching @@ -254,6 +254,7 @@ elseif(UNIX AND NOT APPLE) PRIVATE -Wl,--build-id=sha1) endif() endif() + target_link_options(SilKit PRIVATE "LINKER:--version-script=${CMAKE_CURRENT_SOURCE_DIR}/silkit.map") endif() if ((CMAKE_CXX_COMPILER_ID STREQUAL GNU OR CMAKE_CXX_COMPILER_ID STREQUAL Clang) AND NOT SILKIT_USE_SYSTEM_LIBRARIES) diff --git a/SilKit/source/CreateParticipantImpl.cpp b/SilKit/source/CreateParticipantImpl.cpp index 535002fd9..7b1693aab 100644 --- a/SilKit/source/CreateParticipantImpl.cpp +++ b/SilKit/source/CreateParticipantImpl.cpp @@ -27,8 +27,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SilKit { auto CreateParticipantImpl(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri) - -> std::unique_ptr + const std::string& participantName, + const std::string& registryUri) -> std::unique_ptr { auto participant = Core::CreateParticipantInternal(std::move(participantConfig), participantName, registryUri); participant->JoinSilKitSimulation(); diff --git a/SilKit/source/CreateParticipantImpl.hpp b/SilKit/source/CreateParticipantImpl.hpp index 16e7bf0e8..bba5685a4 100644 --- a/SilKit/source/CreateParticipantImpl.hpp +++ b/SilKit/source/CreateParticipantImpl.hpp @@ -45,8 +45,8 @@ class IParticipantConfiguration; namespace SilKit { auto CreateParticipantImpl(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri) - -> std::unique_ptr; + const std::string& participantName, + const std::string& registryUri) -> std::unique_ptr; auto CreateParticipantImpl(std::shared_ptr participantConfig, const std::string& participantName) -> std::unique_ptr; diff --git a/SilKit/source/LegacyAbi.cpp b/SilKit/source/LegacyAbi.cpp index f67c12845..d29645365 100644 --- a/SilKit/source/LegacyAbi.cpp +++ b/SilKit/source/LegacyAbi.cpp @@ -157,8 +157,8 @@ SilKitAPI auto GitHash() -> const char* namespace SilKit { SilKitAPI auto CreateParticipant(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri) - -> std::unique_ptr + const std::string& participantName, + const std::string& registryUri) -> std::unique_ptr { return CreateParticipantImpl(std::move(participantConfig), participantName, registryUri); } diff --git a/SilKit/source/SilKitForceIncludes.cpp b/SilKit/source/SilKitForceIncludes.cpp index 24235bbc5..997d7cc16 100644 --- a/SilKit/source/SilKitForceIncludes.cpp +++ b/SilKit/source/SilKitForceIncludes.cpp @@ -51,8 +51,7 @@ void __silkit_force_include_experimental() SILKIT_UNUSED_ARG(systemController); // LinController extensions - auto handlerId = - SilKit::Experimental::Services::Lin::AddLinSlaveConfigurationHandler(nullptr, nullptr); + auto handlerId = SilKit::Experimental::Services::Lin::AddLinSlaveConfigurationHandler(nullptr, nullptr); SILKIT_UNUSED_ARG(handlerId); SilKit::Experimental::Services::Lin::RemoveLinSlaveConfigurationHandler(nullptr, SilKit::Util::HandlerId{}); auto slaveConfig = SilKit::Experimental::Services::Lin::GetSlaveConfiguration(nullptr); diff --git a/SilKit/source/capi/CMakeLists.txt b/SilKit/source/capi/CMakeLists.txt index 4d1e33d70..9d1f0f9d2 100644 --- a/SilKit/source/capi/CMakeLists.txt +++ b/SilKit/source/capi/CMakeLists.txt @@ -34,7 +34,7 @@ add_library(O_SilKit_Capi OBJECT CapiUtils.cpp CapiVendor.cpp CapiVersion.cpp - + CapiNetworkSimulator.cpp TypeConversion.hpp ) @@ -49,7 +49,6 @@ target_link_libraries(O_SilKit_Capi PRIVATE I_SilKit_VersionImpl ) - add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_CapiInterfaces.cpp LIBS S_SilKitImpl) add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_CapiCan.cpp LIBS O_SilKit_Services_Can S_SilKitImpl I_SilKit_Core_Mock_Participant) add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_CapiEthernet.cpp LIBS S_SilKitImpl I_SilKit_Core_Mock_Participant) @@ -64,4 +63,5 @@ add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_CapiParticipantStateH add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_CapiTimeSync.cpp LIBS S_SilKitImpl I_SilKit_Core_Mock_Participant) add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_CapiLin.cpp LIBS S_SilKitImpl I_SilKit_Core_Mock_Participant) add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_CapiSymbols.cpp LIBS S_SilKitImpl) +add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_CapiNetSim.cpp LIBS S_SilKitImpl I_SilKit_Core_Mock_Participant) diff --git a/SilKit/source/capi/CapiCan.cpp b/SilKit/source/capi/CapiCan.cpp old mode 100755 new mode 100644 index 339a0dec6..6549ab619 --- a/SilKit/source/capi/CapiCan.cpp +++ b/SilKit/source/capi/CapiCan.cpp @@ -30,8 +30,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "silkit/services/can/all.hpp" -SilKit_ReturnCode SilKitCALL SilKit_CanController_Create(SilKit_CanController** outController, SilKit_Participant* participant, - const char* cName, const char* cNetwork) +SilKit_ReturnCode SilKitCALL SilKit_CanController_Create(SilKit_CanController** outController, + SilKit_Participant* participant, const char* cName, + const char* cNetwork) try { ASSERT_VALID_OUT_PARAMETER(outController); @@ -48,8 +49,9 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_CanController_AddFrameHandler(SilKit_CanController* controller, void* context, - SilKit_CanFrameHandler_t callback, SilKit_Direction directionMask, - SilKit_HandlerId* outHandlerId) + SilKit_CanFrameHandler_t callback, + SilKit_Direction directionMask, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -58,33 +60,35 @@ try auto canController = reinterpret_cast(controller); *outHandlerId = (SilKit_HandlerId)canController->AddFrameHandler( - [context, controller, callback](SilKit::Services::Can::ICanController* /*ctrl*/, - const SilKit::Services::Can::CanFrameEvent& cppCanFrameEvent) { - SilKit_CanFrame frame{}; - SilKit_Struct_Init(SilKit_CanFrame, frame); - frame.id = cppCanFrameEvent.frame.canId; - frame.flags = cppCanFrameEvent.frame.flags; - frame.dlc = cppCanFrameEvent.frame.dlc; - frame.sdt = cppCanFrameEvent.frame.sdt; - frame.vcid = cppCanFrameEvent.frame.vcid; - frame.af = cppCanFrameEvent.frame.af; - frame.data = ToSilKitByteVector(cppCanFrameEvent.frame.dataField); - - SilKit_CanFrameEvent frameEvent{}; - SilKit_Struct_Init(SilKit_CanFrameEvent, frameEvent); - frameEvent.timestamp = cppCanFrameEvent.timestamp.count(); - frameEvent.frame = &frame; - frameEvent.direction = static_cast(cppCanFrameEvent.direction); - frameEvent.userContext = cppCanFrameEvent.userContext; - - callback(context, controller, &frameEvent); - }, directionMask); + [context, controller, callback](SilKit::Services::Can::ICanController* /*ctrl*/, + const SilKit::Services::Can::CanFrameEvent& cppCanFrameEvent) { + SilKit_CanFrame frame{}; + SilKit_Struct_Init(SilKit_CanFrame, frame); + frame.id = cppCanFrameEvent.frame.canId; + frame.flags = cppCanFrameEvent.frame.flags; + frame.dlc = cppCanFrameEvent.frame.dlc; + frame.sdt = cppCanFrameEvent.frame.sdt; + frame.vcid = cppCanFrameEvent.frame.vcid; + frame.af = cppCanFrameEvent.frame.af; + frame.data = ToSilKitByteVector(cppCanFrameEvent.frame.dataField); + + SilKit_CanFrameEvent frameEvent{}; + SilKit_Struct_Init(SilKit_CanFrameEvent, frameEvent); + frameEvent.timestamp = cppCanFrameEvent.timestamp.count(); + frameEvent.frame = &frame; + frameEvent.direction = static_cast(cppCanFrameEvent.direction); + frameEvent.userContext = cppCanFrameEvent.userContext; + + callback(context, controller, &frameEvent); + }, + directionMask); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveFrameHandler(SilKit_CanController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveFrameHandler(SilKit_CanController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -96,9 +100,11 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_CanController_AddFrameTransmitHandler(SilKit_CanController* controller, void* context, - SilKit_CanFrameTransmitHandler_t callback, - SilKit_CanTransmitStatus statusMask, SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_CanController_AddFrameTransmitHandler(SilKit_CanController* controller, + void* context, + SilKit_CanFrameTransmitHandler_t callback, + SilKit_CanTransmitStatus statusMask, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -107,23 +113,24 @@ try auto canController = reinterpret_cast(controller); *outHandlerId = (SilKit_HandlerId)canController->AddFrameTransmitHandler( - [callback, context, controller](SilKit::Services::Can::ICanController* /*ctrl*/, - const SilKit::Services::Can::CanFrameTransmitEvent& cppFrameTransmitEvent) { - SilKit_CanFrameTransmitEvent frameTransmitEvent{}; - SilKit_Struct_Init(SilKit_CanFrameTransmitEvent, frameTransmitEvent); - frameTransmitEvent.userContext = cppFrameTransmitEvent.userContext; - frameTransmitEvent.timestamp = cppFrameTransmitEvent.timestamp.count(); - frameTransmitEvent.status = (SilKit_CanTransmitStatus)cppFrameTransmitEvent.status; - frameTransmitEvent.canId = cppFrameTransmitEvent.canId; - callback(context, controller, &frameTransmitEvent); - }, - static_cast(statusMask)); + [callback, context, controller](SilKit::Services::Can::ICanController* /*ctrl*/, + const SilKit::Services::Can::CanFrameTransmitEvent& cppFrameTransmitEvent) { + SilKit_CanFrameTransmitEvent frameTransmitEvent{}; + SilKit_Struct_Init(SilKit_CanFrameTransmitEvent, frameTransmitEvent); + frameTransmitEvent.userContext = cppFrameTransmitEvent.userContext; + frameTransmitEvent.timestamp = cppFrameTransmitEvent.timestamp.count(); + frameTransmitEvent.status = (SilKit_CanTransmitStatus)cppFrameTransmitEvent.status; + frameTransmitEvent.canId = cppFrameTransmitEvent.canId; + callback(context, controller, &frameTransmitEvent); + }, + static_cast(statusMask)); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveFrameTransmitHandler(SilKit_CanController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveFrameTransmitHandler(SilKit_CanController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -136,7 +143,8 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_CanController_AddStateChangeHandler(SilKit_CanController* controller, void* context, - SilKit_CanStateChangeHandler_t callback, SilKit_HandlerId* outHandlerId) + SilKit_CanStateChangeHandler_t callback, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -145,20 +153,21 @@ try auto canController = reinterpret_cast(controller); *outHandlerId = (SilKit_HandlerId)canController->AddStateChangeHandler( - [callback, context, controller](SilKit::Services::Can::ICanController* /*ctrl*/, - const SilKit::Services::Can::CanStateChangeEvent cppStateChangeEvent) { - SilKit_CanStateChangeEvent stateChangeEvent; - SilKit_Struct_Init(SilKit_CanStateChangeEvent, stateChangeEvent); - stateChangeEvent.timestamp = cppStateChangeEvent.timestamp.count(); - stateChangeEvent.state = (SilKit_CanControllerState)cppStateChangeEvent.state; - callback(context, controller, &stateChangeEvent); - }); + [callback, context, controller](SilKit::Services::Can::ICanController* /*ctrl*/, + const SilKit::Services::Can::CanStateChangeEvent cppStateChangeEvent) { + SilKit_CanStateChangeEvent stateChangeEvent; + SilKit_Struct_Init(SilKit_CanStateChangeEvent, stateChangeEvent); + stateChangeEvent.timestamp = cppStateChangeEvent.timestamp.count(); + stateChangeEvent.state = (SilKit_CanControllerState)cppStateChangeEvent.state; + callback(context, controller, &stateChangeEvent); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveStateChangeHandler(SilKit_CanController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveStateChangeHandler(SilKit_CanController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -170,9 +179,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_CanController_AddErrorStateChangeHandler(SilKit_CanController* controller, void* context, - SilKit_CanErrorStateChangeHandler_t callback, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_CanController_AddErrorStateChangeHandler( + SilKit_CanController* controller, void* context, SilKit_CanErrorStateChangeHandler_t callback, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -181,21 +190,23 @@ try auto canController = reinterpret_cast(controller); auto cppHandlerId = canController->AddErrorStateChangeHandler( - [callback, context, controller](SilKit::Services::Can::ICanController* /*ctrl*/, - const SilKit::Services::Can::CanErrorStateChangeEvent cppErrorStateChangeEvent) { - SilKit_CanErrorStateChangeEvent errorStateChangeEvent; - SilKit_Struct_Init(SilKit_CanErrorStateChangeEvent, errorStateChangeEvent); - errorStateChangeEvent.timestamp = cppErrorStateChangeEvent.timestamp.count(); - errorStateChangeEvent.errorState = (SilKit_CanErrorState)cppErrorStateChangeEvent.errorState; - callback(context, controller, &errorStateChangeEvent); - }); + [callback, context, controller]( + SilKit::Services::Can::ICanController* /*ctrl*/, + const SilKit::Services::Can::CanErrorStateChangeEvent cppErrorStateChangeEvent) { + SilKit_CanErrorStateChangeEvent errorStateChangeEvent; + SilKit_Struct_Init(SilKit_CanErrorStateChangeEvent, errorStateChangeEvent); + errorStateChangeEvent.timestamp = cppErrorStateChangeEvent.timestamp.count(); + errorStateChangeEvent.errorState = (SilKit_CanErrorState)cppErrorStateChangeEvent.errorState; + callback(context, controller, &errorStateChangeEvent); + }); *outHandlerId = static_cast(cppHandlerId); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveErrorStateChangeHandler(SilKit_CanController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_CanController_RemoveErrorStateChangeHandler(SilKit_CanController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -207,7 +218,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_CanController_SetBaudRate(SilKit_CanController* controller, uint32_t rate, uint32_t fdRate, uint32_t xlRate) +SilKit_ReturnCode SilKitCALL SilKit_CanController_SetBaudRate(SilKit_CanController* controller, uint32_t rate, + uint32_t fdRate, uint32_t xlRate) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -219,7 +231,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_CanController_SendFrame(SilKit_CanController* controller, SilKit_CanFrame* message, void* transmitContext) +SilKit_ReturnCode SilKitCALL SilKit_CanController_SendFrame(SilKit_CanController* controller, SilKit_CanFrame* message, + void* transmitContext) try { ASSERT_VALID_POINTER_PARAMETER(controller); diff --git a/SilKit/source/capi/CapiDataPubSub.cpp b/SilKit/source/capi/CapiDataPubSub.cpp index ae5a3c8ac..647345db4 100644 --- a/SilKit/source/capi/CapiDataPubSub.cpp +++ b/SilKit/source/capi/CapiDataPubSub.cpp @@ -33,10 +33,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include -SilKit_ReturnCode SilKitCALL SilKit_DataPublisher_Create(SilKit_DataPublisher** outPublisher, SilKit_Participant* participant, - const char* controllerName, - SilKit_DataSpec* dataSpec, - uint8_t history) +SilKit_ReturnCode SilKitCALL SilKit_DataPublisher_Create(SilKit_DataPublisher** outPublisher, + SilKit_Participant* participant, const char* controllerName, + SilKit_DataSpec* dataSpec, uint8_t history) try { ASSERT_VALID_OUT_PARAMETER(outPublisher); @@ -68,10 +67,10 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_DataSubscriber_Create(SilKit_DataSubscriber** outSubscriber, SilKit_Participant* participant, - const char* controllerName, SilKit_DataSpec* dataSpec, - void* defaultDataHandlerContext, - SilKit_DataMessageHandler_t defaultDataHandler) +SilKit_ReturnCode SilKitCALL SilKit_DataSubscriber_Create(SilKit_DataSubscriber** outSubscriber, + SilKit_Participant* participant, const char* controllerName, + SilKit_DataSpec* dataSpec, void* defaultDataHandlerContext, + SilKit_DataMessageHandler_t defaultDataHandler) try { ASSERT_VALID_OUT_PARAMETER(outSubscriber); @@ -91,19 +90,18 @@ try uint8_t* payloadPointer = nullptr; if (cppDataMessageEvent.data.size() > 0) { - payloadPointer = (uint8_t*) &(cppDataMessageEvent.data[0]); + payloadPointer = (uint8_t*)&(cppDataMessageEvent.data[0]); } SilKit_DataMessageEvent cDataMessageEvent; SilKit_Struct_Init(SilKit_DataMessageEvent, cDataMessageEvent); cDataMessageEvent.timestamp = cppDataMessageEvent.timestamp.count(); - cDataMessageEvent.data = { payloadPointer, cppDataMessageEvent.data.size() }; + cDataMessageEvent.data = {payloadPointer, cppDataMessageEvent.data.size()}; defaultDataHandler(defaultDataHandlerContext, cSubscriber, &cDataMessageEvent); }; - auto dataSubscriber = cppParticipant->CreateDataSubscriber(controllerName, cppDataNodeSpec, - cppDefaultDataHandler); + auto dataSubscriber = cppParticipant->CreateDataSubscriber(controllerName, cppDataNodeSpec, cppDefaultDataHandler); *outSubscriber = reinterpret_cast(dataSubscriber); return SilKit_ReturnCode_SUCCESS; } @@ -111,7 +109,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_DataSubscriber_SetDataMessageHandler(SilKit_DataSubscriber* self, void* context, - SilKit_DataMessageHandler_t dataHandler) + SilKit_DataMessageHandler_t dataHandler) try { ASSERT_VALID_POINTER_PARAMETER(self); @@ -119,21 +117,21 @@ try auto cppSubscriber = reinterpret_cast(self); cppSubscriber->SetDataMessageHandler( - [dataHandler, context](SilKit::Services::PubSub::IDataSubscriber* cppSubscriberHandler, - const SilKit::Services::PubSub::DataMessageEvent& cppDataMessageEvent) { - auto* cSubscriber = reinterpret_cast(cppSubscriberHandler); - uint8_t* payloadPointer = nullptr; - if (cppDataMessageEvent.data.size() > 0) - { - payloadPointer = (uint8_t*)&(cppDataMessageEvent.data[0]); - } - SilKit_DataMessageEvent cDataMessageEvent; - SilKit_Struct_Init(SilKit_DataMessageEvent, cDataMessageEvent); - cDataMessageEvent.timestamp = cppDataMessageEvent.timestamp.count(); - cDataMessageEvent.data = { payloadPointer, cppDataMessageEvent.data.size() }; - - dataHandler(context, cSubscriber, &cDataMessageEvent); - }); + [dataHandler, context](SilKit::Services::PubSub::IDataSubscriber* cppSubscriberHandler, + const SilKit::Services::PubSub::DataMessageEvent& cppDataMessageEvent) { + auto* cSubscriber = reinterpret_cast(cppSubscriberHandler); + uint8_t* payloadPointer = nullptr; + if (cppDataMessageEvent.data.size() > 0) + { + payloadPointer = (uint8_t*)&(cppDataMessageEvent.data[0]); + } + SilKit_DataMessageEvent cDataMessageEvent; + SilKit_Struct_Init(SilKit_DataMessageEvent, cDataMessageEvent); + cDataMessageEvent.timestamp = cppDataMessageEvent.timestamp.count(); + cDataMessageEvent.data = {payloadPointer, cppDataMessageEvent.data.size()}; + + dataHandler(context, cSubscriber, &cDataMessageEvent); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS diff --git a/SilKit/source/capi/CapiEthernet.cpp b/SilKit/source/capi/CapiEthernet.cpp old mode 100755 new mode 100644 index 6ebbf30f0..76e996ee2 --- a/SilKit/source/capi/CapiEthernet.cpp +++ b/SilKit/source/capi/CapiEthernet.cpp @@ -29,8 +29,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "CapiImpl.hpp" -SilKit_ReturnCode SilKitCALL SilKit_EthernetController_Create(SilKit_EthernetController** outController, SilKit_Participant* participant, - const char* name, const char* network) +SilKit_ReturnCode SilKitCALL SilKit_EthernetController_Create(SilKit_EthernetController** outController, + SilKit_Participant* participant, const char* name, + const char* network) try { ASSERT_VALID_OUT_PARAMETER(outController); @@ -70,10 +71,11 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddFrameHandler(SilKit_EthernetController* controller, void* context, - SilKit_EthernetFrameHandler_t handler, - SilKit_Direction directionMask, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddFrameHandler(SilKit_EthernetController* controller, + void* context, + SilKit_EthernetFrameHandler_t handler, + SilKit_Direction directionMask, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -81,34 +83,34 @@ try ASSERT_VALID_OUT_PARAMETER(outHandlerId); auto cppController = reinterpret_cast(controller); - auto cppHandlerId = cppController->AddFrameHandler( - [handler, context, controller](auto* /*ctrl*/, - const auto& cppFrameEvent) { - auto& cppFrame = cppFrameEvent.frame; - auto* dataPointer = !cppFrame.raw.empty() ? cppFrame.raw.data() : nullptr; + auto cppHandlerId = + cppController->AddFrameHandler([handler, context, controller](auto* /*ctrl*/, const auto& cppFrameEvent) { + auto& cppFrame = cppFrameEvent.frame; + auto* dataPointer = !cppFrame.raw.empty() ? cppFrame.raw.data() : nullptr; - SilKit_EthernetFrame frame; - SilKit_Struct_Init(SilKit_EthernetFrame, frame); + SilKit_EthernetFrame frame; + SilKit_Struct_Init(SilKit_EthernetFrame, frame); - frame.raw = {dataPointer, cppFrame.raw.size()}; + frame.raw = {dataPointer, cppFrame.raw.size()}; - SilKit_EthernetFrameEvent frameEvent; - SilKit_Struct_Init(SilKit_EthernetFrameEvent, frameEvent); + SilKit_EthernetFrameEvent frameEvent; + SilKit_Struct_Init(SilKit_EthernetFrameEvent, frameEvent); - frameEvent.ethernetFrame = &frame; - frameEvent.timestamp = cppFrameEvent.timestamp.count(); - frameEvent.direction = static_cast(cppFrameEvent.direction); - frameEvent.userContext = cppFrameEvent.userContext; + frameEvent.ethernetFrame = &frame; + frameEvent.timestamp = cppFrameEvent.timestamp.count(); + frameEvent.direction = static_cast(cppFrameEvent.direction); + frameEvent.userContext = cppFrameEvent.userContext; - handler(context, controller, &frameEvent); - }, directionMask); + handler(context, controller, &frameEvent); + }, directionMask); *outHandlerId = static_cast(cppHandlerId); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveFrameHandler(SilKit_EthernetController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveFrameHandler(SilKit_EthernetController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -120,11 +122,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddFrameTransmitHandler(SilKit_EthernetController* controller, - void* context, - SilKit_EthernetFrameTransmitHandler_t handler, - SilKit_EthernetTransmitStatus transmitStatusMask, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddFrameTransmitHandler( + SilKit_EthernetController* controller, void* context, SilKit_EthernetFrameTransmitHandler_t handler, + SilKit_EthernetTransmitStatus transmitStatusMask, SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -138,13 +138,13 @@ try auto cppController = reinterpret_cast(controller); auto cppHandlerId = cppController->AddFrameTransmitHandler( [context, handler](IEthernetController* controller, const EthernetFrameTransmitEvent& frameTransmitEvent) { - SilKit_EthernetFrameTransmitEvent cEvent; - SilKit_Struct_Init(SilKit_EthernetFrameTransmitEvent, cEvent); - cEvent.status = (SilKit_EthernetTransmitStatus)frameTransmitEvent.status; - cEvent.timestamp = frameTransmitEvent.timestamp.count(); - cEvent.userContext = frameTransmitEvent.userContext; - handler(context, reinterpret_cast(controller), &cEvent); - }, transmitStatusMask); + SilKit_EthernetFrameTransmitEvent cEvent; + SilKit_Struct_Init(SilKit_EthernetFrameTransmitEvent, cEvent); + cEvent.status = (SilKit_EthernetTransmitStatus)frameTransmitEvent.status; + cEvent.timestamp = frameTransmitEvent.timestamp.count(); + cEvent.userContext = frameTransmitEvent.userContext; + handler(context, reinterpret_cast(controller), &cEvent); + }, transmitStatusMask); *outHandlerId = static_cast(cppHandlerId); return SilKit_ReturnCode_SUCCESS; } @@ -152,7 +152,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveFrameTransmitHandler(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId) + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -164,9 +164,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddStateChangeHandler(SilKit_EthernetController* controller, void* context, - SilKit_EthernetStateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddStateChangeHandler( + SilKit_EthernetController* controller, void* context, SilKit_EthernetStateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -177,12 +177,12 @@ try auto cppHandlerId = cppController->AddStateChangeHandler( [handler, context, controller](SilKit::Services::Ethernet::IEthernetController*, const SilKit::Services::Ethernet::EthernetStateChangeEvent& stateChangeEvent) { - SilKit_EthernetStateChangeEvent cStateChangeEvent; - SilKit_Struct_Init(SilKit_EthernetStateChangeEvent, cStateChangeEvent); - cStateChangeEvent.timestamp = stateChangeEvent.timestamp.count(); - cStateChangeEvent.state = (SilKit_EthernetState)stateChangeEvent.state; - handler(context, controller, &cStateChangeEvent); - }); + SilKit_EthernetStateChangeEvent cStateChangeEvent; + SilKit_Struct_Init(SilKit_EthernetStateChangeEvent, cStateChangeEvent); + cStateChangeEvent.timestamp = stateChangeEvent.timestamp.count(); + cStateChangeEvent.state = (SilKit_EthernetState)stateChangeEvent.state; + handler(context, controller, &cStateChangeEvent); + }); *outHandlerId = static_cast(cppHandlerId); return SilKit_ReturnCode_SUCCESS; } @@ -190,7 +190,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveStateChangeHandler(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId) + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -202,9 +202,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddBitrateChangeHandler(SilKit_EthernetController* controller, void* context, - SilKit_EthernetBitrateChangeHandler_t handler, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_EthernetController_AddBitrateChangeHandler( + SilKit_EthernetController* controller, void* context, SilKit_EthernetBitrateChangeHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -213,15 +213,16 @@ try auto cppController = reinterpret_cast(controller); auto cppHandlerId = cppController->AddBitrateChangeHandler( - [handler, context, controller](SilKit::Services::Ethernet::IEthernetController*, - const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& bitrateChangeEvent) { - SilKit_EthernetBitrateChangeEvent cBitrateChangeEvent; - SilKit_Struct_Init(SilKit_EthernetBitrateChangeEvent, cBitrateChangeEvent); - cBitrateChangeEvent.timestamp = bitrateChangeEvent.timestamp.count(); - cBitrateChangeEvent.bitrate = (SilKit_EthernetBitrate)bitrateChangeEvent.bitrate; - - handler(context, controller, &cBitrateChangeEvent); - }); + [handler, context, controller]( + SilKit::Services::Ethernet::IEthernetController*, + const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& bitrateChangeEvent) { + SilKit_EthernetBitrateChangeEvent cBitrateChangeEvent; + SilKit_Struct_Init(SilKit_EthernetBitrateChangeEvent, cBitrateChangeEvent); + cBitrateChangeEvent.timestamp = bitrateChangeEvent.timestamp.count(); + cBitrateChangeEvent.bitrate = (SilKit_EthernetBitrate)bitrateChangeEvent.bitrate; + + handler(context, controller, &cBitrateChangeEvent); + }); *outHandlerId = static_cast(cppHandlerId); return SilKit_ReturnCode_SUCCESS; } @@ -229,7 +230,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_EthernetController_RemoveBitrateChangeHandler(SilKit_EthernetController* controller, - SilKit_HandlerId handlerId) + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -241,8 +242,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_EthernetController_SendFrame(SilKit_EthernetController* controller, SilKit_EthernetFrame* frame, - void* userContext) +SilKit_ReturnCode SilKitCALL SilKit_EthernetController_SendFrame(SilKit_EthernetController* controller, + SilKit_EthernetFrame* frame, void* userContext) try { ASSERT_VALID_POINTER_PARAMETER(controller); diff --git a/SilKit/source/capi/CapiFlexray.cpp b/SilKit/source/capi/CapiFlexray.cpp old mode 100755 new mode 100644 index 5a56e2632..8404dce5f --- a/SilKit/source/capi/CapiFlexray.cpp +++ b/SilKit/source/capi/CapiFlexray.cpp @@ -44,7 +44,7 @@ void assign(SilKit::Services::Flexray::FlexrayTxBufferConfig& cppConfig, const S } void assign(SilKit::Services::Flexray::FlexrayClusterParameters& cppClusterParameters, - const SilKit_FlexrayClusterParameters* clusterParameters) + const SilKit_FlexrayClusterParameters* clusterParameters) { cppClusterParameters.gColdstartAttempts = clusterParameters->gColdstartAttempts; cppClusterParameters.gCycleCountMax = clusterParameters->gCycleCountMax; @@ -69,7 +69,7 @@ void assign(SilKit::Services::Flexray::FlexrayClusterParameters& cppClusterParam } void assign(SilKit::Services::Flexray::FlexrayNodeParameters& cppNodeParameters, - const SilKit_FlexrayNodeParameters* nodeParameters) + const SilKit_FlexrayNodeParameters* nodeParameters) { cppNodeParameters.pAllowHaltDueToClock = nodeParameters->pAllowHaltDueToClock; cppNodeParameters.pAllowPassiveToActive = nodeParameters->pAllowPassiveToActive; @@ -109,11 +109,12 @@ void assign(SilKit::Services::Flexray::FlexrayControllerConfig& cppConfig, const } } -}//namespace +} //namespace -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_Create(SilKit_FlexrayController** outController, SilKit_Participant* participant, - const char* name, const char* network) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_Create(SilKit_FlexrayController** outController, + SilKit_Participant* participant, const char* name, + const char* network) try { ASSERT_VALID_OUT_PARAMETER(outController); @@ -134,7 +135,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_Configure(SilKit_FlexrayController* controller, - const SilKit_FlexrayControllerConfig* config) + const SilKit_FlexrayControllerConfig* config) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -156,8 +157,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_ReconfigureTxBuffer(SilKit_FlexrayController* controller, uint16_t txBufferIdx, - const SilKit_FlexrayTxBufferConfig* config) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_ReconfigureTxBuffer(SilKit_FlexrayController* controller, + uint16_t txBufferIdx, + const SilKit_FlexrayTxBufferConfig* config) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -176,7 +178,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_UpdateTxBuffer(SilKit_FlexrayController* controller, - const SilKit_FlexrayTxBufferUpdate* update) + const SilKit_FlexrayTxBufferUpdate* update) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -198,7 +200,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_ExecuteCmd(SilKit_FlexrayController* controller, SilKit_FlexrayChiCommand cmd) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_ExecuteCmd(SilKit_FlexrayController* controller, + SilKit_FlexrayChiCommand cmd) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -232,8 +235,10 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddFrameHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayFrameHandler_t handler, SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddFrameHandler(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexrayFrameHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -242,37 +247,39 @@ try const auto cppController = reinterpret_cast(controller); *outHandlerId = (SilKit_HandlerId)cppController->AddFrameHandler( - [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, const SilKit::Services::Flexray::FlexrayFrameEvent& msg) { - SilKit_FlexrayFrameEvent message; - SilKit_FlexrayFrame frame; - SilKit_FlexrayHeader header; - - SilKit_Struct_Init(SilKit_FlexrayFrameEvent, message); - SilKit_Struct_Init(SilKit_FlexrayFrame, frame); - SilKit_Struct_Init(SilKit_FlexrayHeader, header); - - header.cycleCount = msg.frame.header.cycleCount; - header.frameId = msg.frame.header.frameId; - header.flags = msg.frame.header.flags; - header.headerCrc = msg.frame.header.headerCrc; - header.payloadLength = msg.frame.header.payloadLength; - - frame.header = &header; - frame.payload.data = (uint8_t*)msg.frame.payload.data(); - frame.payload.size = (uint32_t)msg.frame.payload.size(); - - message.timestamp = msg.timestamp.count(); - message.channel = (SilKit_FlexrayChannel)msg.channel; - message.frame = &frame; - - handler(context, ctrl, &message); - }); + [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, + const SilKit::Services::Flexray::FlexrayFrameEvent& msg) { + SilKit_FlexrayFrameEvent message; + SilKit_FlexrayFrame frame; + SilKit_FlexrayHeader header; + + SilKit_Struct_Init(SilKit_FlexrayFrameEvent, message); + SilKit_Struct_Init(SilKit_FlexrayFrame, frame); + SilKit_Struct_Init(SilKit_FlexrayHeader, header); + + header.cycleCount = msg.frame.header.cycleCount; + header.frameId = msg.frame.header.frameId; + header.flags = msg.frame.header.flags; + header.headerCrc = msg.frame.header.headerCrc; + header.payloadLength = msg.frame.header.payloadLength; + + frame.header = &header; + frame.payload.data = (uint8_t*)msg.frame.payload.data(); + frame.payload.size = (uint32_t)msg.frame.payload.size(); + + message.timestamp = msg.timestamp.count(); + message.channel = (SilKit_FlexrayChannel)msg.channel; + message.frame = &frame; + + handler(context, ctrl, &message); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveFrameHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveFrameHandler(SilKit_FlexrayController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -284,9 +291,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddFrameTransmitHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayFrameTransmitHandler_t handler, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddFrameTransmitHandler( + SilKit_FlexrayController* controller, void* context, SilKit_FlexrayFrameTransmitHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -297,37 +304,37 @@ try *outHandlerId = (SilKit_HandlerId)cppController->AddFrameTransmitHandler( [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, const SilKit::Services::Flexray::FlexrayFrameTransmitEvent& msg) { - SilKit_FlexrayFrameTransmitEvent message; - SilKit_FlexrayFrame frame; - SilKit_FlexrayHeader header; - - SilKit_Struct_Init(SilKit_FlexrayFrameEvent, message); - SilKit_Struct_Init(SilKit_FlexrayFrame, frame); - SilKit_Struct_Init(SilKit_FlexrayHeader, header); - - header.cycleCount = msg.frame.header.cycleCount; - header.frameId = msg.frame.header.frameId; - header.flags = msg.frame.header.flags; - header.headerCrc = msg.frame.header.headerCrc; - header.payloadLength = msg.frame.header.payloadLength; - - frame.payload.data = (uint8_t*)msg.frame.payload.data(); - frame.payload.size = (uint32_t)msg.frame.payload.size(); - frame.header = &header; - - message.timestamp = msg.timestamp.count(); - message.txBufferIndex = msg.txBufferIndex; - message.channel = (SilKit_FlexrayChannel)msg.channel; - message.frame = &frame; - handler(context, ctrl, &message); - }); + SilKit_FlexrayFrameTransmitEvent message; + SilKit_FlexrayFrame frame; + SilKit_FlexrayHeader header; + + SilKit_Struct_Init(SilKit_FlexrayFrameEvent, message); + SilKit_Struct_Init(SilKit_FlexrayFrame, frame); + SilKit_Struct_Init(SilKit_FlexrayHeader, header); + + header.cycleCount = msg.frame.header.cycleCount; + header.frameId = msg.frame.header.frameId; + header.flags = msg.frame.header.flags; + header.headerCrc = msg.frame.header.headerCrc; + header.payloadLength = msg.frame.header.payloadLength; + + frame.payload.data = (uint8_t*)msg.frame.payload.data(); + frame.payload.size = (uint32_t)msg.frame.payload.size(); + frame.header = &header; + + message.timestamp = msg.timestamp.count(); + message.txBufferIndex = msg.txBufferIndex; + message.channel = (SilKit_FlexrayChannel)msg.channel; + message.frame = &frame; + handler(context, ctrl, &message); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveFrameTransmitHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId) + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -339,8 +346,10 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddWakeupHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayWakeupHandler_t handler, SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddWakeupHandler(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexrayWakeupHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -349,21 +358,23 @@ try const auto cppController = reinterpret_cast(controller); *outHandlerId = (SilKit_HandlerId)cppController->AddWakeupHandler( - [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, const SilKit::Services::Flexray::FlexrayWakeupEvent& msg) { - SilKit_FlexrayWakeupEvent message; - SilKit_Struct_Init(SilKit_FlexrayWakeupEvent, message); - - message.timestamp = msg.timestamp.count(); - message.channel = (SilKit_FlexrayChannel)msg.channel; - message.pattern = (SilKit_FlexraySymbolPattern)msg.pattern; - handler(context, ctrl, &message); - }); + [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, + const SilKit::Services::Flexray::FlexrayWakeupEvent& msg) { + SilKit_FlexrayWakeupEvent message; + SilKit_Struct_Init(SilKit_FlexrayWakeupEvent, message); + + message.timestamp = msg.timestamp.count(); + message.channel = (SilKit_FlexrayChannel)msg.channel; + message.pattern = (SilKit_FlexraySymbolPattern)msg.pattern; + handler(context, ctrl, &message); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveWakeupHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveWakeupHandler(SilKit_FlexrayController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -375,9 +386,10 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddPocStatusHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayPocStatusHandler_t handler, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddPocStatusHandler(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexrayPocStatusHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -388,27 +400,27 @@ try *outHandlerId = (SilKit_HandlerId)cppController->AddPocStatusHandler( [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, const SilKit::Services::Flexray::FlexrayPocStatusEvent& msg) { - SilKit_FlexrayPocStatusEvent message; - SilKit_Struct_Init(SilKit_FlexrayPocStatusEvent, message); - message.timestamp = msg.timestamp.count(); - message.state = (SilKit_FlexrayPocState)msg.state; - message.chiHaltRequest = msg.chiHaltRequest; - message.coldstartNoise = msg.coldstartNoise; - message.freeze = msg.freeze; - message.chiReadyRequest = msg.chiReadyRequest; - message.errorMode = (SilKit_FlexrayErrorModeType)msg.errorMode; - message.slotMode = (SilKit_FlexraySlotModeType)msg.slotMode; - message.startupState = (SilKit_FlexrayStartupStateType)msg.startupState; - message.wakeupStatus = (SilKit_FlexrayWakeupStatusType)msg.wakeupStatus; - handler(context, ctrl, &message); - }); + SilKit_FlexrayPocStatusEvent message; + SilKit_Struct_Init(SilKit_FlexrayPocStatusEvent, message); + message.timestamp = msg.timestamp.count(); + message.state = (SilKit_FlexrayPocState)msg.state; + message.chiHaltRequest = msg.chiHaltRequest; + message.coldstartNoise = msg.coldstartNoise; + message.freeze = msg.freeze; + message.chiReadyRequest = msg.chiReadyRequest; + message.errorMode = (SilKit_FlexrayErrorModeType)msg.errorMode; + message.slotMode = (SilKit_FlexraySlotModeType)msg.slotMode; + message.startupState = (SilKit_FlexrayStartupStateType)msg.startupState; + message.wakeupStatus = (SilKit_FlexrayWakeupStatusType)msg.wakeupStatus; + handler(context, ctrl, &message); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemovePocStatusHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId) + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -420,8 +432,10 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddSymbolHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexraySymbolHandler_t handler, SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddSymbolHandler(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexraySymbolHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -430,20 +444,22 @@ try const auto cppController = reinterpret_cast(controller); *outHandlerId = (SilKit_HandlerId)cppController->AddSymbolHandler( - [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, const SilKit::Services::Flexray::FlexraySymbolEvent& msg) { - SilKit_FlexraySymbolEvent message; - SilKit_Struct_Init(SilKit_FlexraySymbolEvent, message); - message.timestamp = msg.timestamp.count(); - message.channel = (SilKit_FlexrayChannel)msg.channel; - message.pattern = (SilKit_FlexraySymbolPattern)msg.pattern; - handler(context, ctrl, &message); - }); + [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, + const SilKit::Services::Flexray::FlexraySymbolEvent& msg) { + SilKit_FlexraySymbolEvent message; + SilKit_Struct_Init(SilKit_FlexraySymbolEvent, message); + message.timestamp = msg.timestamp.count(); + message.channel = (SilKit_FlexrayChannel)msg.channel; + message.pattern = (SilKit_FlexraySymbolPattern)msg.pattern; + handler(context, ctrl, &message); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveSymbolHandler(SilKit_FlexrayController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveSymbolHandler(SilKit_FlexrayController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -455,9 +471,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddSymbolTransmitHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexraySymbolTransmitHandler_t handler, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddSymbolTransmitHandler( + SilKit_FlexrayController* controller, void* context, SilKit_FlexraySymbolTransmitHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -468,20 +484,20 @@ try *outHandlerId = (SilKit_HandlerId)cppController->AddSymbolTransmitHandler( [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, const SilKit::Services::Flexray::FlexraySymbolTransmitEvent& msg) { - SilKit_FlexraySymbolTransmitEvent message; - SilKit_Struct_Init(SilKit_FlexraySymbolTransmitEvent, message); - message.timestamp = msg.timestamp.count(); - message.channel = (SilKit_FlexrayChannel)msg.channel; - message.pattern = (SilKit_FlexraySymbolPattern)msg.pattern; - handler(context, ctrl, &message); - }); + SilKit_FlexraySymbolTransmitEvent message; + SilKit_Struct_Init(SilKit_FlexraySymbolTransmitEvent, message); + message.timestamp = msg.timestamp.count(); + message.channel = (SilKit_FlexrayChannel)msg.channel; + message.pattern = (SilKit_FlexraySymbolPattern)msg.pattern; + handler(context, ctrl, &message); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveSymbolTransmitHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId) + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -493,9 +509,10 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddCycleStartHandler(SilKit_FlexrayController* controller, void* context, - SilKit_FlexrayCycleStartHandler_t handler, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_AddCycleStartHandler(SilKit_FlexrayController* controller, + void* context, + SilKit_FlexrayCycleStartHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -506,19 +523,19 @@ try *outHandlerId = (SilKit_HandlerId)cppController->AddCycleStartHandler( [context, handler](SilKit::Services::Flexray::IFlexrayController* ctrl, const SilKit::Services::Flexray::FlexrayCycleStartEvent& msg) { - SilKit_FlexrayCycleStartEvent message; - SilKit_Struct_Init(SilKit_FlexrayCycleStartEvent, message); - message.timestamp = msg.timestamp.count(); - message.cycleCounter = msg.cycleCounter; - handler(context, ctrl, &message); - }); + SilKit_FlexrayCycleStartEvent message; + SilKit_Struct_Init(SilKit_FlexrayCycleStartEvent, message); + message.timestamp = msg.timestamp.count(); + message.cycleCounter = msg.cycleCounter; + handler(context, ctrl, &message); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_FlexrayController_RemoveCycleStartHandler(SilKit_FlexrayController* controller, - SilKit_HandlerId handlerId) + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); diff --git a/SilKit/source/capi/CapiImpl.hpp b/SilKit/source/capi/CapiImpl.hpp old mode 100755 new mode 100644 index 37afff360..dcd9dbcf0 --- a/SilKit/source/capi/CapiImpl.hpp +++ b/SilKit/source/capi/CapiImpl.hpp @@ -66,8 +66,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ { \ throw SilKit::CapiBadParameterError{"Parameter '" #p "' must not be null."}; \ } \ - } \ - while (false) + } while (false) #define ASSERT_VALID_POINTER_TO_POINTER_PARAMETER(p) \ do \ @@ -80,8 +79,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ { \ throw SilKit::CapiBadParameterError{"Parameter '" #p "' must not point to a null value."}; \ } \ - } \ - while (false) + } while (false) #define ASSERT_VALID_OUT_PARAMETER(p) \ do \ @@ -90,8 +88,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ { \ throw SilKit::CapiBadParameterError{"Return parameter '" #p "' must not be null."}; \ } \ - } \ - while (false) + } while (false) #define kInvalidFunctionPointer "Handler function parameter must not be null." @@ -102,8 +99,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ { \ throw SilKit::CapiBadParameterError{kInvalidFunctionPointer}; \ } \ - } \ - while (false) + } while (false) #define ASSERT_VALID_BOOL_PARAMETER(b) \ do \ @@ -112,8 +108,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ { \ throw SilKit::CapiBadParameterError{"The parameter '" #b "' is not a valid SilKit_Bool."}; \ } \ - } \ - while (false) + } while (false) #define ASSERT_VALID_STRUCT_HEADER(p) \ do \ @@ -123,8 +118,16 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ throw SilKit::CapiBadParameterError{"The parameter '" #p \ "' has no valid SilKit_StructHeader. Check your library version"}; \ } \ - } \ - while (false) + } while (false) + +#define ASSERT_VALID_PLAIN_STRUCT_HEADER(p) \ + do \ + { \ + if (!IsValidStructHeader(p)) \ + { \ + throw SilKit::CapiBadParameterError{"The parameter '" #p "' is not a valid SilKit_StructHeader."}; \ + } \ + } while (false) extern thread_local std::string SilKit_error_string; @@ -132,29 +135,34 @@ extern thread_local std::string SilKit_error_string; // Utility to verify a CAPI struct header -namespace detail +namespace detail { +template +struct HasStructHeader : std::false_type { - template - struct HasStructHeader: std::false_type - { - }; +}; - template - struct HasStructHeader>().structHeader = SilKit_StructHeader{})>> +template +struct HasStructHeader< + T, SilKit::Util::VoidT>().structHeader = SilKit_StructHeader{})>> : std::true_type - { - }; +{ +}; } //namespace detail -template +template bool HasValidStructHeader(const StructT*, std::enable_if_t::value, bool> = false) { //struct type has no header, ignored. - return false; + return false; } -template +template bool HasValidStructHeader(const StructT* s, std::enable_if_t::value, bool> = true) { return SK_ID_IS_VALID(SilKit_Struct_GetId(*s)); } + +inline bool IsValidStructHeader(const SilKit_StructHeader* s) +{ + return SK_ID_IS_VALID(s->version); +} diff --git a/SilKit/source/capi/CapiLin.cpp b/SilKit/source/capi/CapiLin.cpp old mode 100755 new mode 100644 index 5d03fef54..26b842370 --- a/SilKit/source/capi/CapiLin.cpp +++ b/SilKit/source/capi/CapiLin.cpp @@ -66,7 +66,8 @@ void assign(SilKit::Services::Lin::LinControllerConfig& cppConfig, const SilKit_ assign(cppConfig.frameResponses, cConfig->frameResponses, cConfig->numFrameResponses); } -void assign(SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& cppConfig, const SilKit_Experimental_LinControllerDynamicConfig* cConfig) +void assign(SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& cppConfig, + const SilKit_Experimental_LinControllerDynamicConfig* cConfig) { cppConfig.baudRate = static_cast(cConfig->baudRate); cppConfig.controllerMode = static_cast(cConfig->controllerMode); @@ -86,7 +87,9 @@ void assign(SilKit_Experimental_LinSlaveConfiguration** cLinSlaveConfiguration, } // namespace -SilKit_ReturnCode SilKitCALL SilKit_LinController_Create(SilKit_LinController** outLinController, SilKit_Participant* participant, const char* name, const char* network) +SilKit_ReturnCode SilKitCALL SilKit_LinController_Create(SilKit_LinController** outLinController, + SilKit_Participant* participant, const char* name, + const char* network) try { ASSERT_VALID_POINTER_PARAMETER(participant); @@ -106,7 +109,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LinController_Init(SilKit_LinController* controller, const SilKit_LinControllerConfig* config) +SilKit_ReturnCode SilKitCALL SilKit_LinController_Init(SilKit_LinController* controller, + const SilKit_LinControllerConfig* config) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -140,7 +144,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LinController_Status(SilKit_LinController* controller, SilKit_LinControllerStatus* outStatus) +SilKit_ReturnCode SilKitCALL SilKit_LinController_Status(SilKit_LinController* controller, + SilKit_LinControllerStatus* outStatus) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -153,8 +158,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LinController_SendFrame(SilKit_LinController* controller, const SilKit_LinFrame* frame, - SilKit_LinFrameResponseType responseType) +SilKit_ReturnCode SilKitCALL SilKit_LinController_SendFrame(SilKit_LinController* controller, + const SilKit_LinFrame* frame, + SilKit_LinFrameResponseType responseType) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -183,7 +189,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_LinController_UpdateTxBuffer(SilKit_LinController* controller, - const SilKit_LinFrame* frame) + const SilKit_LinFrame* frame) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -247,8 +253,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_GetSlaveConfiguration(SilKit_LinController* controller, - SilKit_Experimental_LinSlaveConfiguration* outLinSlaveConfiguration) +SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_GetSlaveConfiguration( + SilKit_LinController* controller, SilKit_Experimental_LinSlaveConfiguration* outLinSlaveConfiguration) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -264,7 +270,8 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_LinController_AddFrameStatusHandler(SilKit_LinController* controller, void* context, - SilKit_LinFrameStatusHandler_t handler, SilKit_HandlerId* outHandlerId) + SilKit_LinFrameStatusHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -273,29 +280,29 @@ try auto linController = reinterpret_cast(controller); *outHandlerId = (SilKit_HandlerId)linController->AddFrameStatusHandler( - [handler, context, controller]( - SilKit::Services::Lin::ILinController* /*ctrl*/, const SilKit::Services::Lin::LinFrameStatusEvent& cppFrameStatusEvent) - { - SilKit_LinFrame cFrame; - cFrame.id = static_cast(cppFrameStatusEvent.frame.id); - cFrame.checksumModel = static_cast(cppFrameStatusEvent.frame.checksumModel); - cFrame.dataLength = static_cast(cppFrameStatusEvent.frame.dataLength); - memcpy(cFrame.data, cppFrameStatusEvent.frame.data.data(), 8); - - SilKit_LinFrameStatusEvent cFrameStatusEvent{}; - SilKit_Struct_Init(SilKit_LinFrameStatusEvent, cFrameStatusEvent); - cFrameStatusEvent.timestamp = (SilKit_NanosecondsTime)cppFrameStatusEvent.timestamp.count(); - cFrameStatusEvent.frame = &cFrame; - cFrameStatusEvent.status = (SilKit_LinFrameStatus)cppFrameStatusEvent.status; - - handler(context, controller, &cFrameStatusEvent); - }); + [handler, context, controller](SilKit::Services::Lin::ILinController* /*ctrl*/, + const SilKit::Services::Lin::LinFrameStatusEvent& cppFrameStatusEvent) { + SilKit_LinFrame cFrame; + cFrame.id = static_cast(cppFrameStatusEvent.frame.id); + cFrame.checksumModel = static_cast(cppFrameStatusEvent.frame.checksumModel); + cFrame.dataLength = static_cast(cppFrameStatusEvent.frame.dataLength); + memcpy(cFrame.data, cppFrameStatusEvent.frame.data.data(), 8); + + SilKit_LinFrameStatusEvent cFrameStatusEvent{}; + SilKit_Struct_Init(SilKit_LinFrameStatusEvent, cFrameStatusEvent); + cFrameStatusEvent.timestamp = (SilKit_NanosecondsTime)cppFrameStatusEvent.timestamp.count(); + cFrameStatusEvent.frame = &cFrame; + cFrameStatusEvent.status = (SilKit_LinFrameStatus)cppFrameStatusEvent.status; + + handler(context, controller, &cFrameStatusEvent); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveFrameStatusHandler(SilKit_LinController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveFrameStatusHandler(SilKit_LinController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -308,7 +315,8 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_LinController_AddGoToSleepHandler(SilKit_LinController* controller, void* context, - SilKit_LinGoToSleepHandler_t handler, SilKit_HandlerId* outHandlerId) + SilKit_LinGoToSleepHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -319,17 +327,18 @@ try *outHandlerId = (SilKit_HandlerId)linController->AddGoToSleepHandler( [handler, context, controller](SilKit::Services::Lin::ILinController* /*ctrl*/, const SilKit::Services::Lin::LinGoToSleepEvent& cppGoToSleepEvent) { - SilKit_LinGoToSleepEvent goToSleepEvent{}; - SilKit_Struct_Init(SilKit_LinGoToSleepEvent, goToSleepEvent); - goToSleepEvent.timestamp = (SilKit_NanosecondsTime)cppGoToSleepEvent.timestamp.count(); - handler(context, controller, &goToSleepEvent); - }); + SilKit_LinGoToSleepEvent goToSleepEvent{}; + SilKit_Struct_Init(SilKit_LinGoToSleepEvent, goToSleepEvent); + goToSleepEvent.timestamp = (SilKit_NanosecondsTime)cppGoToSleepEvent.timestamp.count(); + handler(context, controller, &goToSleepEvent); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveGoToSleepHandler(SilKit_LinController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveGoToSleepHandler(SilKit_LinController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -341,7 +350,8 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_LinController_AddWakeupHandler(SilKit_LinController* controller, void* context, - SilKit_LinWakeupHandler_t handler, SilKit_HandlerId* outHandlerId) + SilKit_LinWakeupHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -352,18 +362,19 @@ try *outHandlerId = (SilKit_HandlerId)linController->AddWakeupHandler( [handler, context, controller](SilKit::Services::Lin::ILinController* /*ctrl*/, const SilKit::Services::Lin::LinWakeupEvent& cppWakeupEvent) { - SilKit_LinWakeupEvent wakeupEvent{}; - SilKit_Struct_Init(SilKit_LinWakeupEvent, wakeupEvent); - wakeupEvent.timestamp = (SilKit_NanosecondsTime)cppWakeupEvent.timestamp.count(); - wakeupEvent.direction = (SilKit_Direction)cppWakeupEvent.direction; - handler(context, controller, &wakeupEvent); + SilKit_LinWakeupEvent wakeupEvent{}; + SilKit_Struct_Init(SilKit_LinWakeupEvent, wakeupEvent); + wakeupEvent.timestamp = (SilKit_NanosecondsTime)cppWakeupEvent.timestamp.count(); + wakeupEvent.direction = (SilKit_Direction)cppWakeupEvent.direction; + handler(context, controller, &wakeupEvent); }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveWakeupHandler(SilKit_LinController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_LinController_RemoveWakeupHandler(SilKit_LinController* controller, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -390,18 +401,18 @@ try [handler, context, controller]( SilKit::Services::Lin::ILinController* /*ctrl*/, const SilKit::Experimental::Services::Lin::LinSlaveConfigurationEvent& cppLinSlaveConfigurationEvent) { - SilKit_Experimental_LinSlaveConfigurationEvent slaveConfigurationEvent{}; - SilKit_Struct_Init(SilKit_Experimental_LinSlaveConfigurationEvent, slaveConfigurationEvent); - slaveConfigurationEvent.timestamp = - (SilKit_NanosecondsTime)cppLinSlaveConfigurationEvent.timestamp.count(); - handler(context, controller, &slaveConfigurationEvent); - }); + SilKit_Experimental_LinSlaveConfigurationEvent slaveConfigurationEvent{}; + SilKit_Struct_Init(SilKit_Experimental_LinSlaveConfigurationEvent, slaveConfigurationEvent); + slaveConfigurationEvent.timestamp = (SilKit_NanosecondsTime)cppLinSlaveConfigurationEvent.timestamp.count(); + handler(context, controller, &slaveConfigurationEvent); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler(SilKit_LinController* controller, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler( + SilKit_LinController* controller, SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(controller); @@ -442,12 +453,12 @@ try auto linController = reinterpret_cast(controller); auto cppHandlerId = SilKit::Experimental::Services::Lin::AddFrameHeaderHandlerImpl( linController, [handler, context, controller](auto* /*ctrl*/, auto&& cppEvent) { - SilKit_Experimental_LinFrameHeaderEvent cEvent{}; - SilKit_Struct_Init(SilKit_LinWakeupEvent, cEvent); - cEvent.timestamp = (SilKit_NanosecondsTime)cppEvent.timestamp.count(); - cEvent.id = (SilKit_LinId)cppEvent.id; - handler(context, controller, &cEvent); - }); + SilKit_Experimental_LinFrameHeaderEvent cEvent{}; + SilKit_Struct_Init(SilKit_LinWakeupEvent, cEvent); + cEvent.timestamp = (SilKit_NanosecondsTime)cppEvent.timestamp.count(); + cEvent.id = (SilKit_LinId)cppEvent.id; + handler(context, controller, &cEvent); + }); *outHandlerId = static_cast(cppHandlerId); return SilKit_ReturnCode_SUCCESS; } @@ -469,7 +480,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinController_SendDynamicResponse(SilKit_LinController* controller, - const SilKit_LinFrame* frame) + const SilKit_LinFrame* frame) try { ASSERT_VALID_POINTER_PARAMETER(controller); diff --git a/SilKit/source/capi/CapiNetworkSimulator.cpp b/SilKit/source/capi/CapiNetworkSimulator.cpp new file mode 100644 index 000000000..dd1d22424 --- /dev/null +++ b/SilKit/source/capi/CapiNetworkSimulator.cpp @@ -0,0 +1,743 @@ +/* Copyright (c) 2022 Vector Informatik GmbH + +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. */ + +#include +#include +#include +#include +#include +#include + +#include "silkit/capi/SilKit.h" +#include "silkit/SilKit.hpp" +#include "CapiImpl.hpp" + +#include "silkit/experimental/netsim/all.hpp" + +#include "silkit/detail/impl/HourglassConversions.hpp" +#include "participant/ParticipantExtensionsImpl.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +namespace Can { + +// -------------------------------- +// CAN +// -------------------------------- + +class CApiSimulatedCanController : public ISimulatedCanController +{ + void* _userController{nullptr}; + const SilKit_Experimental_SimulatedCanControllerFunctions* _functions{nullptr}; + +public: + CApiSimulatedCanController() = default; + + CApiSimulatedCanController(void* controller, const SilKit_Experimental_SimulatedCanControllerFunctions* functions) + : _userController{controller} + , _functions{functions} + { + } + + void OnSetControllerMode(const CanControllerMode& cxxMsg) override + { + SilKit_Experimental_NetSim_CanControllerMode cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_CanControllerMode, cMsg); + + assignCxxToC(cxxMsg, cMsg); + + _functions->OnSetControllerMode(_userController, &cMsg); + } + + void OnSetBaudrate(const CanConfigureBaudrate& cxxMsg) override + { + SilKit_Experimental_NetSim_CanConfigureBaudrate cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_CanConfigureBaudrate, cMsg); + assignCxxToC(cxxMsg, cMsg); + + _functions->OnSetBaudrate(_userController, &cMsg); + } + + void OnFrameRequest(const CanFrameRequest& cxxMsg) override + { + SilKit_Experimental_NetSim_CanFrameRequest cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_CanFrameRequest, cMsg); + SilKit_CanFrame canFrame; + SilKit_Struct_Init(SilKit_CanFrame, canFrame); + cMsg.frame = &canFrame; + assignCxxToC(cxxMsg, cMsg); + + _functions->OnFrameRequest(_userController, &cMsg); + } +}; + +} // namespace Can + +namespace Flexray { + +// -------------------------------- +// Flexray +// -------------------------------- + +class CApiSimulatedFlexRayController : public ISimulatedFlexRayController +{ + void* _controller{nullptr}; + const SilKit_Experimental_SimulatedFlexRayControllerFunctions* _functions{nullptr}; + +public: + CApiSimulatedFlexRayController() = default; + + CApiSimulatedFlexRayController(void* controller, + const SilKit_Experimental_SimulatedFlexRayControllerFunctions* functions) + : _controller{controller} + , _functions{functions} + { + } + + void OnHostCommand(const FlexrayHostCommand& cxxMsg) + { + SilKit_Experimental_NetSim_FlexrayHostCommand cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_FlexrayHostCommand, cMsg); + assignCxxToC(cxxMsg, cMsg); + + _functions->OnHostCommand(_controller, &cMsg); + } + + void OnControllerConfig(const FlexrayControllerConfig& cxxMsg) + { + SilKit_Experimental_NetSim_FlexrayControllerConfig cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_FlexrayControllerConfig, cMsg); + SilKit_FlexrayControllerConfig controllerConfig; + SilKit_Struct_Init(SilKit_FlexrayControllerConfig, controllerConfig); + SilKit_FlexrayClusterParameters clusterParameters; + SilKit_Struct_Init(SilKit_FlexrayClusterParameters, clusterParameters); + SilKit_FlexrayNodeParameters nodeParameters; + SilKit_Struct_Init(SilKit_FlexrayNodeParameters, nodeParameters); + + std::vector cTxBufferConfigs; + for (uint32_t idx = 0; idx < cxxMsg.bufferConfigs.size(); idx++) + { + SilKit_FlexrayTxBufferConfig cTxBufferConfig; + SilKit_Struct_Init(SilKit_FlexrayTxBufferConfig, cTxBufferConfig); + cTxBufferConfigs.emplace_back(cTxBufferConfig); + } + cMsg.bufferConfigs = cTxBufferConfigs.data(); + cMsg.clusterParams = &clusterParameters; + cMsg.nodeParams = &nodeParameters; + + // Assign the data (including bufferConfigs data) + assignCxxToC(cxxMsg, cMsg); + + _functions->OnControllerConfig(_controller, &cMsg); + } + + void OnTxBufferConfigUpdate(const FlexrayTxBufferConfigUpdate& cxxMsg) + { + SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate, cMsg); + SilKit_FlexrayTxBufferConfig txBufferConfig; + SilKit_Struct_Init(SilKit_FlexrayTxBufferConfig, txBufferConfig); + cMsg.txBufferConfig = &txBufferConfig; + assignCxxToC(cxxMsg, cMsg); + + _functions->OnTxBufferConfigUpdate(_controller, &cMsg); + } + + void OnTxBufferUpdate(const FlexrayTxBufferUpdate& cxxMsg) + { + SilKit_Experimental_NetSim_FlexrayTxBufferUpdate cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_FlexrayTxBufferUpdate, cMsg); + assignCxxToC(cxxMsg, cMsg); + + _functions->OnTxBufferUpdate(_controller, &cMsg); + } +}; + +} // namespace Flexray + +namespace Ethernet { + +// -------------------------------- +// Ethernet +// -------------------------------- + +class CApiSimulatedEthernetController : public ISimulatedEthernetController +{ + void* _userController{nullptr}; + const SilKit_Experimental_SimulatedEthernetControllerFunctions* _functions{nullptr}; + +public: + CApiSimulatedEthernetController() = default; + + CApiSimulatedEthernetController(void* controller, + const SilKit_Experimental_SimulatedEthernetControllerFunctions* functions) + : _userController{controller} + , _functions{functions} + { + } + + void OnFrameRequest(const EthernetFrameRequest& cxxMsg) override + { + SilKit_Experimental_NetSim_EthernetFrameRequest cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_EthernetFrameRequest, cMsg); + SilKit_EthernetFrame ethernetFrame; + SilKit_Struct_Init(SilKit_EthernetFrame, ethernetFrame); + cMsg.ethernetFrame = ðernetFrame; + assignCxxToC(cxxMsg, cMsg); + + _functions->OnFrameRequest(_userController, &cMsg); + } + + void OnSetControllerMode(const EthernetControllerMode& cxxMsg) override + { + SilKit_Experimental_NetSim_EthernetControllerMode cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_EthernetControllerMode, cMsg); + assignCxxToC(cxxMsg, cMsg); + + _functions->OnSetControllerMode(_userController, &cMsg); + } +}; + +} // namespace Ethernet + + +namespace Lin { + +// -------------------------------- +// Lin +// -------------------------------- + + +class CApiSimulatedLinController : public ISimulatedLinController +{ + void* _userController{nullptr}; + const SilKit_Experimental_SimulatedLinControllerFunctions* _functions{nullptr}; + +public: + CApiSimulatedLinController() = default; + + CApiSimulatedLinController(void* controller, const SilKit_Experimental_SimulatedLinControllerFunctions* functions) + : _userController{controller} + , _functions{functions} + { + } + + void OnFrameRequest(const LinFrameRequest& cxxMsg) override + { + SilKit_Experimental_NetSim_LinFrameRequest cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinFrameRequest, cMsg); + SilKit_LinFrame linFrame; + SilKit_Struct_Init(SilKit_LinFrame, linFrame); + cMsg.frame = &linFrame; + assignCxxToC(cxxMsg, cMsg); + + _functions->OnFrameRequest(_userController, &cMsg); + } + + void OnFrameHeaderRequest(const LinFrameHeaderRequest& cxxMsg) override + { + SilKit_Experimental_NetSim_LinFrameHeaderRequest cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinFrameHeaderRequest, cMsg); + assignCxxToC(cxxMsg, cMsg); + + _functions->OnFrameHeaderRequest(_userController, &cMsg); + } + + void OnWakeupPulse(const LinWakeupPulse& cxxMsg) override + { + SilKit_Experimental_NetSim_LinWakeupPulse cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinWakeupPulse, cMsg); + assignCxxToC(cxxMsg, cMsg); + + _functions->OnWakeupPulse(_userController, &cMsg); + } + void OnControllerConfig(const LinControllerConfig& cxxMsg) override + { + SilKit_Experimental_NetSim_LinControllerConfig cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinControllerConfig, cMsg); + + std::vector cLinFrames; + cLinFrames.reserve(cxxMsg.frameResponses.size()); + std::vector cLinFrameResponses; + cLinFrameResponses.reserve(cxxMsg.frameResponses.size()); + for (uint32_t idx = 0; idx < cxxMsg.frameResponses.size(); idx++) + { + SilKit_LinFrameResponse cLinFrameResponse; + SilKit_Struct_Init(SilKit_LinFrameResponse, cLinFrameResponse); + + SilKit_LinFrame cLinFrame; + SilKit_Struct_Init(SilKit_LinFrame, cLinFrame); + + cLinFrames.emplace_back(cLinFrame); + cLinFrameResponse.frame = &cLinFrames.back(); + cLinFrameResponses.emplace_back(cLinFrameResponse); + } + cMsg.frameResponses = cLinFrameResponses.data(); + + assignCxxToC(cxxMsg, cMsg); + + _functions->OnControllerConfig(_userController, &cMsg); + } + void OnFrameResponseUpdate(const LinFrameResponseUpdate& cxxMsg) override + { + SilKit_Experimental_NetSim_LinFrameResponseUpdate cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinFrameResponseUpdate, cMsg); + + std::vector cLinFrames; + cLinFrames.reserve(cxxMsg.frameResponses.size()); + std::vector cLinFrameResponses; + cLinFrameResponses.reserve(cxxMsg.frameResponses.size()); + for (uint32_t idx = 0; idx < cxxMsg.frameResponses.size(); idx++) + { + SilKit_LinFrameResponse cLinFrameResponse; + SilKit_Struct_Init(SilKit_LinFrameResponse, cLinFrameResponse); + + SilKit_LinFrame cLinFrame; + SilKit_Struct_Init(SilKit_LinFrame, cLinFrame); + + cLinFrames.emplace_back(cLinFrame); + cLinFrameResponse.frame = &cLinFrames.back(); + cLinFrameResponses.emplace_back(cLinFrameResponse); + } + cMsg.frameResponses = cLinFrameResponses.data(); + + assignCxxToC(cxxMsg, cMsg); + + _functions->OnFrameResponseUpdate(_userController, &cMsg); + } + void OnControllerStatusUpdate(const LinControllerStatusUpdate& cxxMsg) override + { + SilKit_Experimental_NetSim_LinControllerStatusUpdate cMsg; + SilKit_Struct_Init(SilKit_Experimental_NetSim_LinControllerStatusUpdate, cMsg); + assignCxxToC(cxxMsg, cMsg); + + _functions->OnControllerStatusUpdate(_userController, &cMsg); + } +}; + +} // namespace Lin + +class CApiSimulatedNetwork : public ISimulatedNetwork +{ +public: + void* _simulatedNetwork{nullptr}; + +private: + SilKit_Experimental_SimulatedNetworkType _networkType; + std::string _networkName; + const SilKit_Experimental_SimulatedNetworkFunctions* _functions{nullptr}; + std::unique_ptr _eventProducer; + std::vector> _controllers; + +public: + CApiSimulatedNetwork() = default; + + CApiSimulatedNetwork(SilKit_Experimental_SimulatedNetworkType networkType, const std::string& networkName, + void* simulatedNetwork, const SilKit_Experimental_SimulatedNetworkFunctions* functions) + : _simulatedNetwork{simulatedNetwork} + , _networkType{networkType} + , _networkName{networkName} + , _functions{functions} + { + } + + auto ProvideSimulatedController(ControllerDescriptor controllerDescriptor) -> ISimulatedController* override + { + void* userSimulatedController{nullptr}; + const void* functions{nullptr}; + _functions->ProvideSimulatedController(&userSimulatedController, &functions, controllerDescriptor, + _simulatedNetwork); + + if (userSimulatedController == nullptr) + { + const std::string errorMsg = + "NetworkSimulation: No simulated controller was provided on network '" + _networkName + "'."; + throw SilKitError{errorMsg}; + } + + switch (_networkType) + { + case SilKit_NetworkType_CAN: + _controllers.emplace_back(std::make_unique( + userSimulatedController, (SilKit_Experimental_SimulatedCanControllerFunctions*)functions)); + return _controllers.back().get(); + case SilKit_NetworkType_FlexRay: + _controllers.emplace_back(std::make_unique( + userSimulatedController, (SilKit_Experimental_SimulatedFlexRayControllerFunctions*)functions)); + return _controllers.back().get(); + case SilKit_NetworkType_Ethernet: + _controllers.emplace_back(std::make_unique( + userSimulatedController, (SilKit_Experimental_SimulatedEthernetControllerFunctions*)functions)); + return _controllers.back().get(); + case SilKit_NetworkType_LIN: + _controllers.emplace_back(std::make_unique( + userSimulatedController, (SilKit_Experimental_SimulatedLinControllerFunctions*)functions)); + return _controllers.back().get(); + default: + break; + } + + return {}; + } + + void SimulatedControllerRemoved(ControllerDescriptor controllerDescriptor) override + { + _functions->SimulatedControllerRemoved(controllerDescriptor, _simulatedNetwork); + } + + void SetEventProducer(std::unique_ptr eventProducer) override + { + auto* cEventProducer = reinterpret_cast(eventProducer.get()); + _functions->SetEventProducer(cEventProducer, _simulatedNetwork); + _eventProducer = std::move(eventProducer); + } +}; + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit + + +SilKit_ReturnCode SilKitCALL SilKit_Experimental_NetworkSimulator_Create( + SilKit_Experimental_NetworkSimulator** outNetworkSimulator, SilKit_Participant* participant) +try +{ + ASSERT_VALID_OUT_PARAMETER(outNetworkSimulator); + ASSERT_VALID_POINTER_PARAMETER(participant); + + auto cppParticipant = reinterpret_cast(participant); + auto* cppNetworkSimulator = SilKit::Experimental::Participant::CreateNetworkSimulatorImpl(cppParticipant); + *outNetworkSimulator = reinterpret_cast(cppNetworkSimulator); + + return SilKit_ReturnCode_SUCCESS; +} +CAPI_CATCH_EXCEPTIONS + + +SilKit_ReturnCode SilKitCALL SilKit_Experimental_NetworkSimulator_SimulateNetwork( + SilKit_Experimental_NetworkSimulator* networkSimulator, const char* networkName, + SilKit_Experimental_SimulatedNetworkType networkType, void* userSimulatedNetwork, + const SilKit_Experimental_SimulatedNetworkFunctions* functions) +try +{ + ASSERT_VALID_POINTER_PARAMETER(networkSimulator); + ASSERT_VALID_POINTER_PARAMETER(networkName); + ASSERT_VALID_POINTER_PARAMETER(userSimulatedNetwork); + ASSERT_VALID_POINTER_PARAMETER(functions); + ASSERT_VALID_STRUCT_HEADER(functions); + + // Create simulatedNetwork with user functions + auto simulatedNetwork = std::make_unique( + networkType, networkName, userSimulatedNetwork, functions); + auto cppNetworkSimulator = + reinterpret_cast(networkSimulator); + cppNetworkSimulator->SimulateNetwork( + networkName, static_cast(networkType), + std::move(simulatedNetwork)); + + return SilKit_ReturnCode_SUCCESS; +} +CAPI_CATCH_EXCEPTIONS + + +SilKit_ReturnCode SilKitCALL +SilKit_Experimental_NetworkSimulator_Start(SilKit_Experimental_NetworkSimulator* networkSimulator) +try +{ + ASSERT_VALID_POINTER_PARAMETER(networkSimulator); + + auto cppNetworkSimulator = + reinterpret_cast(networkSimulator); + cppNetworkSimulator->Start(); + return SilKit_ReturnCode_SUCCESS; +} +CAPI_CATCH_EXCEPTIONS + +// -------------------------------- +// Can +// -------------------------------- + +template +void Produce(MsgT msg, const SilKit_Experimental_EventReceivers* receivers, + SilKit_Experimental_CanEventProducer* eventProducer) +{ + auto cppEventProducer = + reinterpret_cast(eventProducer); + auto cppReceivers = SilKit::Util::Span( + receivers->controllerDescriptors, receivers->numReceivers); + cppEventProducer->Produce(msg, cppReceivers); +} + +SilKit_ReturnCode SilKitCALL SilKit_Experimental_CanEventProducer_Produce( + SilKit_Experimental_CanEventProducer* eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers) +try +{ + ASSERT_VALID_POINTER_PARAMETER(eventProducer); + ASSERT_VALID_POINTER_PARAMETER(cEvent); + ASSERT_VALID_POINTER_PARAMETER(receivers); + ASSERT_VALID_PLAIN_STRUCT_HEADER(cEvent); + ASSERT_VALID_STRUCT_HEADER(receivers); + + auto msgDatatypeId = SK_ID_GET_DATATYPE(cEvent->version); + switch (msgDatatypeId) + { + case SilKit_CanFrameEvent_DATATYPE_ID: + { + SilKit::Services::Can::CanFrameEvent cxxEvent; + assignCToCxx((SilKit_CanFrameEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_CanFrameTransmitEvent_DATATYPE_ID: + { + SilKit::Services::Can::CanFrameTransmitEvent cxxEvent; + assignCToCxx((SilKit_CanFrameTransmitEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_CanStateChangeEvent_DATATYPE_ID: + { + SilKit::Services::Can::CanStateChangeEvent cxxEvent; + assignCToCxx((SilKit_CanStateChangeEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_CanErrorStateChangeEvent_DATATYPE_ID: + { + SilKit::Services::Can::CanErrorStateChangeEvent cxxEvent; + assignCToCxx((SilKit_CanErrorStateChangeEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + default: + break; + } + + return SilKit_ReturnCode_SUCCESS; +} +CAPI_CATCH_EXCEPTIONS + +// -------------------------------- +// FlexRay +// -------------------------------- + +template +void Produce(MsgT msg, const SilKit_Experimental_EventReceivers* receivers, + SilKit_Experimental_FlexRayEventProducer* eventProducer) +{ + auto cppEventProducer = + reinterpret_cast(eventProducer); + auto cppReceivers = SilKit::Util::Span( + receivers->controllerDescriptors, receivers->numReceivers); + cppEventProducer->Produce(msg, cppReceivers); +} + +SilKit_ReturnCode SilKitCALL SilKit_Experimental_FlexRayEventProducer_Produce( + SilKit_Experimental_FlexRayEventProducer* eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers) +try +{ + ASSERT_VALID_POINTER_PARAMETER(eventProducer); + ASSERT_VALID_POINTER_PARAMETER(cEvent); + ASSERT_VALID_POINTER_PARAMETER(receivers); + ASSERT_VALID_PLAIN_STRUCT_HEADER(cEvent); + ASSERT_VALID_STRUCT_HEADER(receivers); + + auto msgDatatypeId = SK_ID_GET_DATATYPE(cEvent->version); + switch (msgDatatypeId) + { + case SilKit_FlexrayFrameEvent_DATATYPE_ID: + { + SilKit::Services::Flexray::FlexrayFrameEvent cxxEvent; + assignCToCxx((SilKit_FlexrayFrameEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_FlexrayFrameTransmitEvent_DATATYPE_ID: + { + SilKit::Services::Flexray::FlexrayFrameTransmitEvent cxxEvent; + assignCToCxx((SilKit_FlexrayFrameTransmitEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_FlexraySymbolEvent_DATATYPE_ID: + { + SilKit::Services::Flexray::FlexraySymbolEvent cxxEvent; + assignCToCxx((SilKit_FlexraySymbolEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_FlexraySymbolTransmitEvent_DATATYPE_ID: + { + SilKit::Services::Flexray::FlexraySymbolTransmitEvent cxxEvent; + assignCToCxx((SilKit_FlexraySymbolTransmitEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_FlexrayCycleStartEvent_DATATYPE_ID: + { + SilKit::Services::Flexray::FlexrayCycleStartEvent cxxEvent; + assignCToCxx((SilKit_FlexrayCycleStartEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_FlexrayPocStatusEvent_DATATYPE_ID: + { + SilKit::Services::Flexray::FlexrayPocStatusEvent cxxEvent; + assignCToCxx((SilKit_FlexrayPocStatusEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + default: + break; + } + + return SilKit_ReturnCode_SUCCESS; +} +CAPI_CATCH_EXCEPTIONS + +// -------------------------------- +// Ethernet +// -------------------------------- + +template +void Produce(MsgT msg, const SilKit_Experimental_EventReceivers* receivers, + SilKit_Experimental_EthernetEventProducer* eventProducer) +{ + auto cppEventProducer = + reinterpret_cast(eventProducer); + auto cppReceivers = SilKit::Util::Span( + receivers->controllerDescriptors, receivers->numReceivers); + cppEventProducer->Produce(msg, cppReceivers); +} + +SilKit_ReturnCode SilKitCALL SilKit_Experimental_EthernetEventProducer_Produce( + SilKit_Experimental_EthernetEventProducer* eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers) +try +{ + ASSERT_VALID_POINTER_PARAMETER(eventProducer); + ASSERT_VALID_POINTER_PARAMETER(cEvent); + ASSERT_VALID_POINTER_PARAMETER(receivers); + ASSERT_VALID_PLAIN_STRUCT_HEADER(cEvent); + ASSERT_VALID_STRUCT_HEADER(receivers); + + auto msgDatatypeId = SK_ID_GET_DATATYPE(cEvent->version); + switch (msgDatatypeId) + { + case SilKit_EthernetFrameEvent_DATATYPE_ID: + { + SilKit::Services::Ethernet::EthernetFrameEvent cxxEvent; + assignCToCxx((SilKit_EthernetFrameEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_EthernetFrameTransmitEvent_DATATYPE_ID: + { + SilKit::Services::Ethernet::EthernetFrameTransmitEvent cxxEvent; + assignCToCxx((SilKit_EthernetFrameTransmitEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_EthernetStateChangeEvent_DATATYPE_ID: + { + SilKit::Services::Ethernet::EthernetStateChangeEvent cxxEvent; + assignCToCxx((SilKit_EthernetStateChangeEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_EthernetBitrateChangeEvent_DATATYPE_ID: + { + SilKit::Services::Ethernet::EthernetBitrateChangeEvent cxxEvent; + assignCToCxx((SilKit_EthernetBitrateChangeEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + default: + break; + } + + return SilKit_ReturnCode_SUCCESS; +} +CAPI_CATCH_EXCEPTIONS + +// -------------------------------- +// Lin +// -------------------------------- + +template +void Produce(MsgT msg, const SilKit_Experimental_EventReceivers* receivers, + SilKit_Experimental_LinEventProducer* eventProducer) +{ + auto cppEventProducer = + reinterpret_cast(eventProducer); + auto cppReceivers = SilKit::Util::Span( + receivers->controllerDescriptors, receivers->numReceivers); + cppEventProducer->Produce(msg, cppReceivers); +} + +SilKit_ReturnCode SilKitCALL SilKit_Experimental_LinEventProducer_Produce( + SilKit_Experimental_LinEventProducer* eventProducer, SilKit_StructHeader* cEvent, + const SilKit_Experimental_EventReceivers* receivers) +try +{ + ASSERT_VALID_POINTER_PARAMETER(eventProducer); + ASSERT_VALID_POINTER_PARAMETER(cEvent); + ASSERT_VALID_POINTER_PARAMETER(receivers); + ASSERT_VALID_PLAIN_STRUCT_HEADER(cEvent); + ASSERT_VALID_STRUCT_HEADER(receivers); + + auto msgDatatypeId = SK_ID_GET_DATATYPE(cEvent->version); + + + switch (msgDatatypeId) + { + case SilKit_LinFrameStatusEvent_DATATYPE_ID: + { + SilKit::Services::Lin::LinFrameStatusEvent cxxEvent; + assignCToCxx((SilKit_LinFrameStatusEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_LinSendFrameHeaderRequest_DATATYPE_ID: + { + SilKit::Services::Lin::LinSendFrameHeaderRequest cxxEvent; + assignCToCxx((SilKit_LinSendFrameHeaderRequest*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + case SilKit_LinWakeupEvent_DATATYPE_ID: + { + SilKit::Services::Lin::LinWakeupEvent cxxEvent; + assignCToCxx((SilKit_LinWakeupEvent*)cEvent, cxxEvent); + Produce(cxxEvent, receivers, eventProducer); + break; + } + default: + break; + } + + return SilKit_ReturnCode_SUCCESS; +} +CAPI_CATCH_EXCEPTIONS diff --git a/SilKit/source/capi/CapiOrchestration.cpp b/SilKit/source/capi/CapiOrchestration.cpp old mode 100755 new mode 100644 index 707b5172a..e336de51e --- a/SilKit/source/capi/CapiOrchestration.cpp +++ b/SilKit/source/capi/CapiOrchestration.cpp @@ -39,24 +39,24 @@ namespace { auto CToCpp(const SilKit_LifecycleConfiguration* csc) { - SilKit::Services::Orchestration::LifecycleConfiguration cpp{}; - cpp.operationMode = static_cast(csc->operationMode); - return cpp; + SilKit::Services::Orchestration::LifecycleConfiguration cpp{}; + cpp.operationMode = static_cast(csc->operationMode); + return cpp; } void CppToC( const SilKit::Services::Orchestration::ParticipantConnectionInformation& cppParticipantConnectionInformation, SilKit_ParticipantConnectionInformation& cParticipantConnectionInformation) { - SilKit_Struct_Init(SilKit_ParticipantConnectionInformation, cParticipantConnectionInformation); - cParticipantConnectionInformation.participantName = cppParticipantConnectionInformation.participantName.c_str(); + SilKit_Struct_Init(SilKit_ParticipantConnectionInformation, cParticipantConnectionInformation); + cParticipantConnectionInformation.participantName = cppParticipantConnectionInformation.participantName.c_str(); } } // namespace SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_Create(SilKit_SystemMonitor** outSystemMonitor, - SilKit_Participant* participant) + SilKit_Participant* participant) try { ASSERT_VALID_OUT_PARAMETER(outSystemMonitor); @@ -71,8 +71,8 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Create(SilKit_LifecycleService** outLifecycleService, - SilKit_Participant* participant, - const SilKit_LifecycleConfiguration* startConfiguration) + SilKit_Participant* participant, + const SilKit_LifecycleConfiguration* startConfiguration) try { ASSERT_VALID_OUT_PARAMETER(outLifecycleService); @@ -89,7 +89,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_TimeSyncService_Create(SilKit_TimeSyncService** outTimeSyncService, SilKit_LifecycleService* lifecycleService) +SilKit_ReturnCode SilKitCALL SilKit_TimeSyncService_Create(SilKit_TimeSyncService** outTimeSyncService, + SilKit_LifecycleService* lifecycleService) try { ASSERT_VALID_OUT_PARAMETER(outTimeSyncService); @@ -105,8 +106,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetCommunicationReadyHandler(SilKit_LifecycleService* lifecycleService, void* context, - SilKit_LifecycleService_CommunicationReadyHandler_t handler) +SilKit_ReturnCode SilKitCALL +SilKit_LifecycleService_SetCommunicationReadyHandler(SilKit_LifecycleService* lifecycleService, void* context, + SilKit_LifecycleService_CommunicationReadyHandler_t handler) try { ASSERT_VALID_POINTER_PARAMETER(lifecycleService); @@ -114,16 +116,16 @@ try auto* cppLifecycleService = reinterpret_cast(lifecycleService); - cppLifecycleService->SetCommunicationReadyHandler([handler, context, lifecycleService]() { - handler(context, lifecycleService); - }); + cppLifecycleService->SetCommunicationReadyHandler( + [handler, context, lifecycleService]() { handler(context, lifecycleService); }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetCommunicationReadyHandlerAsync(SilKit_LifecycleService* lifecycleService, void* context, +SilKit_ReturnCode SilKitCALL +SilKit_LifecycleService_SetCommunicationReadyHandlerAsync(SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_CommunicationReadyHandler_t handler) try { @@ -132,16 +134,16 @@ try auto* cppLifecycleService = reinterpret_cast(lifecycleService); - cppLifecycleService->SetCommunicationReadyHandlerAsync([handler, context, lifecycleService]() { - handler(context, lifecycleService); - }); + cppLifecycleService->SetCommunicationReadyHandlerAsync( + [handler, context, lifecycleService]() { handler(context, lifecycleService); }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_CompleteCommunicationReadyHandlerAsync(SilKit_LifecycleService* lifecycleService) +SilKit_ReturnCode SilKitCALL +SilKit_LifecycleService_CompleteCommunicationReadyHandlerAsync(SilKit_LifecycleService* lifecycleService) try { ASSERT_VALID_POINTER_PARAMETER(lifecycleService); @@ -156,27 +158,25 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetStartingHandler( - SilKit_LifecycleService* lifecycleService, void* context, - SilKit_LifecycleService_StartingHandler_t handler) + SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_StartingHandler_t handler) try { ASSERT_VALID_POINTER_PARAMETER(lifecycleService); ASSERT_VALID_HANDLER_PARAMETER(handler); - auto* cppLifecycleService = - reinterpret_cast(lifecycleService); + auto* cppLifecycleService = reinterpret_cast(lifecycleService); - cppLifecycleService->SetStartingHandler([handler, context, lifecycleService]() { - handler(context, lifecycleService); - }); + cppLifecycleService->SetStartingHandler( + [handler, context, lifecycleService]() { handler(context, lifecycleService); }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetStopHandler(SilKit_LifecycleService* clifecycleService, void* context, - SilKit_LifecycleService_StopHandler_t handler) +SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetStopHandler(SilKit_LifecycleService* clifecycleService, + void* context, + SilKit_LifecycleService_StopHandler_t handler) try { ASSERT_VALID_POINTER_PARAMETER(clifecycleService); @@ -185,16 +185,15 @@ try auto* cppLifecycleService = reinterpret_cast(clifecycleService); - cppLifecycleService->SetStopHandler([handler, context, clifecycleService]() { - handler(context, clifecycleService); - }); + cppLifecycleService->SetStopHandler( + [handler, context, clifecycleService]() { handler(context, clifecycleService); }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetShutdownHandler(SilKit_LifecycleService* clifecycleService, void* context, - SilKit_LifecycleService_ShutdownHandler_t handler) +SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetShutdownHandler( + SilKit_LifecycleService* clifecycleService, void* context, SilKit_LifecycleService_ShutdownHandler_t handler) try { ASSERT_VALID_POINTER_PARAMETER(clifecycleService); @@ -203,29 +202,27 @@ try auto* cppLifecycleService = reinterpret_cast(clifecycleService); - cppLifecycleService->SetShutdownHandler([handler, context, clifecycleService]() { - handler(context, clifecycleService); - }); + cppLifecycleService->SetShutdownHandler( + [handler, context, clifecycleService]() { handler(context, clifecycleService); }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetAbortHandler( - SilKit_LifecycleService* lifecycleService, void* context, SilKit_LifecycleService_AbortHandler_t handler) +SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_SetAbortHandler(SilKit_LifecycleService* lifecycleService, + void* context, + SilKit_LifecycleService_AbortHandler_t handler) try { ASSERT_VALID_POINTER_PARAMETER(lifecycleService); ASSERT_VALID_HANDLER_PARAMETER(handler); - auto* cppLifecycleService = - reinterpret_cast(lifecycleService); + auto* cppLifecycleService = reinterpret_cast(lifecycleService); cppLifecycleService->SetAbortHandler( - [handler, context, - lifecycleService](SilKit::Services::Orchestration::ParticipantState cppParticipantState) { - handler(context, lifecycleService, static_cast(cppParticipantState)); - }); + [handler, context, lifecycleService](SilKit::Services::Orchestration::ParticipantState cppParticipantState) { + handler(context, lifecycleService, static_cast(cppParticipantState)); + }); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS @@ -239,14 +236,14 @@ class LifecycleFutureMap using ParticipantStateFuture = std::future; public: - void Add(SilKit_LifecycleService * lifecycleService, ParticipantStateFuture future) + void Add(SilKit_LifecycleService* lifecycleService, ParticipantStateFuture future) { std::unique_lock lock{_mutex}; _map[lifecycleService] = std::move(future); } - auto Get(SilKit_LifecycleService *lifecycleService) -> ParticipantStateFuture * + auto Get(SilKit_LifecycleService* lifecycleService) -> ParticipantStateFuture* { std::unique_lock lock{_mutex}; @@ -258,7 +255,7 @@ class LifecycleFutureMap return &it->second; } - void Remove(SilKit_LifecycleService *lifecycleService) + void Remove(SilKit_LifecycleService* lifecycleService) { std::unique_lock lock{_mutex}; @@ -286,8 +283,7 @@ try ASSERT_VALID_POINTER_PARAMETER(clifecycleService); auto* cppLifecycleService = - reinterpret_cast( - clifecycleService); + reinterpret_cast(clifecycleService); GetLifecycleFutureMap()->Add(clifecycleService, cppLifecycleService->StartLifecycle()); @@ -296,8 +292,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_WaitForLifecycleToComplete(SilKit_LifecycleService* clifecycleService, - SilKit_ParticipantState* outParticipantState) +SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_WaitForLifecycleToComplete( + SilKit_LifecycleService* clifecycleService, SilKit_ParticipantState* outParticipantState) try { ASSERT_VALID_POINTER_PARAMETER(clifecycleService); @@ -371,8 +367,7 @@ try const auto& participantStatus = lifecycleService->Status(); outParticipantStatus->enterReason = participantStatus.enterReason.c_str(); - outParticipantStatus->enterTime = - std::chrono::nanoseconds{participantStatus.enterTime.time_since_epoch()}.count(); + outParticipantStatus->enterTime = std::chrono::nanoseconds{participantStatus.enterTime.time_since_epoch()}.count(); outParticipantStatus->refreshTime = std::chrono::nanoseconds{participantStatus.refreshTime.time_since_epoch()}.count(); outParticipantStatus->participantName = participantStatus.participantName.c_str(); @@ -394,10 +389,9 @@ try auto* timeSyncService = reinterpret_cast(ctimeSyncService); timeSyncService->SetSimulationStepHandler( [handler, context, ctimeSyncService](std::chrono::nanoseconds now, std::chrono::nanoseconds duration) { - handler(context, ctimeSyncService, static_cast(now.count()), - static_cast(duration.count())); - }, - std::chrono::nanoseconds(initialStepSize)); + handler(context, ctimeSyncService, static_cast(now.count()), + static_cast(duration.count())); + }, std::chrono::nanoseconds(initialStepSize)); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS @@ -415,10 +409,9 @@ try timeSyncService->SetSimulationStepHandlerAsync( [handler, context, ctimeSyncService](std::chrono::nanoseconds now, std::chrono::nanoseconds duration) { - handler(context, ctimeSyncService, static_cast(now.count()), - static_cast(duration.count())); - }, - std::chrono::nanoseconds(initialStepSize)); + handler(context, ctimeSyncService, static_cast(now.count()), + static_cast(duration.count())); + }, std::chrono::nanoseconds(initialStepSize)); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS @@ -450,14 +443,14 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Pause(SilKit_LifecycleService* clifecycleService, const char* reason) +SilKit_ReturnCode SilKitCALL SilKit_LifecycleService_Pause(SilKit_LifecycleService* clifecycleService, + const char* reason) try { ASSERT_VALID_POINTER_PARAMETER(clifecycleService); ASSERT_VALID_POINTER_PARAMETER(reason); - auto* lifeCycleService = - reinterpret_cast(clifecycleService); + auto* lifeCycleService = reinterpret_cast(clifecycleService); lifeCycleService->Pause(reason); return SilKit_ReturnCode_SUCCESS; } @@ -469,8 +462,7 @@ try { ASSERT_VALID_POINTER_PARAMETER(clifecycleService); - auto* lifeCycleService = - reinterpret_cast(clifecycleService); + auto* lifeCycleService = reinterpret_cast(clifecycleService); lifeCycleService->Continue(); return SilKit_ReturnCode_SUCCESS; } @@ -483,8 +475,7 @@ try ASSERT_VALID_POINTER_PARAMETER(lifecycleService); ASSERT_VALID_POINTER_PARAMETER(reason); - auto* cppLifecycleService = - reinterpret_cast(lifecycleService); + auto* cppLifecycleService = reinterpret_cast(lifecycleService); cppLifecycleService->Stop(reason); return SilKit_ReturnCode_SUCCESS; } @@ -493,8 +484,8 @@ CAPI_CATCH_EXCEPTIONS // SystemMonitor related functions SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_GetParticipantStatus(SilKit_ParticipantStatus* outParticipantState, - SilKit_SystemMonitor* csystemMonitor, - const char* participantName) + SilKit_SystemMonitor* csystemMonitor, + const char* participantName) try { ASSERT_VALID_POINTER_PARAMETER(csystemMonitor); @@ -504,7 +495,7 @@ try auto* systemMonitor = reinterpret_cast(csystemMonitor); auto& participantStatus = systemMonitor->ParticipantStatus(participantName); - SilKit_ParticipantStatus cstatus {}; + SilKit_ParticipantStatus cstatus{}; SilKit_Struct_Init(SilKit_ParticipantStatus, cstatus); cstatus.enterReason = participantStatus.enterReason.c_str(); @@ -519,7 +510,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_GetSystemState(SilKit_SystemState* outParticipantState, SilKit_SystemMonitor* csystemMonitor) +SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_GetSystemState(SilKit_SystemState* outParticipantState, + SilKit_SystemMonitor* csystemMonitor) try { ASSERT_VALID_POINTER_PARAMETER(csystemMonitor); @@ -533,8 +525,10 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_AddSystemStateHandler(SilKit_SystemMonitor* csystemMonitor, void* context, - SilKit_SystemStateHandler_t handler, SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_AddSystemStateHandler(SilKit_SystemMonitor* csystemMonitor, + void* context, + SilKit_SystemStateHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(csystemMonitor); @@ -545,15 +539,16 @@ try auto cppHandlerId = systemMonitor->AddSystemStateHandler( [handler, context, csystemMonitor](SilKit::Services::Orchestration::SystemState systemState) { - handler(context, csystemMonitor, (SilKit_SystemState)systemState); - }); + handler(context, csystemMonitor, (SilKit_SystemState)systemState); + }); *outHandlerId = static_cast(cppHandlerId); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_RemoveSystemStateHandler(SilKit_SystemMonitor* csystemMonitor, SilKit_HandlerId handlerId) +SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_RemoveSystemStateHandler(SilKit_SystemMonitor* csystemMonitor, + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(csystemMonitor); @@ -567,9 +562,10 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_AddParticipantStatusHandler(SilKit_SystemMonitor* csystemMonitor, void* context, - SilKit_ParticipantStatusHandler_t handler, - SilKit_HandlerId* outHandlerId) +SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_AddParticipantStatusHandler(SilKit_SystemMonitor* csystemMonitor, + void* context, + SilKit_ParticipantStatusHandler_t handler, + SilKit_HandlerId* outHandlerId) try { ASSERT_VALID_POINTER_PARAMETER(csystemMonitor); @@ -580,20 +576,18 @@ try auto cppHandlerId = systemMonitor->AddParticipantStatusHandler( [handler, context, csystemMonitor](SilKit::Services::Orchestration::ParticipantStatus cppStatus) { - SilKit_ParticipantStatus cStatus; - SilKit_Struct_Init(SilKit_ParticipantStatus, cStatus); - - cStatus.enterReason = cppStatus.enterReason.c_str(); - cStatus.enterTime = - std::chrono::duration_cast(cppStatus.enterTime.time_since_epoch()) - .count(); - cStatus.participantName = cppStatus.participantName.c_str(); - cStatus.participantState = (SilKit_ParticipantState)cppStatus.state; - cStatus.refreshTime = - std::chrono::duration_cast(cppStatus.refreshTime.time_since_epoch()) - .count(); - handler(context, csystemMonitor, cppStatus.participantName.c_str(), &cStatus); - }); + SilKit_ParticipantStatus cStatus; + SilKit_Struct_Init(SilKit_ParticipantStatus, cStatus); + + cStatus.enterReason = cppStatus.enterReason.c_str(); + cStatus.enterTime = + std::chrono::duration_cast(cppStatus.enterTime.time_since_epoch()).count(); + cStatus.participantName = cppStatus.participantName.c_str(); + cStatus.participantState = (SilKit_ParticipantState)cppStatus.state; + cStatus.refreshTime = + std::chrono::duration_cast(cppStatus.refreshTime.time_since_epoch()).count(); + handler(context, csystemMonitor, cppStatus.participantName.c_str(), &cStatus); + }); *outHandlerId = static_cast(cppHandlerId); return SilKit_ReturnCode_SUCCESS; } @@ -601,7 +595,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_SystemMonitor_RemoveParticipantStatusHandler(SilKit_SystemMonitor* csystemMonitor, - SilKit_HandlerId handlerId) + SilKit_HandlerId handlerId) try { ASSERT_VALID_POINTER_PARAMETER(csystemMonitor); @@ -627,11 +621,11 @@ try cppSystemMonitor->SetParticipantConnectedHandler( [handler, context, systemMonitor](const SilKit::Services::Orchestration::ParticipantConnectionInformation& cppParticipantConnectionInformation) { - SilKit_ParticipantConnectionInformation cParticipantConnectionInformation; - CppToC(cppParticipantConnectionInformation, cParticipantConnectionInformation); + SilKit_ParticipantConnectionInformation cParticipantConnectionInformation; + CppToC(cppParticipantConnectionInformation, cParticipantConnectionInformation); - handler(context, systemMonitor, &cParticipantConnectionInformation); - }); + handler(context, systemMonitor, &cParticipantConnectionInformation); + }); return SilKit_ReturnCode_SUCCESS; } @@ -650,11 +644,11 @@ try cppSystemMonitor->SetParticipantDisconnectedHandler( [handler, context, systemMonitor](const SilKit::Services::Orchestration::ParticipantConnectionInformation& cppParticipantConnectionInformation) { - SilKit_ParticipantConnectionInformation cParticipantConnectionInformation; - CppToC(cppParticipantConnectionInformation, cParticipantConnectionInformation); + SilKit_ParticipantConnectionInformation cParticipantConnectionInformation; + CppToC(cppParticipantConnectionInformation, cParticipantConnectionInformation); - handler(context, systemMonitor, &cParticipantConnectionInformation); - }); + handler(context, systemMonitor, &cParticipantConnectionInformation); + }); return SilKit_ReturnCode_SUCCESS; } @@ -694,8 +688,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_Experimental_SystemController_AbortSimulation( - SilKit_Experimental_SystemController* cSystemController) +SilKit_ReturnCode SilKitCALL +SilKit_Experimental_SystemController_AbortSimulation(SilKit_Experimental_SystemController* cSystemController) try { ASSERT_VALID_POINTER_PARAMETER(cSystemController); @@ -711,8 +705,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_Experimental_SystemController_SetWorkflowConfiguration( - SilKit_Experimental_SystemController* cSystemController, - const SilKit_WorkflowConfiguration* cWorkflowConfiguration) + SilKit_Experimental_SystemController* cSystemController, const SilKit_WorkflowConfiguration* cWorkflowConfiguration) try { ASSERT_VALID_POINTER_PARAMETER(cSystemController); diff --git a/SilKit/source/capi/CapiParticipant.cpp b/SilKit/source/capi/CapiParticipant.cpp index b9f820874..86932177d 100644 --- a/SilKit/source/capi/CapiParticipant.cpp +++ b/SilKit/source/capi/CapiParticipant.cpp @@ -34,22 +34,12 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #include #include - -#ifdef _WIN32 -# define NOMINMAX -# define WIN32_LEAN_AND_MEAN -# include "Windows.h" -#endif - - -namespace { -auto OpenTextFile(const std::string& path) -> std::ifstream; -} // namespace +#include SilKit_ReturnCode SilKitCALL SilKit_Participant_Create(SilKit_Participant** outParticipant, - SilKit_ParticipantConfiguration *participantConfiguration, - const char* participantName, const char* registryUri) + SilKit_ParticipantConfiguration* participantConfiguration, + const char* participantName, const char* registryUri) try { ASSERT_VALID_OUT_PARAMETER(outParticipant); @@ -114,8 +104,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_ParticipantConfiguration_FromString( - SilKit_ParticipantConfiguration** outParticipantConfiguration, - const char* participantConfigurationString) + SilKit_ParticipantConfiguration** outParticipantConfiguration, const char* participantConfigurationString) try { ASSERT_VALID_OUT_PARAMETER(outParticipantConfiguration); @@ -141,31 +130,33 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_ParticipantConfiguration_FromFile( - SilKit_ParticipantConfiguration** outParticipantConfiguration, - const char* participantConfigurationPath) + SilKit_ParticipantConfiguration** outParticipantConfiguration, const char* participantConfigurationPath) try { ASSERT_VALID_OUT_PARAMETER(outParticipantConfiguration); ASSERT_VALID_POINTER_PARAMETER(participantConfigurationPath); - std::stringstream ss; - - // read the whole configuration file + // create the configuration using the C++ API function + auto cppSharedParticipantConfiguration = std::dynamic_pointer_cast( + SilKit::Config::ParticipantConfigurationFromFileImpl(participantConfigurationPath)); + if (cppSharedParticipantConfiguration == nullptr) { - const auto fs = OpenTextFile(participantConfigurationPath); - ss << fs.rdbuf(); + SilKit_error_string = "Participant configuration could not be created."; + return SilKit_ReturnCode_UNSPECIFIEDERROR; } - const auto string = ss.str(); + // since it is not possible to release the "raw" pointer from a shared_ptr, we copy it into our own raw pointer + auto* cppParticipantConfiguration = + new SilKit::Config::ParticipantConfiguration(*cppSharedParticipantConfiguration); - // dispatch to the function reading the configuration from a string - return SilKit_ParticipantConfiguration_FromString(outParticipantConfiguration, string.c_str()); + *outParticipantConfiguration = reinterpret_cast(cppParticipantConfiguration); + return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_ParticipantConfiguration_Destroy( - SilKit_ParticipantConfiguration* participantConfiguration) +SilKit_ReturnCode SilKitCALL +SilKit_ParticipantConfiguration_Destroy(SilKit_ParticipantConfiguration* participantConfiguration) try { ASSERT_VALID_POINTER_PARAMETER(participantConfiguration); @@ -183,47 +174,3 @@ try return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS - - -namespace { - -#ifdef _WIN32 - -auto OpenTextFile(const std::string& path) -> std::ifstream -{ - std::wstring widePath; - - constexpr DWORD MB2WC_FLAGS = 0; - - const auto pathSize = static_cast(path.size()); - - // determine the size of the required wide-character string - const int widePathSize = ::MultiByteToWideChar(CP_UTF8, MB2WC_FLAGS, path.c_str(), pathSize, NULL, 0); - if (widePathSize <= 0) - { - throw SilKit::ConfigurationError{"conversion from UTF-8 to UTF-16 failed"}; - } - - widePath.resize(static_cast(widePathSize)); - - // actually convert the path into a wide-character string - const int realWidePathSize = - ::MultiByteToWideChar(CP_UTF8, MB2WC_FLAGS, path.c_str(), pathSize, &widePath[0], widePathSize); - if (realWidePathSize != widePathSize) - { - throw SilKit::ConfigurationError{"conversion from UTF-8 to UTF-16 failed"}; - } - - return std::ifstream{widePath}; -} - -#else - -auto OpenTextFile(const std::string& path) -> std::ifstream -{ - return std::ifstream{path}; -} - -#endif - -} // namespace diff --git a/SilKit/source/capi/CapiRpc.cpp b/SilKit/source/capi/CapiRpc.cpp old mode 100755 new mode 100644 index 99ab7c82e..ab4df4a84 --- a/SilKit/source/capi/CapiRpc.cpp +++ b/SilKit/source/capi/CapiRpc.cpp @@ -38,9 +38,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace { -SilKit::Services::Rpc::RpcCallResultHandler MakeRpcCallResultHandler(void* context, SilKit_RpcCallResultHandler_t handler) +SilKit::Services::Rpc::RpcCallResultHandler MakeRpcCallResultHandler(void* context, + SilKit_RpcCallResultHandler_t handler) { - return [handler, context](SilKit::Services::Rpc::IRpcClient* cppClient, const SilKit::Services::Rpc::RpcCallResultEvent& event) { + return [handler, context](SilKit::Services::Rpc::IRpcClient* cppClient, + const SilKit::Services::Rpc::RpcCallResultEvent& event) { auto* cClient = reinterpret_cast(cppClient); SilKit_RpcCallResultEvent cEvent; SilKit_Struct_Init(SilKit_RpcCallResultEvent, cEvent); @@ -54,7 +56,8 @@ SilKit::Services::Rpc::RpcCallResultHandler MakeRpcCallResultHandler(void* conte SilKit::Services::Rpc::RpcCallHandler MakeRpcCallHandler(void* context, SilKit_RpcCallHandler_t handler) { - return [handler, context](SilKit::Services::Rpc::IRpcServer* cppServer, const SilKit::Services::Rpc::RpcCallEvent& event) { + return [handler, context](SilKit::Services::Rpc::IRpcServer* cppServer, + const SilKit::Services::Rpc::RpcCallEvent& event) { auto* cServer = reinterpret_cast(cppServer); SilKit_RpcCallEvent cEvent; SilKit_Struct_Init(SilKit_RpcCallEvent, cEvent); @@ -68,8 +71,9 @@ SilKit::Services::Rpc::RpcCallHandler MakeRpcCallHandler(void* context, SilKit_R } // namespace -SilKit_ReturnCode SilKitCALL SilKit_RpcServer_Create(SilKit_RpcServer** out, SilKit_Participant* participant, const char* controllerName, - SilKit_RpcSpec* rpcSpec, void* context, SilKit_RpcCallHandler_t callHandler) +SilKit_ReturnCode SilKitCALL SilKit_RpcServer_Create(SilKit_RpcServer** out, SilKit_Participant* participant, + const char* controllerName, SilKit_RpcSpec* rpcSpec, void* context, + SilKit_RpcCallHandler_t callHandler) try { ASSERT_VALID_OUT_PARAMETER(out); @@ -81,8 +85,8 @@ try auto cppParticipant = reinterpret_cast(participant); SilKit::Services::Rpc::RpcSpec cppDataSpec; assign(cppDataSpec, rpcSpec); - auto rcpServer = cppParticipant->CreateRpcServer(controllerName, cppDataSpec, - MakeRpcCallHandler(context, callHandler)); + auto rcpServer = + cppParticipant->CreateRpcServer(controllerName, cppDataSpec, MakeRpcCallHandler(context, callHandler)); *out = reinterpret_cast(rcpServer); return SilKit_ReturnCode_SUCCESS; @@ -91,7 +95,7 @@ CAPI_CATCH_EXCEPTIONS SilKit_ReturnCode SilKitCALL SilKit_RpcServer_SubmitResult(SilKit_RpcServer* self, SilKit_RpcCallHandle* callHandle, - const SilKit_ByteVector* returnData) + const SilKit_ByteVector* returnData) try { ASSERT_VALID_POINTER_PARAMETER(self); @@ -106,7 +110,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_RpcServer_SetCallHandler(SilKit_RpcServer* self, void* context, SilKit_RpcCallHandler_t handler) +SilKit_ReturnCode SilKitCALL SilKit_RpcServer_SetCallHandler(SilKit_RpcServer* self, void* context, + SilKit_RpcCallHandler_t handler) try { ASSERT_VALID_POINTER_PARAMETER(self); @@ -119,9 +124,9 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_RpcClient_Create(SilKit_RpcClient** out, SilKit_Participant* participant, const char* controllerName, - SilKit_RpcSpec* rpcSpec, - void* context, SilKit_RpcCallResultHandler_t resultHandler) +SilKit_ReturnCode SilKitCALL SilKit_RpcClient_Create(SilKit_RpcClient** out, SilKit_Participant* participant, + const char* controllerName, SilKit_RpcSpec* rpcSpec, void* context, + SilKit_RpcCallResultHandler_t resultHandler) try { ASSERT_VALID_OUT_PARAMETER(out); @@ -133,8 +138,8 @@ try auto cppParticipant = reinterpret_cast(participant); SilKit::Services::Rpc::RpcSpec cppRpcSpec; assign(cppRpcSpec, rpcSpec); - auto rcpClient = cppParticipant->CreateRpcClient(controllerName, cppRpcSpec, - MakeRpcCallResultHandler(context, resultHandler)); + auto rcpClient = + cppParticipant->CreateRpcClient(controllerName, cppRpcSpec, MakeRpcCallResultHandler(context, resultHandler)); *out = reinterpret_cast(rcpClient); return SilKit_ReturnCode_SUCCESS; @@ -142,7 +147,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_RpcClient_Call(SilKit_RpcClient* self, const SilKit_ByteVector* argumentData, void* userContext) +SilKit_ReturnCode SilKitCALL SilKit_RpcClient_Call(SilKit_RpcClient* self, const SilKit_ByteVector* argumentData, + void* userContext) try { ASSERT_VALID_POINTER_PARAMETER(self); @@ -154,8 +160,9 @@ try } CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_RpcClient_CallWithTimeout(SilKit_RpcClient* self, const SilKit_ByteVector* argumentData, - SilKit_NanosecondsTime duration, void* userContext) +SilKit_ReturnCode SilKitCALL SilKit_RpcClient_CallWithTimeout(SilKit_RpcClient* self, + const SilKit_ByteVector* argumentData, + SilKit_NanosecondsTime duration, void* userContext) try { ASSERT_VALID_POINTER_PARAMETER(self); @@ -168,7 +175,8 @@ try CAPI_CATCH_EXCEPTIONS -SilKit_ReturnCode SilKitCALL SilKit_RpcClient_SetCallResultHandler(SilKit_RpcClient* self, void* context, SilKit_RpcCallResultHandler_t handler) +SilKit_ReturnCode SilKitCALL SilKit_RpcClient_SetCallResultHandler(SilKit_RpcClient* self, void* context, + SilKit_RpcCallResultHandler_t handler) try { ASSERT_VALID_POINTER_PARAMETER(self); diff --git a/SilKit/source/capi/CapiVendor.cpp b/SilKit/source/capi/CapiVendor.cpp index daa75cfe1..a21ac9eb0 100644 --- a/SilKit/source/capi/CapiVendor.cpp +++ b/SilKit/source/capi/CapiVendor.cpp @@ -88,9 +88,8 @@ try auto* cppRegistry = reinterpret_cast(cSilKitRegistry); - cppRegistry->SetAllDisconnectedHandler([handler, context, cSilKitRegistry]() { - handler(context, cSilKitRegistry); - }); + cppRegistry->SetAllDisconnectedHandler( + [handler, context, cSilKitRegistry]() { handler(context, cSilKitRegistry); }); return SilKit_ReturnCode_SUCCESS; } diff --git a/SilKit/source/capi/Test_CapiCan.cpp b/SilKit/source/capi/Test_CapiCan.cpp old mode 100755 new mode 100644 index 9bd96a778..4503806ae --- a/SilKit/source/capi/Test_CapiCan.cpp +++ b/SilKit/source/capi/Test_CapiCan.cpp @@ -25,316 +25,325 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "MockParticipant.hpp" namespace { - using namespace SilKit::Services::Can; - using SilKit::Core::Tests::DummyParticipant; - - MATCHER_P(CanFrameMatcher, controlFrame, "") { - *result_listener << "matches can frames of the c-api to the cpp api"; - const SilKit_CanFrame& frame2 = controlFrame; - const CanFrame& frame1 = arg; - if (frame1.canId != frame2.id || frame1.dlc != frame2.dlc || frame1.dataField.size() != frame2.data.size) - { - return false; - } - for (size_t i = 0; i < frame1.dataField.size(); i++) - { - if (frame1.dataField[i] != frame2.data.data[i]) - { - return false; - } - } - if (frame1.sdt != frame2.sdt || frame1.vcid != frame2.vcid || frame1.af != frame2.af) - { - return false; - } - if (((frame1.flags & static_cast(CanFrameFlag::Ide)) != 0) != ((frame2.flags & SilKit_CanFrameFlag_ide) != 0)) - { - return false; - } - if (((frame1.flags & static_cast(CanFrameFlag::Fdf)) != 0) != ((frame2.flags & SilKit_CanFrameFlag_fdf) != 0)) - { - return false; - } - if (((frame1.flags & static_cast(CanFrameFlag::Brs)) != 0) != ((frame2.flags & SilKit_CanFrameFlag_brs) != 0)) - { - return false; - } - if (((frame1.flags & static_cast(CanFrameFlag::Esi)) != 0) != ((frame2.flags & SilKit_CanFrameFlag_esi) != 0)) - { - return false; - } - if (((frame1.flags & static_cast(CanFrameFlag::Rtr)) != 0) != ((frame2.flags & SilKit_CanFrameFlag_rtr) != 0)) - { - return false; - } - if (((frame1.flags & static_cast(CanFrameFlag::Xlf)) != 0) != ((frame2.flags & SilKit_CanFrameFlag_xlf) != 0)) - { - return false; - } - if (((frame1.flags & static_cast(CanFrameFlag::Sec)) != 0) != ((frame2.flags & SilKit_CanFrameFlag_sec) != 0)) +using namespace SilKit::Services::Can; +using SilKit::Core::Tests::DummyParticipant; + +MATCHER_P(CanFrameMatcher, controlFrame, "") +{ + *result_listener << "matches can frames of the c-api to the cpp api"; + const SilKit_CanFrame& frame2 = controlFrame; + const CanFrame& frame1 = arg; + if (frame1.canId != frame2.id || frame1.dlc != frame2.dlc || frame1.dataField.size() != frame2.data.size) + { + return false; + } + for (size_t i = 0; i < frame1.dataField.size(); i++) + { + if (frame1.dataField[i] != frame2.data.data[i]) { return false; } - return true; } - - class MockCanController : public SilKit::Services::Can::ICanController + if (frame1.sdt != frame2.sdt || frame1.vcid != frame2.vcid || frame1.af != frame2.af) { - public: - MOCK_METHOD(void, SetBaudRate, (uint32_t rate, uint32_t fdRate, uint32_t xlRate), (override)); - MOCK_METHOD(void, Reset, (), (override)); - MOCK_METHOD(void, Start, (), (override)); - MOCK_METHOD(void, Stop, (), (override)); - MOCK_METHOD(void, Sleep, (), (override)); - MOCK_METHOD(void, SendFrame, (const CanFrame&, void*), (override)); - MOCK_METHOD(SilKit::Services::HandlerId, AddFrameHandler, (FrameHandler, SilKit::Services::DirectionMask), (override)); - MOCK_METHOD(void, RemoveFrameHandler, (SilKit::Services::HandlerId), (override)); - MOCK_METHOD(SilKit::Services::HandlerId, AddStateChangeHandler, (StateChangeHandler), (override)); - MOCK_METHOD(void, RemoveStateChangeHandler, (SilKit::Services::HandlerId), (override)); - MOCK_METHOD(SilKit::Services::HandlerId, AddErrorStateChangeHandler, (ErrorStateChangeHandler), (override)); - MOCK_METHOD(void, RemoveErrorStateChangeHandler, (SilKit::Services::HandlerId), (override)); - MOCK_METHOD(SilKit::Services::HandlerId, AddFrameTransmitHandler, (FrameTransmitHandler, CanTransmitStatusMask), (override)); - MOCK_METHOD(void, RemoveFrameTransmitHandler, (SilKit::Services::HandlerId), (override)); - }; - - void SilKitCALL FrameTransmitHandler(void* /*context*/, SilKit_CanController* /*controller*/, SilKit_CanFrameTransmitEvent* /*ack*/) + return false; + } + if (((frame1.flags & static_cast(CanFrameFlag::Ide)) != 0) + != ((frame2.flags & SilKit_CanFrameFlag_ide) != 0)) { + return false; } - - void SilKitCALL FrameHandler(void* /*context*/, SilKit_CanController* /*controller*/, SilKit_CanFrameEvent* /*metaData*/) + if (((frame1.flags & static_cast(CanFrameFlag::Fdf)) != 0) + != ((frame2.flags & SilKit_CanFrameFlag_fdf) != 0)) { + return false; } - - void SilKitCALL StateChangeHandler(void* /*context*/, SilKit_CanController* /*controller*/, SilKit_CanStateChangeEvent* /*state*/) + if (((frame1.flags & static_cast(CanFrameFlag::Brs)) != 0) + != ((frame2.flags & SilKit_CanFrameFlag_brs) != 0)) { + return false; } - - void SilKitCALL ErrorStateChangeHandler(void* /*context*/, SilKit_CanController* /*controller*/, SilKit_CanErrorStateChangeEvent* /*state*/) + if (((frame1.flags & static_cast(CanFrameFlag::Esi)) != 0) + != ((frame2.flags & SilKit_CanFrameFlag_esi) != 0)) { + return false; } - - class MockParticipant : public DummyParticipant + if (((frame1.flags & static_cast(CanFrameFlag::Rtr)) != 0) + != ((frame2.flags & SilKit_CanFrameFlag_rtr) != 0)) { - public: - MOCK_METHOD2(CreateCanController, SilKit::Services::Can::ICanController*(const std::string& /*canonicalName*/, - const std::string& /*networkName*/)); - }; - - class Test_CapiCan : public testing::Test + return false; + } + if (((frame1.flags & static_cast(CanFrameFlag::Xlf)) != 0) + != ((frame2.flags & SilKit_CanFrameFlag_xlf) != 0)) { - public: - MockCanController mockController; - Test_CapiCan() - { - } - }; - - TEST_F(Test_CapiCan, can_controller_function_mapping) + return false; + } + if (((frame1.flags & static_cast(CanFrameFlag::Sec)) != 0) + != ((frame2.flags & SilKit_CanFrameFlag_sec) != 0)) { - using SilKit::Util::HandlerId; - - SilKit_ReturnCode returnCode; - MockParticipant mockParticipant; - SilKit_HandlerId handlerId; - - EXPECT_CALL(mockParticipant, CreateCanController("ControllerName", "NetworkName")).Times(testing::Exactly(1)); - SilKit_CanController* testParam; - returnCode = SilKit_CanController_Create(&testParam, (SilKit_Participant*)&mockParticipant, "ControllerName", - "NetworkName"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, SetBaudRate(123, 456, 789)).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_SetBaudRate((SilKit_CanController*)&mockController, 123, 456, 789); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, Start()).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_Start((SilKit_CanController*)&mockController); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, Stop()).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_Stop((SilKit_CanController*)&mockController); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, Sleep()).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_Sleep((SilKit_CanController*)&mockController); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, SendFrame(testing::_, testing::_)).Times(testing::Exactly(1)); - SilKit_CanFrame cf{}; - SilKit_Struct_Init(SilKit_CanFrame, cf); - cf.id = 1; - returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf, NULL); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, AddFrameHandler(testing::_, testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_AddFrameHandler((SilKit_CanController*)&mockController, NULL, &FrameHandler, - SilKit_Direction_SendReceive, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, RemoveFrameHandler(static_cast(0))).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_RemoveFrameHandler((SilKit_CanController*)&mockController, 0); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, AddStateChangeHandler(testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_AddStateChangeHandler((SilKit_CanController*)&mockController, NULL, - &StateChangeHandler, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, RemoveStateChangeHandler(static_cast(0))).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_RemoveStateChangeHandler((SilKit_CanController*)&mockController, 0); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, AddErrorStateChangeHandler(testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_AddErrorStateChangeHandler((SilKit_CanController*)&mockController, NULL, - &ErrorStateChangeHandler, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, RemoveErrorStateChangeHandler(static_cast(0))).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_RemoveErrorStateChangeHandler((SilKit_CanController*)&mockController, 0); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, AddFrameTransmitHandler(testing::_, testing::_)).Times(testing::Exactly(1)); - returnCode = - SilKit_CanController_AddFrameTransmitHandler((SilKit_CanController*)&mockController, NULL, &FrameTransmitHandler, - SilKit_CanTransmitStatus_Transmitted, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockController, RemoveFrameTransmitHandler(static_cast(0))).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_RemoveFrameTransmitHandler((SilKit_CanController*)&mockController, 0); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - + return false; } + return true; +} - TEST_F(Test_CapiCan, can_controller_send_frame_no_flags) - { +class MockCanController : public SilKit::Services::Can::ICanController +{ +public: + MOCK_METHOD(void, SetBaudRate, (uint32_t rate, uint32_t fdRate, uint32_t xlRate), (override)); + MOCK_METHOD(void, Reset, (), (override)); + MOCK_METHOD(void, Start, (), (override)); + MOCK_METHOD(void, Stop, (), (override)); + MOCK_METHOD(void, Sleep, (), (override)); + MOCK_METHOD(void, SendFrame, (const CanFrame&, void*), (override)); + MOCK_METHOD(SilKit::Services::HandlerId, AddFrameHandler, (FrameHandler, SilKit::Services::DirectionMask), + (override)); + MOCK_METHOD(void, RemoveFrameHandler, (SilKit::Services::HandlerId), (override)); + MOCK_METHOD(SilKit::Services::HandlerId, AddStateChangeHandler, (StateChangeHandler), (override)); + MOCK_METHOD(void, RemoveStateChangeHandler, (SilKit::Services::HandlerId), (override)); + MOCK_METHOD(SilKit::Services::HandlerId, AddErrorStateChangeHandler, (ErrorStateChangeHandler), (override)); + MOCK_METHOD(void, RemoveErrorStateChangeHandler, (SilKit::Services::HandlerId), (override)); + MOCK_METHOD(SilKit::Services::HandlerId, AddFrameTransmitHandler, (FrameTransmitHandler, CanTransmitStatusMask), + (override)); + MOCK_METHOD(void, RemoveFrameTransmitHandler, (SilKit::Services::HandlerId), (override)); +}; + +void SilKitCALL FrameTransmitHandler(void* /*context*/, SilKit_CanController* /*controller*/, + SilKit_CanFrameTransmitEvent* /*ack*/) +{ +} - SilKit_ReturnCode returnCode; - - SilKit_CanFrame cf1{}; - SilKit_Struct_Init(SilKit_CanFrame, cf1); - cf1.id = 1; - cf1.data = { 0,0 }; - cf1.dlc = 1; - cf1.flags = 0; - EXPECT_CALL(mockController, SendFrame(CanFrameMatcher(cf1), testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf1, NULL); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } +void SilKitCALL FrameHandler(void* /*context*/, SilKit_CanController* /*controller*/, + SilKit_CanFrameEvent* /*metaData*/) +{ +} - TEST_F(Test_CapiCan, can_controller_send_frame_flags1) - { +void SilKitCALL StateChangeHandler(void* /*context*/, SilKit_CanController* /*controller*/, + SilKit_CanStateChangeEvent* /*state*/) +{ +} - SilKit_ReturnCode returnCode; - - SilKit_CanFrame cf1{}; - SilKit_Struct_Init(SilKit_CanFrame, cf1); - cf1.id = 1; - cf1.data = { 0,0 }; - cf1.dlc = 1; - cf1.flags = SilKit_CanFrameFlag_ide | SilKit_CanFrameFlag_rtr | SilKit_CanFrameFlag_esi; - EXPECT_CALL(mockController, SendFrame(CanFrameMatcher(cf1), testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf1, NULL); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } +void SilKitCALL ErrorStateChangeHandler(void* /*context*/, SilKit_CanController* /*controller*/, + SilKit_CanErrorStateChangeEvent* /*state*/) +{ +} - TEST_F(Test_CapiCan, can_controller_send_frame_flags2) - { +class MockParticipant : public DummyParticipant +{ +public: + MOCK_METHOD2(CreateCanController, SilKit::Services::Can::ICanController*(const std::string& /*canonicalName*/, + const std::string& /*networkName*/)); +}; - SilKit_ReturnCode returnCode; - - SilKit_CanFrame cf1{}; - SilKit_Struct_Init(SilKit_CanFrame, cf1); - cf1.id = 1; - cf1.data = { 0,0 }; - cf1.dlc = 1; - cf1.flags = SilKit_CanFrameFlag_fdf | SilKit_CanFrameFlag_brs; - EXPECT_CALL(mockController, SendFrame(CanFrameMatcher(cf1), testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf1, NULL); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } +class Test_CapiCan : public testing::Test +{ +public: + MockCanController mockController; + Test_CapiCan() {} +}; +TEST_F(Test_CapiCan, can_controller_function_mapping) +{ + using SilKit::Util::HandlerId; - TEST_F(Test_CapiCan, can_controller_nullpointer_params) - { - SilKit_ReturnCode returnCode; - SilKit_HandlerId handlerId; - - returnCode = SilKit_CanController_SetBaudRate(nullptr, 123, 456, 789); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - returnCode = SilKit_CanController_Start(nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - returnCode = SilKit_CanController_Stop(nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - returnCode = SilKit_CanController_Sleep(nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - SilKit_CanFrame cf{}; - SilKit_Struct_Init(SilKit_CanFrame, cf); - cf.id = 1; - returnCode = SilKit_CanController_SendFrame(nullptr, &cf, NULL); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, nullptr, NULL); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - - returnCode = - SilKit_CanController_AddFrameHandler(nullptr, NULL, &FrameHandler, SilKit_Direction_SendReceive, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_AddFrameHandler((SilKit_CanController*)&mockController, NULL, nullptr, - SilKit_Direction_SendReceive, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_AddFrameHandler((SilKit_CanController*)&mockController, NULL, &FrameHandler, - SilKit_Direction_SendReceive, nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - - returnCode = SilKit_CanController_AddStateChangeHandler(nullptr, NULL, &StateChangeHandler, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = - SilKit_CanController_AddStateChangeHandler((SilKit_CanController*)&mockController, NULL, nullptr, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_AddStateChangeHandler((SilKit_CanController*)&mockController, NULL, - &StateChangeHandler, nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - - returnCode = SilKit_CanController_AddErrorStateChangeHandler(nullptr, NULL, &ErrorStateChangeHandler, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_AddErrorStateChangeHandler((SilKit_CanController*)&mockController, NULL, nullptr, - &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_AddErrorStateChangeHandler((SilKit_CanController*)&mockController, NULL, - &ErrorStateChangeHandler, nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - - returnCode = SilKit_CanController_AddFrameTransmitHandler(nullptr, NULL, &FrameTransmitHandler, - SilKit_CanTransmitStatus_Canceled, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_AddFrameTransmitHandler((SilKit_CanController*)&mockController, NULL, nullptr, - SilKit_CanTransmitStatus_Canceled, &handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_AddFrameTransmitHandler( - (SilKit_CanController*)&mockController, NULL, &FrameTransmitHandler, SilKit_CanTransmitStatus_Canceled, nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - - returnCode = SilKit_CanController_RemoveFrameHandler(nullptr, handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_RemoveFrameTransmitHandler(nullptr, handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_RemoveStateChangeHandler(nullptr, handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_CanController_RemoveErrorStateChangeHandler(nullptr, handlerId); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - } + SilKit_ReturnCode returnCode; + MockParticipant mockParticipant; + SilKit_HandlerId handlerId; + + EXPECT_CALL(mockParticipant, CreateCanController("ControllerName", "NetworkName")).Times(testing::Exactly(1)); + SilKit_CanController* testParam; + returnCode = + SilKit_CanController_Create(&testParam, (SilKit_Participant*)&mockParticipant, "ControllerName", "NetworkName"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, SetBaudRate(123, 456, 789)).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_SetBaudRate((SilKit_CanController*)&mockController, 123, 456, 789); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, Start()).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_Start((SilKit_CanController*)&mockController); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, Stop()).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_Stop((SilKit_CanController*)&mockController); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, Sleep()).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_Sleep((SilKit_CanController*)&mockController); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, SendFrame(testing::_, testing::_)).Times(testing::Exactly(1)); + SilKit_CanFrame cf{}; + SilKit_Struct_Init(SilKit_CanFrame, cf); + cf.id = 1; + returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf, NULL); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, AddFrameHandler(testing::_, testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_AddFrameHandler((SilKit_CanController*)&mockController, NULL, &FrameHandler, + SilKit_Direction_SendReceive, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, RemoveFrameHandler(static_cast(0))).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_RemoveFrameHandler((SilKit_CanController*)&mockController, 0); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, AddStateChangeHandler(testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_AddStateChangeHandler((SilKit_CanController*)&mockController, NULL, + &StateChangeHandler, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, RemoveStateChangeHandler(static_cast(0))).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_RemoveStateChangeHandler((SilKit_CanController*)&mockController, 0); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, AddErrorStateChangeHandler(testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_AddErrorStateChangeHandler((SilKit_CanController*)&mockController, NULL, + &ErrorStateChangeHandler, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, RemoveErrorStateChangeHandler(static_cast(0))).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_RemoveErrorStateChangeHandler((SilKit_CanController*)&mockController, 0); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, AddFrameTransmitHandler(testing::_, testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_AddFrameTransmitHandler((SilKit_CanController*)&mockController, NULL, + &FrameTransmitHandler, + SilKit_CanTransmitStatus_Transmitted, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockController, RemoveFrameTransmitHandler(static_cast(0))).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_RemoveFrameTransmitHandler((SilKit_CanController*)&mockController, 0); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); +} + +TEST_F(Test_CapiCan, can_controller_send_frame_no_flags) +{ + SilKit_ReturnCode returnCode; + + SilKit_CanFrame cf1{}; + SilKit_Struct_Init(SilKit_CanFrame, cf1); + cf1.id = 1; + cf1.data = {0, 0}; + cf1.dlc = 1; + cf1.flags = 0; + EXPECT_CALL(mockController, SendFrame(CanFrameMatcher(cf1), testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf1, NULL); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); +} + +TEST_F(Test_CapiCan, can_controller_send_frame_flags1) +{ + SilKit_ReturnCode returnCode; + + SilKit_CanFrame cf1{}; + SilKit_Struct_Init(SilKit_CanFrame, cf1); + cf1.id = 1; + cf1.data = {0, 0}; + cf1.dlc = 1; + cf1.flags = SilKit_CanFrameFlag_ide | SilKit_CanFrameFlag_rtr | SilKit_CanFrameFlag_esi; + EXPECT_CALL(mockController, SendFrame(CanFrameMatcher(cf1), testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf1, NULL); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); +} + +TEST_F(Test_CapiCan, can_controller_send_frame_flags2) +{ + SilKit_ReturnCode returnCode; + + SilKit_CanFrame cf1{}; + SilKit_Struct_Init(SilKit_CanFrame, cf1); + cf1.id = 1; + cf1.data = {0, 0}; + cf1.dlc = 1; + cf1.flags = SilKit_CanFrameFlag_fdf | SilKit_CanFrameFlag_brs; + EXPECT_CALL(mockController, SendFrame(CanFrameMatcher(cf1), testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf1, NULL); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); +} + + +TEST_F(Test_CapiCan, can_controller_nullpointer_params) +{ + SilKit_ReturnCode returnCode; + SilKit_HandlerId handlerId; + + returnCode = SilKit_CanController_SetBaudRate(nullptr, 123, 456, 789); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + returnCode = SilKit_CanController_Start(nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + returnCode = SilKit_CanController_Stop(nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + returnCode = SilKit_CanController_Sleep(nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + SilKit_CanFrame cf{}; + SilKit_Struct_Init(SilKit_CanFrame, cf); + cf.id = 1; + returnCode = SilKit_CanController_SendFrame(nullptr, &cf, NULL); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, nullptr, NULL); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + + returnCode = + SilKit_CanController_AddFrameHandler(nullptr, NULL, &FrameHandler, SilKit_Direction_SendReceive, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_AddFrameHandler((SilKit_CanController*)&mockController, NULL, nullptr, + SilKit_Direction_SendReceive, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_AddFrameHandler((SilKit_CanController*)&mockController, NULL, &FrameHandler, + SilKit_Direction_SendReceive, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + + returnCode = SilKit_CanController_AddStateChangeHandler(nullptr, NULL, &StateChangeHandler, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = + SilKit_CanController_AddStateChangeHandler((SilKit_CanController*)&mockController, NULL, nullptr, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_AddStateChangeHandler((SilKit_CanController*)&mockController, NULL, + &StateChangeHandler, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + + returnCode = SilKit_CanController_AddErrorStateChangeHandler(nullptr, NULL, &ErrorStateChangeHandler, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_AddErrorStateChangeHandler((SilKit_CanController*)&mockController, NULL, nullptr, + &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_AddErrorStateChangeHandler((SilKit_CanController*)&mockController, NULL, + &ErrorStateChangeHandler, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + + returnCode = SilKit_CanController_AddFrameTransmitHandler(nullptr, NULL, &FrameTransmitHandler, + SilKit_CanTransmitStatus_Canceled, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_AddFrameTransmitHandler((SilKit_CanController*)&mockController, NULL, nullptr, + SilKit_CanTransmitStatus_Canceled, &handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = + SilKit_CanController_AddFrameTransmitHandler((SilKit_CanController*)&mockController, NULL, + &FrameTransmitHandler, SilKit_CanTransmitStatus_Canceled, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + + returnCode = SilKit_CanController_RemoveFrameHandler(nullptr, handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_RemoveFrameTransmitHandler(nullptr, handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_RemoveStateChangeHandler(nullptr, handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_CanController_RemoveErrorStateChangeHandler(nullptr, handlerId); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); +} TEST_F(Test_CapiCan, send_with_invalud_struct_header) { - SilKit_CanFrame cf{};// we do not call SilKit_Struct_Init(SilKit_CanFrame, cf) here + SilKit_CanFrame cf{}; // we do not call SilKit_Struct_Init(SilKit_CanFrame, cf) here cf.id = 1; auto returnCode = SilKit_CanController_SendFrame((SilKit_CanController*)&mockController, &cf, nullptr); ASSERT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); diff --git a/SilKit/source/capi/Test_CapiData.cpp b/SilKit/source/capi/Test_CapiData.cpp index 763b629d7..8c282b1d8 100644 --- a/SilKit/source/capi/Test_CapiData.cpp +++ b/SilKit/source/capi/Test_CapiData.cpp @@ -21,7 +21,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef WIN32 -# define _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS #endif #include "gtest/gtest.h" @@ -67,7 +67,8 @@ class MockParticipant : public SilKit::Core::Tests::DummyParticipant { public: MOCK_METHOD(SilKit::Services::PubSub::IDataPublisher*, CreateDataPublisher, - (const std::string& /*canonicalName*/, (const SilKit::Services::PubSub::PubSubSpec& /*dataSpec*/), size_t /*history*/), + (const std::string& /*canonicalName*/, (const SilKit::Services::PubSub::PubSubSpec& /*dataSpec*/), + size_t /*history*/), (override)); MOCK_METHOD(SilKit::Services::PubSub::IDataSubscriber*, CreateDataSubscriber, @@ -123,8 +124,8 @@ class Test_CapiData : public testing::Test { for (uint32_t index = 0; index != labelList->numLabels; ++index) { - free(const_cast(labelList->labels[index].key)); - free(const_cast(labelList->labels[index].value)); + free(const_cast(labelList->labels[index].key)); + free(const_cast(labelList->labels[index].value)); } free(labelList->labels); free(labelList); @@ -142,7 +143,8 @@ class Test_CapiData : public testing::Test SilKit_LabelList* labelList; }; -void SilKitCALL DefaultDataHandler(void* /*context*/, SilKit_DataSubscriber* /*subscriber*/, const SilKit_DataMessageEvent* /*dataMessageEvent*/) +void SilKitCALL DefaultDataHandler(void* /*context*/, SilKit_DataSubscriber* /*subscriber*/, + const SilKit_DataMessageEvent* /*dataMessageEvent*/) { } @@ -175,9 +177,7 @@ TEST_F(Test_CapiData, data_subscriber_function_mapping) SilKit_DataSubscriber* subscriber; - EXPECT_CALL(mockParticipant, - CreateDataSubscriber("subscriber", testing::_, testing::_)) - .Times(testing::Exactly(1)); + EXPECT_CALL(mockParticipant, CreateDataSubscriber("subscriber", testing::_, testing::_)).Times(testing::Exactly(1)); SilKit_DataSpec dataSpec; SilKit_Struct_Init(SilKit_DataSpec, dataSpec); dataSpec.topic = "TopicA"; @@ -190,9 +190,8 @@ TEST_F(Test_CapiData, data_subscriber_function_mapping) EXPECT_CALL(mockDataSubscriber, SetDataMessageHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_DataSubscriber_SetDataMessageHandler((SilKit_DataSubscriber*)&mockDataSubscriber, nullptr, - &DefaultDataHandler); + &DefaultDataHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } TEST_F(Test_CapiData, data_publisher_bad_parameters) @@ -207,8 +206,7 @@ TEST_F(Test_CapiData, data_publisher_bad_parameters) dataSpec.labelList.numLabels = 0; dataSpec.labelList.labels = nullptr; - returnCode = - SilKit_DataPublisher_Create(nullptr, (SilKit_Participant*)&mockParticipant, "publisher", &dataSpec, 0); + returnCode = SilKit_DataPublisher_Create(nullptr, (SilKit_Participant*)&mockParticipant, "publisher", &dataSpec, 0); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_DataPublisher_Create(&publisher, nullptr, "publisher", &dataSpec, 0); @@ -217,7 +215,8 @@ TEST_F(Test_CapiData, data_publisher_bad_parameters) returnCode = SilKit_DataPublisher_Create(&publisher, (SilKit_Participant*)&mockParticipant, nullptr, &dataSpec, 0); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_DataPublisher_Create(&publisher, (SilKit_Participant*)&mockParticipant, "publisher", nullptr, 0); + returnCode = + SilKit_DataPublisher_Create(&publisher, (SilKit_Participant*)&mockParticipant, "publisher", nullptr, 0); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_DataPublisher_Publish(nullptr, &data); @@ -238,30 +237,27 @@ TEST_F(Test_CapiData, data_subscriber_bad_parameters) dataSpec.labelList.numLabels = 0; dataSpec.labelList.labels = nullptr; - returnCode = - SilKit_DataSubscriber_Create(nullptr, (SilKit_Participant*)&mockParticipant, "subscriber", &dataSpec, - dummyContextPtr, - &DefaultDataHandler); + returnCode = SilKit_DataSubscriber_Create(nullptr, (SilKit_Participant*)&mockParticipant, "subscriber", &dataSpec, + dummyContextPtr, &DefaultDataHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_DataSubscriber_Create(&subscriber, nullptr, "subscriber", &dataSpec, - dummyContextPtr, &DefaultDataHandler); + returnCode = SilKit_DataSubscriber_Create(&subscriber, nullptr, "subscriber", &dataSpec, dummyContextPtr, + &DefaultDataHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = - SilKit_DataSubscriber_Create(&subscriber, (SilKit_Participant*)&mockParticipant, nullptr, &dataSpec, - dummyContextPtr, &DefaultDataHandler); + returnCode = SilKit_DataSubscriber_Create(&subscriber, (SilKit_Participant*)&mockParticipant, nullptr, &dataSpec, + dummyContextPtr, &DefaultDataHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_DataSubscriber_Create(&subscriber, (SilKit_Participant*)&mockParticipant, "subscriber", nullptr, dummyContextPtr, - &DefaultDataHandler); + returnCode = SilKit_DataSubscriber_Create(&subscriber, (SilKit_Participant*)&mockParticipant, "subscriber", nullptr, + dummyContextPtr, &DefaultDataHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_DataSubscriber_SetDataMessageHandler(nullptr, dummyContextPtr, &DefaultDataHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = - SilKit_DataSubscriber_SetDataMessageHandler((SilKit_DataSubscriber*)&mockDataSubscriber, dummyContextPtr, nullptr); + returnCode = SilKit_DataSubscriber_SetDataMessageHandler((SilKit_DataSubscriber*)&mockDataSubscriber, + dummyContextPtr, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); } diff --git a/SilKit/source/capi/Test_CapiEthernet.cpp b/SilKit/source/capi/Test_CapiEthernet.cpp old mode 100755 new mode 100644 index 6b3646b6b..08a84c8cb --- a/SilKit/source/capi/Test_CapiEthernet.cpp +++ b/SilKit/source/capi/Test_CapiEthernet.cpp @@ -32,7 +32,7 @@ namespace { using namespace SilKit::Services::Ethernet; using SilKit::Core::Tests::DummyParticipant; -MATCHER_P(EthFrameMatcher, controlFrame, "") +MATCHER_P(EthFrameMatcher, controlFrame, "") { *result_listener << "matches ethernet frames by their content and length"; auto frame1 = controlFrame; @@ -51,13 +51,16 @@ MATCHER_P(EthFrameMatcher, controlFrame, "") return true; } -class MockEthernetController : public SilKit::Services::Ethernet::IEthernetController { +class MockEthernetController : public SilKit::Services::Ethernet::IEthernetController +{ public: MOCK_METHOD(void, Activate, (), (override)); MOCK_METHOD(void, Deactivate, (), (override)); - MOCK_METHOD(SilKit::Services::HandlerId, AddFrameHandler, (FrameHandler, SilKit::Services::DirectionMask), (override)); + MOCK_METHOD(SilKit::Services::HandlerId, AddFrameHandler, (FrameHandler, SilKit::Services::DirectionMask), + (override)); MOCK_METHOD(void, RemoveFrameHandler, (SilKit::Services::HandlerId), (override)); - MOCK_METHOD(SilKit::Services::HandlerId, AddFrameTransmitHandler, (FrameTransmitHandler, EthernetTransmitStatusMask), (override)); + MOCK_METHOD(SilKit::Services::HandlerId, AddFrameTransmitHandler, + (FrameTransmitHandler, EthernetTransmitStatusMask), (override)); MOCK_METHOD(void, RemoveFrameTransmitHandler, (SilKit::Services::HandlerId), (override)); MOCK_METHOD(SilKit::Services::HandlerId, AddStateChangeHandler, (StateChangeHandler), (override)); MOCK_METHOD(void, RemoveStateChangeHandler, (SilKit::Services::HandlerId), (override)); @@ -68,34 +71,37 @@ class MockEthernetController : public SilKit::Services::Ethernet::IEthernetContr class Test_CapiEthernet : public testing::Test { -public: +public: MockEthernetController mockController; - Test_CapiEthernet() - { - } + Test_CapiEthernet() {} }; -void SilKitCALL FrameTransmitHandler(void* /*context*/, SilKit_EthernetController* /*controller*/, SilKit_EthernetFrameTransmitEvent* /*cAck*/) +void SilKitCALL FrameTransmitHandler(void* /*context*/, SilKit_EthernetController* /*controller*/, + SilKit_EthernetFrameTransmitEvent* /*cAck*/) { } -void SilKitCALL FrameHandler(void* /*context*/, SilKit_EthernetController* /*controller*/, SilKit_EthernetFrameEvent* /*metaData*/) +void SilKitCALL FrameHandler(void* /*context*/, SilKit_EthernetController* /*controller*/, + SilKit_EthernetFrameEvent* /*metaData*/) { } -void SilKitCALL StateChangeHandler(void* /*context*/, SilKit_EthernetController* /*controller*/, SilKit_EthernetStateChangeEvent* /*stateChangeEvent*/) +void SilKitCALL StateChangeHandler(void* /*context*/, SilKit_EthernetController* /*controller*/, + SilKit_EthernetStateChangeEvent* /*stateChangeEvent*/) { } -void SilKitCALL BitrateChangeHandler(void* /*context*/, SilKit_EthernetController* /*controller*/, SilKit_EthernetBitrateChangeEvent* /*bitrateChangeEvent*/) +void SilKitCALL BitrateChangeHandler(void* /*context*/, SilKit_EthernetController* /*controller*/, + SilKit_EthernetBitrateChangeEvent* /*bitrateChangeEvent*/) { } - class MockParticipant : public DummyParticipant +class MockParticipant : public DummyParticipant { public: - MOCK_METHOD2(CreateEthernetController, SilKit::Services::Ethernet::IEthernetController*(const std::string& /*canonicalName*/, - const std::string& /*networkName*/)); + MOCK_METHOD2(CreateEthernetController, + SilKit::Services::Ethernet::IEthernetController*(const std::string& /*canonicalName*/, + const std::string& /*networkName*/)); }; TEST_F(Test_CapiEthernet, ethernet_controller_function_mapping) @@ -114,7 +120,7 @@ TEST_F(Test_CapiEthernet, ethernet_controller_function_mapping) EXPECT_CALL(mockParticipant, CreateEthernetController("ControllerName", "NetworkName")).Times(testing::Exactly(1)); SilKit_EthernetController* testParam; returnCode = SilKit_EthernetController_Create(&testParam, (SilKit_Participant*)&mockParticipant, "ControllerName", - "NetworkName"); + "NetworkName"); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, Activate()).Times(testing::Exactly(1)); @@ -208,7 +214,7 @@ TEST_F(Test_CapiEthernet, ethernet_controller_function_mapping) EXPECT_CALL(mockController, AddStateChangeHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_EthernetController_AddStateChangeHandler((SilKit_EthernetController*)&mockController, NULL, - &StateChangeHandler, &handlerId); + &StateChangeHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveStateChangeHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -217,7 +223,7 @@ TEST_F(Test_CapiEthernet, ethernet_controller_function_mapping) EXPECT_CALL(mockController, AddBitrateChangeHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_EthernetController_AddBitrateChangeHandler((SilKit_EthernetController*)&mockController, NULL, - &BitrateChangeHandler, &handlerId); + &BitrateChangeHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveBitrateChangeHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -227,13 +233,15 @@ TEST_F(Test_CapiEthernet, ethernet_controller_function_mapping) WireEthernetFrame referenceFrame{}; referenceFrame.raw = SilKit::Util::SharedVector{SilKit::Util::MakeSpan(buffer)}; - EXPECT_CALL(mockController, SendFrame(EthFrameMatcher(ToEthernetFrame(referenceFrame)), nullptr)).Times(testing::Exactly(1)); + EXPECT_CALL(mockController, SendFrame(EthFrameMatcher(ToEthernetFrame(referenceFrame)), nullptr)) + .Times(testing::Exactly(1)); returnCode = SilKit_EthernetController_SendFrame((SilKit_EthernetController*)&mockController, &ef, NULL); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); const auto userContext = reinterpret_cast(0x12345); - EXPECT_CALL(mockController, SendFrame(EthFrameMatcher(ToEthernetFrame(referenceFrame)), userContext)).Times(testing::Exactly(1)); + EXPECT_CALL(mockController, SendFrame(EthFrameMatcher(ToEthernetFrame(referenceFrame)), userContext)) + .Times(testing::Exactly(1)); returnCode = SilKit_EthernetController_SendFrame((SilKit_EthernetController*)&mockController, &ef, userContext); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); } @@ -271,22 +279,22 @@ TEST_F(Test_CapiEthernet, ethernet_controller_nullptr_params) SilKit_EthernetTransmitStatus_Transmitted, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_EthernetController_AddStateChangeHandler((SilKit_EthernetController*)&mockController, NULL, nullptr, - &handlerId); + returnCode = SilKit_EthernetController_AddStateChangeHandler((SilKit_EthernetController*)&mockController, NULL, + nullptr, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_EthernetController_AddStateChangeHandler(nullptr, NULL, &StateChangeHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_EthernetController_AddStateChangeHandler((SilKit_EthernetController*)&mockController, NULL, - &StateChangeHandler, nullptr); + &StateChangeHandler, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_EthernetController_AddBitrateChangeHandler((SilKit_EthernetController*)&mockController, NULL, nullptr, - &handlerId); + returnCode = SilKit_EthernetController_AddBitrateChangeHandler((SilKit_EthernetController*)&mockController, NULL, + nullptr, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_EthernetController_AddBitrateChangeHandler(nullptr, NULL, &BitrateChangeHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_EthernetController_AddBitrateChangeHandler((SilKit_EthernetController*)&mockController, NULL, - &BitrateChangeHandler, nullptr); + &BitrateChangeHandler, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_EthernetController_RemoveFrameHandler(nullptr, handlerId); @@ -298,7 +306,7 @@ TEST_F(Test_CapiEthernet, ethernet_controller_nullptr_params) returnCode = SilKit_EthernetController_RemoveBitrateChangeHandler(nullptr, handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - const auto testUserContext = reinterpret_cast(0x12345); + const auto testUserContext = reinterpret_cast(0x12345); SilKit_EthernetFrame ef{}; SilKit_Struct_Init(SilKit_EthernetFrame, ef); @@ -306,7 +314,8 @@ TEST_F(Test_CapiEthernet, ethernet_controller_nullptr_params) returnCode = SilKit_EthernetController_SendFrame((SilKit_EthernetController*)&mockController, nullptr, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_EthernetController_SendFrame((SilKit_EthernetController*)&mockController, nullptr, testUserContext); + returnCode = + SilKit_EthernetController_SendFrame((SilKit_EthernetController*)&mockController, nullptr, testUserContext); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_EthernetController_SendFrame(nullptr, &ef, nullptr); @@ -324,11 +333,11 @@ TEST_F(Test_CapiEthernet, ethernet_controller_send_frame) uint8_t buffer[100]; // set destination mac - uint8_t destinationMac[6] = { 0xF6, 0x04, 0x68, 0x71, 0xAA, 0xC1 }; + uint8_t destinationMac[6] = {0xF6, 0x04, 0x68, 0x71, 0xAA, 0xC1}; memcpy(&(buffer[0]), destinationMac, sizeof(destinationMac)); // set source mac - uint8_t sourceMac[6] = { 0xF6, 0x04, 0x68, 0x71, 0xAA, 0xC2 }; + uint8_t sourceMac[6] = {0xF6, 0x04, 0x68, 0x71, 0xAA, 0xC2}; memcpy(&(buffer[6]), sourceMac, sizeof(sourceMac)); // set ethertype @@ -337,16 +346,14 @@ TEST_F(Test_CapiEthernet, ethernet_controller_send_frame) // set payload int ethernetMessageCounter = 1; - size_t payloadSize = snprintf((char*)buffer + PAYLOAD_OFFSET, - sizeof(buffer) - PAYLOAD_OFFSET, - "This is the demonstration ethernet frame number %i.", - ethernetMessageCounter); + size_t payloadSize = snprintf((char*)buffer + PAYLOAD_OFFSET, sizeof(buffer) - PAYLOAD_OFFSET, + "This is the demonstration ethernet frame number %i.", ethernetMessageCounter); SilKit_EthernetFrame ef{}; SilKit_Struct_Init(SilKit_EthernetFrame, ef); ef.raw = {(const uint8_t*)buffer, PAYLOAD_OFFSET + payloadSize}; - const auto testUserContext = reinterpret_cast(0x12345); + const auto testUserContext = reinterpret_cast(0x12345); EthernetFrame refFrame{}; std::vector rawFrame(ef.raw.data, ef.raw.data + ef.raw.size); @@ -354,7 +361,6 @@ TEST_F(Test_CapiEthernet, ethernet_controller_send_frame) EXPECT_CALL(mockController, SendFrame(EthFrameMatcher(refFrame), testUserContext)).Times(testing::Exactly(1)); returnCode = SilKit_EthernetController_SendFrame((SilKit_EthernetController*)&mockController, &ef, testUserContext); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } TEST_F(Test_CapiEthernet, ethernet_controller_send_short_frame) @@ -362,11 +368,11 @@ TEST_F(Test_CapiEthernet, ethernet_controller_send_short_frame) std::vector buffer; // set destination mac - const EthernetMac destinationMac{ 0xF6, 0x04, 0x68, 0x71, 0xAA, 0xC1 }; + const EthernetMac destinationMac{0xF6, 0x04, 0x68, 0x71, 0xAA, 0xC1}; std::copy(destinationMac.begin(), destinationMac.end(), std::back_inserter(buffer)); // set source mac - const EthernetMac sourceMac{ 0xF6, 0x04, 0x68, 0x71, 0xAA, 0xC2 }; + const EthernetMac sourceMac{0xF6, 0x04, 0x68, 0x71, 0xAA, 0xC2}; std::copy(sourceMac.begin(), sourceMac.end(), std::back_inserter(buffer)); // set ethertype @@ -382,7 +388,7 @@ TEST_F(Test_CapiEthernet, ethernet_controller_send_short_frame) SilKit_Struct_Init(SilKit_EthernetFrame, ef); ef.raw = {buffer.data(), buffer.size()}; - const auto testUserContext = reinterpret_cast(0x12345); + const auto testUserContext = reinterpret_cast(0x12345); // create the expected Ethernet frame std::vector expectedFrameRaw(ef.raw.data, ef.raw.data + ef.raw.size); @@ -393,8 +399,9 @@ TEST_F(Test_CapiEthernet, ethernet_controller_send_short_frame) // in the implementation. EXPECT_CALL(mockController, SendFrame(EthFrameMatcher(expectedFrame), testUserContext)).Times(testing::Exactly(1)); - const auto returnCode = SilKit_EthernetController_SendFrame((SilKit_EthernetController*)&mockController, &ef, testUserContext); + const auto returnCode = + SilKit_EthernetController_SendFrame((SilKit_EthernetController*)&mockController, &ef, testUserContext); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); } -} +} // namespace diff --git a/SilKit/source/capi/Test_CapiFlexray.cpp b/SilKit/source/capi/Test_CapiFlexray.cpp old mode 100755 new mode 100644 index f4b55fd55..fcb6483db --- a/SilKit/source/capi/Test_CapiFlexray.cpp +++ b/SilKit/source/capi/Test_CapiFlexray.cpp @@ -25,8 +25,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "gtest/gtest.h" #include "MockParticipant.hpp" -namespace -{ +namespace { using namespace SilKit::Core; using namespace SilKit::Config; using namespace SilKit::Services::Flexray; @@ -77,37 +76,37 @@ class Test_CapiFlexray : public testing::Test struct Callbacks { static void SilKitCALL FrameHandler(void* /*context*/, SilKit_FlexrayController* /*controller*/, - const SilKit_FlexrayFrameEvent* /*message*/) + const SilKit_FlexrayFrameEvent* /*message*/) { } static void SilKitCALL FrameTransmitHandler(void* /*context*/, SilKit_FlexrayController* /*controller*/, - const SilKit_FlexrayFrameTransmitEvent* /*acknowledge*/) + const SilKit_FlexrayFrameTransmitEvent* /*acknowledge*/) { } static void SilKitCALL WakeupHandler(void* /*context*/, SilKit_FlexrayController* /*controller*/, - const SilKit_FlexrayWakeupEvent* /*wakeup*/) + const SilKit_FlexrayWakeupEvent* /*wakeup*/) { } static void SilKitCALL PocStatusHandler(void* /*context*/, SilKit_FlexrayController* /*controller*/, - const SilKit_FlexrayPocStatusEvent* /*status*/) + const SilKit_FlexrayPocStatusEvent* /*status*/) { } static void SilKitCALL SymbolHandler(void* /*context*/, SilKit_FlexrayController* /*controller*/, - const SilKit_FlexraySymbolEvent* /*symbol*/) + const SilKit_FlexraySymbolEvent* /*symbol*/) { } static void SilKitCALL SymbolTransmitHandler(void* /*context*/, SilKit_FlexrayController* /*controller*/, - const SilKit_FlexraySymbolTransmitEvent* /*acknowledge*/) + const SilKit_FlexraySymbolTransmitEvent* /*acknowledge*/) { } static void SilKitCALL CycleStartHandler(void* /*context*/, SilKit_FlexrayController* /*controller*/, - const SilKit_FlexrayCycleStartEvent* /*cycleStart*/) + const SilKit_FlexrayCycleStartEvent* /*cycleStart*/) { } }; @@ -123,8 +122,8 @@ TEST_F(Test_CapiFlexray, make_flexray_controller) { SilKit_ReturnCode returnCode; SilKit_FlexrayController* frController = nullptr; - returnCode = SilKit_FlexrayController_Create(&frController, (SilKit_Participant*)&participant, controllerName.c_str(), - networkName.c_str()); + returnCode = SilKit_FlexrayController_Create(&frController, (SilKit_Participant*)&participant, + controllerName.c_str(), networkName.c_str()); // needs NullConnectionParticipant, which won't link with C-API. So just expect a general failure here. EXPECT_EQ(returnCode, SilKit_ReturnCode_UNSPECIFIEDERROR); EXPECT_EQ(frController, nullptr); @@ -153,7 +152,7 @@ TEST_F(Test_CapiFlexray, fr_controller_function_mapping) EXPECT_CALL(mockController, AddFrameHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_FlexrayController_AddFrameHandler((SilKit_FlexrayController*)&mockController, NULL, - &Callbacks::FrameHandler, &handlerId); + &Callbacks::FrameHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveFrameHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -162,7 +161,7 @@ TEST_F(Test_CapiFlexray, fr_controller_function_mapping) EXPECT_CALL(mockController, AddFrameTransmitHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_FlexrayController_AddFrameTransmitHandler((SilKit_FlexrayController*)&mockController, NULL, - &Callbacks::FrameTransmitHandler, &handlerId); + &Callbacks::FrameTransmitHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveFrameTransmitHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -171,7 +170,7 @@ TEST_F(Test_CapiFlexray, fr_controller_function_mapping) EXPECT_CALL(mockController, AddWakeupHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_FlexrayController_AddWakeupHandler((SilKit_FlexrayController*)&mockController, NULL, - &Callbacks::WakeupHandler, &handlerId); + &Callbacks::WakeupHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveWakeupHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -180,7 +179,7 @@ TEST_F(Test_CapiFlexray, fr_controller_function_mapping) EXPECT_CALL(mockController, AddPocStatusHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_FlexrayController_AddPocStatusHandler((SilKit_FlexrayController*)&mockController, NULL, - &Callbacks::PocStatusHandler, &handlerId); + &Callbacks::PocStatusHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemovePocStatusHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -189,7 +188,7 @@ TEST_F(Test_CapiFlexray, fr_controller_function_mapping) EXPECT_CALL(mockController, AddSymbolHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_FlexrayController_AddSymbolHandler((SilKit_FlexrayController*)&mockController, NULL, - &Callbacks::SymbolHandler, &handlerId); + &Callbacks::SymbolHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveSymbolHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -198,7 +197,7 @@ TEST_F(Test_CapiFlexray, fr_controller_function_mapping) EXPECT_CALL(mockController, AddSymbolTransmitHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_FlexrayController_AddSymbolTransmitHandler((SilKit_FlexrayController*)&mockController, NULL, - &Callbacks::SymbolTransmitHandler, &handlerId); + &Callbacks::SymbolTransmitHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveSymbolTransmitHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -207,7 +206,7 @@ TEST_F(Test_CapiFlexray, fr_controller_function_mapping) EXPECT_CALL(mockController, AddCycleStartHandler(testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_FlexrayController_AddCycleStartHandler((SilKit_FlexrayController*)&mockController, NULL, - &Callbacks::CycleStartHandler, &handlerId); + &Callbacks::CycleStartHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveCycleStartHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -215,32 +214,33 @@ TEST_F(Test_CapiFlexray, fr_controller_function_mapping) EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, Run()).Times(testing::Exactly(1)); - returnCode = SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, SilKit_FlexrayChiCommand_RUN); + returnCode = + SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, SilKit_FlexrayChiCommand_RUN); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, DeferredHalt()).Times(testing::Exactly(1)); - returnCode = - SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, SilKit_FlexrayChiCommand_DEFERRED_HALT); + returnCode = SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, + SilKit_FlexrayChiCommand_DEFERRED_HALT); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, Freeze()).Times(testing::Exactly(1)); - returnCode = - SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, SilKit_FlexrayChiCommand_FREEZE); + returnCode = SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, + SilKit_FlexrayChiCommand_FREEZE); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, AllowColdstart()).Times(testing::Exactly(1)); returnCode = SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, - SilKit_FlexrayChiCommand_ALLOW_COLDSTART); + SilKit_FlexrayChiCommand_ALLOW_COLDSTART); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, AllSlots()).Times(testing::Exactly(1)); - returnCode = - SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, SilKit_FlexrayChiCommand_ALL_SLOTS); + returnCode = SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, + SilKit_FlexrayChiCommand_ALL_SLOTS); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, Wakeup()).Times(testing::Exactly(1)); - returnCode = - SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, SilKit_FlexrayChiCommand_WAKEUP); + returnCode = SilKit_FlexrayController_ExecuteCmd((SilKit_FlexrayController*)&mockController, + SilKit_FlexrayChiCommand_WAKEUP); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); } @@ -327,15 +327,17 @@ TEST_F(Test_CapiFlexray, fr_controller_nullpointer_params) EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_FlexrayController_AddSymbolTransmitHandler(cController, NULL, nullptr, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = - SilKit_FlexrayController_AddSymbolTransmitHandler(cController, NULL, &Callbacks::SymbolTransmitHandler, nullptr); + returnCode = SilKit_FlexrayController_AddSymbolTransmitHandler(cController, NULL, &Callbacks::SymbolTransmitHandler, + nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_FlexrayController_AddCycleStartHandler(nullptr, NULL, &Callbacks::CycleStartHandler, &handlerId); + returnCode = + SilKit_FlexrayController_AddCycleStartHandler(nullptr, NULL, &Callbacks::CycleStartHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_FlexrayController_AddCycleStartHandler(cController, NULL, nullptr, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_FlexrayController_AddCycleStartHandler(cController, NULL, &Callbacks::CycleStartHandler, nullptr); + returnCode = + SilKit_FlexrayController_AddCycleStartHandler(cController, NULL, &Callbacks::CycleStartHandler, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_FlexrayController_RemoveFrameHandler(nullptr, handlerId); diff --git a/SilKit/source/capi/Test_CapiInterfaces.cpp b/SilKit/source/capi/Test_CapiInterfaces.cpp old mode 100755 new mode 100644 index 27deb5312..3e1e11026 --- a/SilKit/source/capi/Test_CapiInterfaces.cpp +++ b/SilKit/source/capi/Test_CapiInterfaces.cpp @@ -32,15 +32,15 @@ namespace { TEST(Test_CapiInterfaces, compile_test_capi_interface_ids) { - constexpr const auto foo = SilKit_CanStateChangeEvent_STRUCT_VERSION; + constexpr const auto foo = SilKit_CanStateChangeEvent_STRUCT_VERSION; static_assert(SK_ID_GET_SERVICE(foo) == SK_ID_SERVICE_Can, "service id extraction"); - static_assert(SK_ID_GET_DATATYPE(foo) == SilKit_CanStateChangeEvent_DATATYPE_ID, "datatype id extraction"); - static_assert(SK_ID_GET_VERSION(foo) == SilKit_CanStateChangeEvent_VERSION, "datatype version extraction"); - ASSERT_TRUE(SK_ID_IS_VALID(foo)); + static_assert(SK_ID_GET_DATATYPE(foo) == SilKit_CanStateChangeEvent_DATATYPE_ID, "datatype id extraction"); + static_assert(SK_ID_GET_VERSION(foo) == SilKit_CanStateChangeEvent_VERSION, "datatype version extraction"); + ASSERT_TRUE(SK_ID_IS_VALID(foo)); } // Generate this table by script, to verify that there are no copy-pastos. -constexpr uint64_t allSilkidIds[]= { +constexpr uint64_t allSilkidIds[] = { SilKit_CanFrame_STRUCT_VERSION, SilKit_CanFrameTransmitEvent_STRUCT_VERSION, SilKit_CanFrameEvent_STRUCT_VERSION, @@ -79,6 +79,29 @@ constexpr uint64_t allSilkidIds[]= { SilKit_RpcCallResultEvent_STRUCT_VERSION, SilKit_ParticipantStatus_STRUCT_VERSION, SilKit_LifecycleConfiguration_STRUCT_VERSION, + SilKit_WorkflowConfiguration_STRUCT_VERSION, + SilKit_ParticipantConnectionInformation_STRUCT_VERSION, + SilKit_Experimental_EventReceivers_STRUCT_VERSION, + SilKit_Experimental_SimulatedNetworkFunctions_STRUCT_VERSION, + SilKit_Experimental_SimulatedCanControllerFunctions_STRUCT_VERSION, + SilKit_Experimental_SimulatedFlexRayControllerFunctions_STRUCT_VERSION, + SilKit_Experimental_SimulatedEthernetControllerFunctions_STRUCT_VERSION, + SilKit_Experimental_SimulatedLinControllerFunctions_STRUCT_VERSION, + SilKit_Experimental_NetSim_CanConfigureBaudrate_STRUCT_VERSION, + SilKit_Experimental_NetSim_CanControllerMode_STRUCT_VERSION, + SilKit_Experimental_NetSim_CanFrameRequest_STRUCT_VERSION, + SilKit_Experimental_NetSim_FlexrayControllerConfig_STRUCT_VERSION, + SilKit_Experimental_NetSim_FlexrayHostCommand_STRUCT_VERSION, + SilKit_Experimental_NetSim_FlexrayTxBufferConfigUpdate_STRUCT_VERSION, + SilKit_Experimental_NetSim_FlexrayTxBufferUpdate_STRUCT_VERSION, + SilKit_Experimental_NetSim_EthernetFrameRequest_STRUCT_VERSION, + SilKit_Experimental_NetSim_EthernetControllerMode_STRUCT_VERSION, + SilKit_Experimental_NetSim_LinFrameRequest_STRUCT_VERSION, + SilKit_Experimental_NetSim_LinFrameHeaderRequest_STRUCT_VERSION, + SilKit_Experimental_NetSim_LinWakeupPulse_STRUCT_VERSION, + SilKit_Experimental_NetSim_LinControllerConfig_STRUCT_VERSION, + SilKit_Experimental_NetSim_LinFrameResponseUpdate_STRUCT_VERSION, + SilKit_Experimental_NetSim_LinControllerStatusUpdate_STRUCT_VERSION, }; constexpr auto allSilkidIdsSize = sizeof(allSilkidIds) / sizeof(uint64_t); @@ -103,4 +126,4 @@ TEST(Test_CapiInterfaces, silkit_struct_init_zeros_whole_structure) EXPECT_EQ(value.userContext, nullptr); } -}//namespace +} //namespace diff --git a/SilKit/source/capi/Test_CapiLin.cpp b/SilKit/source/capi/Test_CapiLin.cpp old mode 100755 new mode 100644 index b188a0a84..18dd2ecbe --- a/SilKit/source/capi/Test_CapiLin.cpp +++ b/SilKit/source/capi/Test_CapiLin.cpp @@ -37,10 +37,12 @@ class MockLinController { public: MOCK_METHOD(void, Init, (LinControllerConfig config), (override)); - MOCK_METHOD(void, InitDynamic,(const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& config), (override)); + MOCK_METHOD(void, InitDynamic, (const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& config), + (override)); MOCK_METHOD(LinControllerStatus, Status, (), (const, noexcept)); MOCK_METHOD(void, SendFrame, (LinFrame frame, LinFrameResponseType responseType)); - MOCK_METHOD(void, SendFrame, (LinFrame frame, LinFrameResponseType responseType, std::chrono::nanoseconds timestamp)); + MOCK_METHOD(void, SendFrame, + (LinFrame frame, LinFrameResponseType responseType, std::chrono::nanoseconds timestamp)); MOCK_METHOD(void, SendFrameHeader, (LinId linId), (override)); MOCK_METHOD(void, SendFrameHeader, (LinId linId, std::chrono::nanoseconds timestamp)); MOCK_METHOD(void, UpdateTxBuffer, (LinFrame frame), (override)); @@ -63,23 +65,35 @@ class MockLinController (SilKit::Experimental::Services::Lin::LinSlaveConfigurationHandler), (override)); MOCK_METHOD(void, RemoveLinSlaveConfigurationHandler, (SilKit::Services::HandlerId), (override)); - MOCK_METHOD(SilKit::Services::HandlerId, AddFrameHeaderHandler, (SilKit::Experimental::Services::Lin::LinFrameHeaderHandler), (override)); + MOCK_METHOD(SilKit::Services::HandlerId, AddFrameHeaderHandler, + (SilKit::Experimental::Services::Lin::LinFrameHeaderHandler), (override)); }; void SilKitCALL CFrameStatusHandler(void* /*context*/, SilKit_LinController* /*controller*/, - const SilKit_LinFrameStatusEvent* /*frameStatusEvent*/) { } + const SilKit_LinFrameStatusEvent* /*frameStatusEvent*/) +{ +} void SilKitCALL CGoToSleepHandler(void* /*context*/, SilKit_LinController* /*controller*/, - const SilKit_LinGoToSleepEvent* /*goToSleepEvent*/) { } + const SilKit_LinGoToSleepEvent* /*goToSleepEvent*/) +{ +} void SilKitCALL CWakeupHandler(void* /*context*/, SilKit_LinController* /*controller*/, - const SilKit_LinWakeupEvent* /*wakeupEvent*/) { } + const SilKit_LinWakeupEvent* /*wakeupEvent*/) +{ +} void SilKitCALL CFrameHeaderHandler(void* /*context*/, SilKit_LinController* /*controller*/, - const SilKit_Experimental_LinFrameHeaderEvent* /*frameHeaderEvent*/) { } + const SilKit_Experimental_LinFrameHeaderEvent* /*frameHeaderEvent*/) +{ +} -void SilKitCALL CLinSlaveConfigurationHandler(void* /*context*/, SilKit_LinController* /*controller*/, - const SilKit_Experimental_LinSlaveConfigurationEvent* /*slaveConfigurationEvent*/) { } +void SilKitCALL +CLinSlaveConfigurationHandler(void* /*context*/, SilKit_LinController* /*controller*/, + const SilKit_Experimental_LinSlaveConfigurationEvent* /*slaveConfigurationEvent*/) +{ +} class Test_CapiLin : public testing::Test { @@ -152,8 +166,7 @@ TEST_F(Test_CapiLin, lin_controller_function_mapping) EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, AddFrameStatusHandler(testing::_)).Times(testing::Exactly(1)); - returnCode = - SilKit_LinController_AddFrameStatusHandler(cMockController, nullptr, &CFrameStatusHandler, &handlerId); + returnCode = SilKit_LinController_AddFrameStatusHandler(cMockController, nullptr, &CFrameStatusHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveFrameStatusHandler(static_cast(0))).Times(testing::Exactly(1)); @@ -177,19 +190,24 @@ TEST_F(Test_CapiLin, lin_controller_function_mapping) EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, AddLinSlaveConfigurationHandler(testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler(cMockController, nullptr, &CLinSlaveConfigurationHandler, &handlerId); + returnCode = SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler( + cMockController, nullptr, &CLinSlaveConfigurationHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_CALL(mockController, RemoveLinSlaveConfigurationHandler(static_cast(0))).Times(testing::Exactly(1)); - returnCode = SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler((SilKit_LinController*)&mockController, 0); + EXPECT_CALL(mockController, RemoveLinSlaveConfigurationHandler(static_cast(0))) + .Times(testing::Exactly(1)); + returnCode = + SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler((SilKit_LinController*)&mockController, 0); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, AddFrameHeaderHandler(testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler((SilKit_LinController*)&mockController, nullptr, &CFrameHeaderHandler, &handlerId); + returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler((SilKit_LinController*)&mockController, + nullptr, &CFrameHeaderHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveFrameHeaderHandler(static_cast(0))).Times(testing::Exactly(1)); - returnCode = SilKit_Experimental_LinController_RemoveFrameHeaderHandler((SilKit_LinController*)&mockController, handlerId); + returnCode = + SilKit_Experimental_LinController_RemoveFrameHeaderHandler((SilKit_LinController*)&mockController, handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, InitDynamic(testing::_)).Times(testing::Exactly(1)); @@ -201,11 +219,13 @@ TEST_F(Test_CapiLin, lin_controller_function_mapping) EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, AddFrameHeaderHandler(testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler((SilKit_LinController*)&mockController, nullptr, &CFrameHeaderHandler, &handlerId); + returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler((SilKit_LinController*)&mockController, + nullptr, &CFrameHeaderHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); EXPECT_CALL(mockController, RemoveFrameHeaderHandler(static_cast(0))).Times(testing::Exactly(1)); - returnCode = SilKit_Experimental_LinController_RemoveFrameHeaderHandler((SilKit_LinController*)&mockController, handlerId); + returnCode = + SilKit_Experimental_LinController_RemoveFrameHeaderHandler((SilKit_LinController*)&mockController, handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); } @@ -280,8 +300,7 @@ TEST_F(Test_CapiLin, lin_controller_nullpointer_params) EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_LinController_AddFrameStatusHandler(cMockController, nullptr, nullptr, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = - SilKit_LinController_AddFrameStatusHandler(cMockController, nullptr, &CFrameStatusHandler, nullptr); + returnCode = SilKit_LinController_AddFrameStatusHandler(cMockController, nullptr, &CFrameStatusHandler, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_LinController_AddGoToSleepHandler(nullptr, nullptr, &CGoToSleepHandler, &handlerId); @@ -298,11 +317,14 @@ TEST_F(Test_CapiLin, lin_controller_nullpointer_params) returnCode = SilKit_LinController_AddWakeupHandler(cMockController, nullptr, &CWakeupHandler, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler(nullptr, nullptr, &CLinSlaveConfigurationHandler, &handlerId); + returnCode = SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler( + nullptr, nullptr, &CLinSlaveConfigurationHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler(cMockController, nullptr, nullptr, &handlerId); + returnCode = SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler(cMockController, nullptr, nullptr, + &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler(cMockController, nullptr, &CLinSlaveConfigurationHandler, nullptr); + returnCode = SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler( + cMockController, nullptr, &CLinSlaveConfigurationHandler, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_Experimental_LinController_InitDynamic(nullptr, nullptr); @@ -315,15 +337,17 @@ TEST_F(Test_CapiLin, lin_controller_nullpointer_params) returnCode = SilKit_Experimental_LinController_SendDynamicResponse(cMockController, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler(nullptr, nullptr, &CFrameHeaderHandler, &handlerId); + returnCode = + SilKit_Experimental_LinController_AddFrameHeaderHandler(nullptr, nullptr, &CFrameHeaderHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler(cMockController, nullptr, nullptr, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler(cMockController, nullptr, &CFrameHeaderHandler, nullptr); + returnCode = SilKit_Experimental_LinController_AddFrameHeaderHandler(cMockController, nullptr, &CFrameHeaderHandler, + nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_Experimental_LinController_RemoveFrameHeaderHandler(nullptr, static_cast(0)); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); } -} +} // namespace diff --git a/SilKit/source/capi/Test_CapiLogger.cpp b/SilKit/source/capi/Test_CapiLogger.cpp index 33f0d0bcf..ee04cfc5a 100644 --- a/SilKit/source/capi/Test_CapiLogger.cpp +++ b/SilKit/source/capi/Test_CapiLogger.cpp @@ -24,86 +24,84 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "silkit/services/logging/all.hpp" namespace { - using namespace SilKit::Services::Logging; - - class MockLogger : public SilKit::Services::Logging::ILogger - { - public: - MOCK_METHOD2(Log, void(Level, const std::string&)); - MOCK_METHOD1(Trace, void(const std::string&)); - MOCK_METHOD1(Debug, void(const std::string&)); - MOCK_METHOD1(Info, void(const std::string&)); - MOCK_METHOD1(Warn, void(const std::string&)); - MOCK_METHOD1(Error, void(const std::string&)); - MOCK_METHOD1(Critical, void(const std::string&)); - - MOCK_CONST_METHOD0(GetLogLevel, Level()); - }; - - class Test_CapiLogger : public testing::Test - { - public: - MockLogger mockLogger; - Test_CapiLogger() - { - } - }; - - TEST_F(Test_CapiLogger, logger_function_mapping) - { - SilKit_ReturnCode returnCode; - - EXPECT_CALL(mockLogger, Log(Level::Off, "Test message")).Times(testing::Exactly(1)); - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Off, "Test message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } - - TEST_F(Test_CapiLogger, logger_nullpointer_params) - { - SilKit_ReturnCode returnCode; - - returnCode = SilKit_Logger_Log(nullptr, SilKit_LoggingLevel_Off, "Test message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Off, nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - } - - TEST_F(Test_CapiLogger, logger_enum_mappings) - { - SilKit_ReturnCode returnCode; - - EXPECT_CALL(mockLogger, Log(Level::Off, "Test message")).Times(testing::Exactly(1)); - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Off, "Test message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockLogger, Log(Level::Trace, "Trace message")).Times(testing::Exactly(1)); - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Trace, "Trace message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockLogger, Log(Level::Debug, "Debug message")).Times(testing::Exactly(1)); - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Debug, "Debug message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockLogger, Log(Level::Info, "Info message")).Times(testing::Exactly(1)); - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Info, "Info message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockLogger, Log(Level::Warn, "Warn message")).Times(testing::Exactly(1)); - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Warn, "Warn message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockLogger, Log(Level::Error, "Error message")).Times(testing::Exactly(1)); - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Error, "Error message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockLogger, Log(Level::Critical, "Critical message")).Times(testing::Exactly(1)); - returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Critical, "Critical message"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - EXPECT_CALL(mockLogger, GetLogLevel()).Times(testing::Exactly(1)); - SilKit_LoggingLevel logLevel; - returnCode = SilKit_Logger_GetLogLevel((SilKit_Logger*)&mockLogger, &logLevel); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } +using namespace SilKit::Services::Logging; + +class MockLogger : public SilKit::Services::Logging::ILogger +{ +public: + MOCK_METHOD2(Log, void(Level, const std::string&)); + MOCK_METHOD1(Trace, void(const std::string&)); + MOCK_METHOD1(Debug, void(const std::string&)); + MOCK_METHOD1(Info, void(const std::string&)); + MOCK_METHOD1(Warn, void(const std::string&)); + MOCK_METHOD1(Error, void(const std::string&)); + MOCK_METHOD1(Critical, void(const std::string&)); + + MOCK_CONST_METHOD0(GetLogLevel, Level()); +}; + +class Test_CapiLogger : public testing::Test +{ +public: + MockLogger mockLogger; + Test_CapiLogger() {} +}; + +TEST_F(Test_CapiLogger, logger_function_mapping) +{ + SilKit_ReturnCode returnCode; + + EXPECT_CALL(mockLogger, Log(Level::Off, "Test message")).Times(testing::Exactly(1)); + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Off, "Test message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); } + +TEST_F(Test_CapiLogger, logger_nullpointer_params) +{ + SilKit_ReturnCode returnCode; + + returnCode = SilKit_Logger_Log(nullptr, SilKit_LoggingLevel_Off, "Test message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Off, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); +} + +TEST_F(Test_CapiLogger, logger_enum_mappings) +{ + SilKit_ReturnCode returnCode; + + EXPECT_CALL(mockLogger, Log(Level::Off, "Test message")).Times(testing::Exactly(1)); + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Off, "Test message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockLogger, Log(Level::Trace, "Trace message")).Times(testing::Exactly(1)); + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Trace, "Trace message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockLogger, Log(Level::Debug, "Debug message")).Times(testing::Exactly(1)); + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Debug, "Debug message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockLogger, Log(Level::Info, "Info message")).Times(testing::Exactly(1)); + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Info, "Info message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockLogger, Log(Level::Warn, "Warn message")).Times(testing::Exactly(1)); + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Warn, "Warn message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockLogger, Log(Level::Error, "Error message")).Times(testing::Exactly(1)); + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Error, "Error message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockLogger, Log(Level::Critical, "Critical message")).Times(testing::Exactly(1)); + returnCode = SilKit_Logger_Log((SilKit_Logger*)&mockLogger, SilKit_LoggingLevel_Critical, "Critical message"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + EXPECT_CALL(mockLogger, GetLogLevel()).Times(testing::Exactly(1)); + SilKit_LoggingLevel logLevel; + returnCode = SilKit_Logger_GetLogLevel((SilKit_Logger*)&mockLogger, &logLevel); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); +} +} // namespace diff --git a/SilKit/source/capi/Test_CapiNetSim.cpp b/SilKit/source/capi/Test_CapiNetSim.cpp new file mode 100644 index 000000000..205296bdd --- /dev/null +++ b/SilKit/source/capi/Test_CapiNetSim.cpp @@ -0,0 +1,285 @@ +/* Copyright (c) 2022 Vector Informatik GmbH + +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. */ + +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "silkit/capi/SilKit.h" +#include "silkit/experimental/netsim/all.hpp" +#include "MockParticipant.hpp" + +namespace { +using namespace SilKit::Experimental::NetworkSimulation; + +class MockParticipant : public SilKit::Core::Tests::DummyParticipant +{ +public: + MOCK_METHOD(INetworkSimulator*, CreateNetworkSimulator, (), (override)); +}; + +class DummyNetworkSimulator : public SilKit::Experimental::NetworkSimulation::INetworkSimulator +{ +public: + MOCK_METHOD(void, SimulateNetwork, + (const std::string& networkName, SimulatedNetworkType networkType, + std::unique_ptr simulatedNetwork), + (override)); + MOCK_METHOD(void, Start, (), (override)); +}; + +class MockSimulatedNetwork : public SilKit::Experimental::NetworkSimulation::ISimulatedNetwork +{ +public: + MOCK_METHOD(ISimulatedController*, ProvideSimulatedController, (ControllerDescriptor controllerDescriptor), + (override)); + MOCK_METHOD(void, SimulatedControllerRemoved, (ControllerDescriptor controllerDescriptor), (override)); + MOCK_METHOD(void, SetEventProducer, (std::unique_ptr eventProducer), (override)); +}; + +class MockCanEventProducer : public SilKit::Experimental::NetworkSimulation::Can::ICanEventProducer +{ +public: + MOCK_METHOD(void, Produce, + (const SilKit::Services::Can::CanFrameEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Can::CanFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Can::CanStateChangeEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Can::CanErrorStateChangeEvent& msg, + const SilKit::Util::Span& receivers), + (override)); +}; + +class MockEthernetEventProducer : public SilKit::Experimental::NetworkSimulation::Ethernet::IEthernetEventProducer +{ +public: + MOCK_METHOD(void, Produce, + (const SilKit::Services::Ethernet::EthernetFrameEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Ethernet::EthernetStateChangeEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& msg, + const SilKit::Util::Span& receivers), + (override)); +}; + +class MockLinEventProducer : public SilKit::Experimental::NetworkSimulation::Lin::ILinEventProducer +{ +public: + MOCK_METHOD(void, Produce, + (const SilKit::Services::Lin::LinFrameStatusEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Lin::LinSendFrameHeaderRequest& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Lin::LinWakeupEvent& msg, + const SilKit::Util::Span& receivers), + (override)); +}; + +class MockFlexRayEventProducer : public SilKit::Experimental::NetworkSimulation::Flexray::IFlexRayEventProducer +{ +public: + MOCK_METHOD(void, Produce, + (const SilKit::Services::Flexray::FlexrayFrameEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Flexray::FlexrayFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Flexray::FlexraySymbolEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Flexray::FlexraySymbolTransmitEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Flexray::FlexrayCycleStartEvent& msg, + const SilKit::Util::Span& receivers), + (override)); + MOCK_METHOD(void, Produce, + (const SilKit::Services::Flexray::FlexrayPocStatusEvent& msg, + const SilKit::Util::Span& receivers), + (override)); +}; + +class Test_CapiNetsim : public testing::Test +{ +public: + Test_CapiNetsim() + { + mockSimulatedNetwork = std::make_unique(); + } + +protected: + MockParticipant mockParticipant; + DummyNetworkSimulator mockNetworkSimulator; + std::unique_ptr mockSimulatedNetwork; + + MockCanEventProducer mockCanEventProducer; + MockEthernetEventProducer mockEthernetEventProducer; + MockLinEventProducer mockLinEventProducer; + MockFlexRayEventProducer mockFlexRayEventProducer; +}; + +TEST_F(Test_CapiNetsim, netsim_nullpointer_params) +{ + SilKit_ReturnCode returnCode; + auto cMockParticipant = (SilKit_Participant*)&mockParticipant; + auto cMockNetworkSimulator = (SilKit_Experimental_NetworkSimulator*)&mockNetworkSimulator; + + std::string networkName = "networkName"; + SilKit_Experimental_SimulatedNetworkType networkType = SilKit_NetworkType_CAN; + auto cMockSimulatedNetwork = (void*)(mockSimulatedNetwork.get()); + SilKit_Experimental_SimulatedNetworkFunctions cSimulatedNetworkFunctions; + SilKit_Struct_Init(SilKit_Experimental_SimulatedNetworkFunctions, cSimulatedNetworkFunctions); + + SilKit_Experimental_EventReceivers receivers; + SilKit_Struct_Init(SilKit_Experimental_EventReceivers, receivers); + auto cMockCanEventProducer = (SilKit_Experimental_CanEventProducer*)&mockCanEventProducer; + auto cMockEthernetEventProducer = (SilKit_Experimental_EthernetEventProducer*)&mockEthernetEventProducer; + auto cMockLinEventProducer = (SilKit_Experimental_LinEventProducer*)&mockLinEventProducer; + auto cMockFlexRayEventProducer = (SilKit_Experimental_FlexRayEventProducer*)&mockFlexRayEventProducer; + + SilKit_CanFrameEvent canFrameEvent; + SilKit_Struct_Init(SilKit_CanFrameEvent, canFrameEvent); + SilKit_EthernetFrameEvent ethFrameEvent; + SilKit_Struct_Init(SilKit_EthernetFrameEvent, ethFrameEvent); + SilKit_LinFrameStatusEvent linFrameStatusEvent; + SilKit_Struct_Init(SilKit_LinFrameStatusEvent, linFrameStatusEvent); + SilKit_FlexrayFrameEvent flexrayFrameEvent; + SilKit_Struct_Init(SilKit_FlexrayFrameEvent, flexrayFrameEvent); + + // SilKit_Experimental_NetworkSimulator_Create + returnCode = SilKit_Experimental_NetworkSimulator_Create(&cMockNetworkSimulator, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_NetworkSimulator_Create(nullptr, cMockParticipant); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // SilKit_Experimental_NetworkSimulator_SimulateNetwork + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork( + nullptr, networkName.c_str(), networkType, cMockSimulatedNetwork, &cSimulatedNetworkFunctions); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork( + cMockNetworkSimulator, nullptr, networkType, cMockSimulatedNetwork, &cSimulatedNetworkFunctions); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork( + cMockNetworkSimulator, networkName.c_str(), networkType, nullptr, &cSimulatedNetworkFunctions); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork(cMockNetworkSimulator, networkName.c_str(), + networkType, cMockSimulatedNetwork, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // SilKit_Experimental_NetworkSimulator_Start + returnCode = SilKit_Experimental_NetworkSimulator_Start(nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // SilKit_Experimental_CanEventProducer_Produce + returnCode = SilKit_Experimental_CanEventProducer_Produce(nullptr, &canFrameEvent.structHeader, &receivers); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_CanEventProducer_Produce(cMockCanEventProducer, nullptr, &receivers); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = + SilKit_Experimental_CanEventProducer_Produce(cMockCanEventProducer, &canFrameEvent.structHeader, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // SilKit_Experimental_EthernetEventProducer_Produce + returnCode = SilKit_Experimental_EthernetEventProducer_Produce(nullptr, ðFrameEvent.structHeader, &receivers); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_EthernetEventProducer_Produce(cMockEthernetEventProducer, nullptr, &receivers); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_EthernetEventProducer_Produce(cMockEthernetEventProducer, + ðFrameEvent.structHeader, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // SilKit_Experimental_LinEventProducer_Produce + returnCode = SilKit_Experimental_LinEventProducer_Produce(nullptr, &linFrameStatusEvent.structHeader, &receivers); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_LinEventProducer_Produce(cMockLinEventProducer, nullptr, &receivers); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = + SilKit_Experimental_LinEventProducer_Produce(cMockLinEventProducer, &linFrameStatusEvent.structHeader, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // SilKit_Experimental_FlexRayEventProducer_Produce + returnCode = SilKit_Experimental_FlexRayEventProducer_Produce(nullptr, &flexrayFrameEvent.structHeader, &receivers); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_FlexRayEventProducer_Produce(cMockFlexRayEventProducer, nullptr, &receivers); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Experimental_FlexRayEventProducer_Produce(cMockFlexRayEventProducer, + &flexrayFrameEvent.structHeader, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); +} + +TEST_F(Test_CapiNetsim, netsim_function_mapping) +{ + SilKit_ReturnCode returnCode; + auto cMockParticipant = (SilKit_Participant*)&mockParticipant; + auto cMockNetworkSimulator = (SilKit_Experimental_NetworkSimulator*)&mockNetworkSimulator; + auto cMockSimulatedNetwork = (SilKit_Experimental_SimulatedNetwork*)(mockSimulatedNetwork.get()); + + SilKit_Experimental_SimulatedNetworkFunctions cSimulatedNetworkFunctions; + SilKit_Struct_Init(SilKit_Experimental_SimulatedNetworkFunctions, cSimulatedNetworkFunctions); + + std::string networkName = "networkName"; + SilKit_Experimental_SimulatedNetworkType cNetworkType = SilKit_NetworkType_CAN; + SimulatedNetworkType networkType = static_cast(cNetworkType); + + // SilKit_Experimental_NetworkSimulator_Create + EXPECT_CALL(mockParticipant, CreateNetworkSimulator()).Times(testing::Exactly(1)); + returnCode = SilKit_Experimental_NetworkSimulator_Create(&cMockNetworkSimulator, cMockParticipant); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + // SilKit_Experimental_NetworkSimulator_SimulateNetwork -> SimulateNetwork + cMockNetworkSimulator = + (SilKit_Experimental_NetworkSimulator*)&mockNetworkSimulator; // Recreate because the mocked SilKit_Experimental_NetworkSimulator_Create invalidated the pointer + EXPECT_CALL(mockNetworkSimulator, SimulateNetwork(networkName, networkType, testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_Experimental_NetworkSimulator_SimulateNetwork( + cMockNetworkSimulator, networkName.c_str(), cNetworkType, cMockSimulatedNetwork, &cSimulatedNetworkFunctions); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + // SilKit_Experimental_NetworkSimulator_Start -> Start + EXPECT_CALL(mockNetworkSimulator, Start()).Times(testing::Exactly(1)); + returnCode = SilKit_Experimental_NetworkSimulator_Start(cMockNetworkSimulator); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); +} + +} // namespace diff --git a/SilKit/source/capi/Test_CapiParticipantStateHandling.cpp b/SilKit/source/capi/Test_CapiParticipantStateHandling.cpp old mode 100755 new mode 100644 index 12dd29b16..6208ad98a --- a/SilKit/source/capi/Test_CapiParticipantStateHandling.cpp +++ b/SilKit/source/capi/Test_CapiParticipantStateHandling.cpp @@ -20,7 +20,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef WIN32 -# define _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS #endif #include "gtest/gtest.h" @@ -74,9 +74,7 @@ class Test_CapiParticipantStateHandling : public testing::Test const char* names[2] = {"Participant1", "Participant2"}; workflowConfiguration = std::make_unique(); - [this] { - ASSERT_NE(workflowConfiguration, nullptr); - }(); + [this] { ASSERT_NE(workflowConfiguration, nullptr); }(); SilKit_Struct_Init(SilKit_WorkflowConfiguration, *workflowConfiguration); Create_StringList(&workflowConfiguration->requiredParticipantNames, names, numNames); @@ -98,10 +96,17 @@ void SilKitCALL StartingCallback(void* /*context*/, SilKit_LifecycleService* /*l void SilKitCALL StopCallback(void* /*context*/, SilKit_LifecycleService* /*lifecycleService*/) {} void SilKitCALL ShutdownCallback(void* /*context*/, SilKit_LifecycleService* /*lifecycleService*/) {} void SilKitCALL AbortCallback(void* /*context*/, SilKit_LifecycleService* /*lifecycleService*/, - SilKit_ParticipantState /*lastParticipantState*/) {} -void SilKitCALL SystemStateHandler(void* /*context*/, SilKit_SystemMonitor* /*systemMonitor*/, SilKit_SystemState /*state*/) {} + SilKit_ParticipantState /*lastParticipantState*/) +{ +} +void SilKitCALL SystemStateHandler(void* /*context*/, SilKit_SystemMonitor* /*systemMonitor*/, + SilKit_SystemState /*state*/) +{ +} void SilKitCALL ParticipantStatusHandler(void* /*context*/, SilKit_SystemMonitor* /*systemMonitor*/, - const char* /*participantName*/, SilKit_ParticipantStatus* /*status*/) {} + const char* /*participantName*/, SilKit_ParticipantStatus* /*status*/) +{ +} /* * check whether the api rejects bad parameters @@ -114,14 +119,14 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_nullpointer returnCode = SilKit_LifecycleService_SetCommunicationReadyHandler(nullptr, NULL, &CommunicationReadyCallback); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_LifecycleService_SetCommunicationReadyHandler( - (SilKit_LifecycleService*)(lifecycleService), NULL, nullptr); + returnCode = SilKit_LifecycleService_SetCommunicationReadyHandler((SilKit_LifecycleService*)(lifecycleService), + NULL, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_LifecycleService_SetStartingHandler(nullptr, NULL, &StartingCallback); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_LifecycleService_SetStartingHandler( - (SilKit_LifecycleService*)(lifecycleService), NULL, nullptr); + returnCode = + SilKit_LifecycleService_SetStartingHandler((SilKit_LifecycleService*)(lifecycleService), NULL, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_LifecycleService_SetStopHandler(nullptr, NULL, &StopCallback); @@ -131,14 +136,13 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_nullpointer returnCode = SilKit_LifecycleService_SetShutdownHandler(nullptr, NULL, &ShutdownCallback); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_LifecycleService_SetShutdownHandler( - (SilKit_LifecycleService*)(lifecycleService), NULL, nullptr); + returnCode = + SilKit_LifecycleService_SetShutdownHandler((SilKit_LifecycleService*)(lifecycleService), NULL, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_LifecycleService_SetAbortHandler(nullptr, NULL, &AbortCallback); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_LifecycleService_SetAbortHandler( - (SilKit_LifecycleService*)(lifecycleService), NULL, nullptr); + returnCode = SilKit_LifecycleService_SetAbortHandler((SilKit_LifecycleService*)(lifecycleService), NULL, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); // StartLifecycle @@ -150,15 +154,14 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_nullpointer returnCode = SilKit_LifecycleService_WaitForLifecycleToComplete(nullptr, &outParticipantState); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_LifecycleService_WaitForLifecycleToComplete( - (SilKit_LifecycleService*)(lifecycleService), nullptr); + returnCode = + SilKit_LifecycleService_WaitForLifecycleToComplete((SilKit_LifecycleService*)(lifecycleService), nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_LifecycleService_Pause(nullptr, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = - SilKit_LifecycleService_Pause((SilKit_LifecycleService*)(lifecycleService), nullptr); + returnCode = SilKit_LifecycleService_Pause((SilKit_LifecycleService*)(lifecycleService), nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_LifecycleService_Pause(nullptr, "test"); @@ -167,8 +170,7 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_nullpointer returnCode = SilKit_LifecycleService_Stop(nullptr, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = - SilKit_LifecycleService_Stop((SilKit_LifecycleService*)(lifecycleService), nullptr); + returnCode = SilKit_LifecycleService_Stop((SilKit_LifecycleService*)(lifecycleService), nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_LifecycleService_Stop(nullptr, "test"); @@ -231,7 +233,8 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_nullpointer returnCode = SilKit_SystemMonitor_AddParticipantStatusHandler(nullptr, nullptr, nullptr, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_SystemMonitor_AddParticipantStatusHandler(nullptr, nullptr, &ParticipantStatusHandler, &handlerId); + returnCode = + SilKit_SystemMonitor_AddParticipantStatusHandler(nullptr, nullptr, &ParticipantStatusHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_SystemMonitor_AddParticipantStatusHandler(systemMonitor, nullptr, nullptr, &handlerId); @@ -243,7 +246,6 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_nullpointer returnCode = SilKit_SystemMonitor_RemoveParticipantStatusHandler(nullptr, (SilKit_HandlerId)0); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - } TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_no_time_sync_function_mapping) @@ -277,8 +279,7 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_no_time_syn .Times(testing::Exactly(1)) .WillOnce(Return(ByMove(state.get_future()))); - returnCode = - SilKit_LifecycleService_StartLifecycle((SilKit_LifecycleService*)(lifecycleService)); + returnCode = SilKit_LifecycleService_StartLifecycle((SilKit_LifecycleService*)(lifecycleService)); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); returnCode = SilKit_LifecycleService_WaitForLifecycleToComplete((SilKit_LifecycleService*)(lifecycleService), &outParticipantState); @@ -291,7 +292,7 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_no_time_syn SilKit::Services::Orchestration::ParticipantStatus cppParticipantStatus{}; ON_CALL(mockParticipant.mockSystemMonitor, ParticipantStatus(testing::_)) - .WillByDefault(testing::ReturnRef(cppParticipantStatus)); + .WillByDefault(testing::ReturnRef(cppParticipantStatus)); SilKit_ParticipantStatus participantStatus; SilKit_Struct_Init(SilKit_ParticipantStatus, participantStatus); @@ -311,35 +312,24 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_function_ma SilKit::Services::Orchestration::ParticipantStatus mockParticipantStatus{}; testing::DefaultValue::Set(mockParticipantStatus); - EXPECT_CALL(mockParticipant.mockLifecycleService, - SetCommunicationReadyHandler(testing::_) - ).Times(testing::Exactly(1)); + EXPECT_CALL(mockParticipant.mockLifecycleService, SetCommunicationReadyHandler(testing::_)) + .Times(testing::Exactly(1)); - returnCode = SilKit_LifecycleService_SetCommunicationReadyHandler( - (SilKit_LifecycleService*)(lifecycleService), - nullptr, - &CommunicationReadyCallback); + returnCode = SilKit_LifecycleService_SetCommunicationReadyHandler((SilKit_LifecycleService*)(lifecycleService), + nullptr, &CommunicationReadyCallback); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_CALL(mockParticipant.mockLifecycleService, - SetStopHandler(testing::_) - ).Times(testing::Exactly(1)); + EXPECT_CALL(mockParticipant.mockLifecycleService, SetStopHandler(testing::_)).Times(testing::Exactly(1)); - returnCode = SilKit_LifecycleService_SetStopHandler( - (SilKit_LifecycleService*)(lifecycleService), - nullptr, - &StopCallback); + returnCode = + SilKit_LifecycleService_SetStopHandler((SilKit_LifecycleService*)(lifecycleService), nullptr, &StopCallback); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_CALL(mockParticipant.mockLifecycleService, - SetShutdownHandler(testing::_) - ).Times(testing::Exactly(1)); - returnCode = SilKit_LifecycleService_SetShutdownHandler( - (SilKit_LifecycleService*)(lifecycleService), - nullptr, - &ShutdownCallback); + EXPECT_CALL(mockParticipant.mockLifecycleService, SetShutdownHandler(testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_LifecycleService_SetShutdownHandler((SilKit_LifecycleService*)(lifecycleService), nullptr, + &ShutdownCallback); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); @@ -353,18 +343,17 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_function_ma state.set_value(SilKit::Services::Orchestration::ParticipantState::Shutdown); SilKit_LifecycleConfiguration startConfig; - SilKit_Struct_Init(SilKit_LifecycleConfiguration,startConfig); + SilKit_Struct_Init(SilKit_LifecycleConfiguration, startConfig); - EXPECT_CALL(mockParticipant.mockLifecycleService, - StartLifecycle() - ).Times(testing::Exactly(1)) + EXPECT_CALL(mockParticipant.mockLifecycleService, StartLifecycle()) + .Times(testing::Exactly(1)) .WillOnce(Return(ByMove(state.get_future()))); returnCode = SilKit_LifecycleService_StartLifecycle((SilKit_LifecycleService*)(lifecycleService)); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - returnCode = SilKit_LifecycleService_WaitForLifecycleToComplete( - (SilKit_LifecycleService*)(lifecycleService), &outParticipantState); + returnCode = SilKit_LifecycleService_WaitForLifecycleToComplete((SilKit_LifecycleService*)(lifecycleService), + &outParticipantState); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); state = std::promise{}; // reset state @@ -377,8 +366,8 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_function_ma returnCode = SilKit_LifecycleService_StartLifecycle((SilKit_LifecycleService*)(lifecycleService)); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - returnCode = SilKit_LifecycleService_WaitForLifecycleToComplete( - (SilKit_LifecycleService*)(lifecycleService), &outParticipantState); + returnCode = SilKit_LifecycleService_WaitForLifecycleToComplete((SilKit_LifecycleService*)(lifecycleService), + &outParticipantState); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); SilKit_SystemState systemState; @@ -392,23 +381,15 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_function_ma returnCode = SilKit_SystemMonitor_GetParticipantStatus(&participantStatus, systemMonitor, "participant"); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_CALL(mockParticipant.mockLifecycleService, - Pause(testing::_) - ).Times(testing::Exactly(1)); - returnCode = - SilKit_LifecycleService_Pause((SilKit_LifecycleService*)(lifecycleService), "dummy"); + EXPECT_CALL(mockParticipant.mockLifecycleService, Pause(testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_LifecycleService_Pause((SilKit_LifecycleService*)(lifecycleService), "dummy"); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_CALL(mockParticipant.mockLifecycleService, - Stop(testing::_) - ).Times(testing::Exactly(1)); - returnCode = - SilKit_LifecycleService_Stop((SilKit_LifecycleService*)(lifecycleService), "dummy"); + EXPECT_CALL(mockParticipant.mockLifecycleService, Stop(testing::_)).Times(testing::Exactly(1)); + returnCode = SilKit_LifecycleService_Stop((SilKit_LifecycleService*)(lifecycleService), "dummy"); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_CALL(mockParticipant.mockLifecycleService, - Continue() - ).Times(testing::Exactly(1)); + EXPECT_CALL(mockParticipant.mockLifecycleService, Continue()).Times(testing::Exactly(1)); returnCode = SilKit_LifecycleService_Continue((SilKit_LifecycleService*)(lifecycleService)); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); @@ -427,10 +408,10 @@ TEST_F(Test_CapiParticipantStateHandling, participant_state_handling_function_ma SilKit_SystemMonitor_AddParticipantStatusHandler(systemMonitor, nullptr, &ParticipantStatusHandler, &handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_CALL(mockParticipant.mockSystemMonitor, RemoveParticipantStatusHandler(testing::_)).Times(testing::Exactly(1)); + EXPECT_CALL(mockParticipant.mockSystemMonitor, RemoveParticipantStatusHandler(testing::_)) + .Times(testing::Exactly(1)); returnCode = SilKit_SystemMonitor_RemoveParticipantStatusHandler(systemMonitor, handlerId); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } } // namespace diff --git a/SilKit/source/capi/Test_CapiRpc.cpp b/SilKit/source/capi/Test_CapiRpc.cpp old mode 100755 new mode 100644 index 70c2a6874..a6e5b4a3d --- a/SilKit/source/capi/Test_CapiRpc.cpp +++ b/SilKit/source/capi/Test_CapiRpc.cpp @@ -34,29 +34,39 @@ namespace { using namespace SilKit::Services::Rpc; using SilKit::Core::Tests::DummyParticipant; -MATCHER_P(PayloadMatcher, controlPayload, "") { +MATCHER_P(PayloadMatcher, controlPayload, "") +{ *result_listener << "matches data payloads by their content and length"; - if (arg.size() != controlPayload.size()) { + if (arg.size() != controlPayload.size()) + { return false; } - for (size_t i = 0; i < arg.size(); i++) { - if (arg[i] != controlPayload[i]) { + for (size_t i = 0; i < arg.size(); i++) + { + if (arg[i] != controlPayload[i]) + { return false; } } return true; } -class MockRpcClient : public SilKit::Services::Rpc::IRpcClient { +class MockRpcClient : public SilKit::Services::Rpc::IRpcClient +{ public: MOCK_METHOD(void, Call, (SilKit::Util::Span data, void* userContext), (override)); - MOCK_METHOD(void, CallWithTimeout, (SilKit::Util::Span data, std::chrono::nanoseconds timeout, void* userContext), (override)); + MOCK_METHOD(void, CallWithTimeout, + (SilKit::Util::Span data, std::chrono::nanoseconds timeout, void* userContext), + (override)); MOCK_METHOD1(SetCallResultHandler, void(RpcCallResultHandler handler)); }; -class MockRpcServer : public SilKit::Services::Rpc::IRpcServer{ +class MockRpcServer : public SilKit::Services::Rpc::IRpcServer +{ public: - MOCK_METHOD(void, SubmitResult, (SilKit::Services::Rpc::IRpcCallHandle* callHandle, SilKit::Util::Span resultData), (override)); + MOCK_METHOD(void, SubmitResult, + (SilKit::Services::Rpc::IRpcCallHandle * callHandle, SilKit::Util::Span resultData), + (override)); MOCK_METHOD1(SetCallHandler, void(RpcCallHandler handler)); }; @@ -83,7 +93,7 @@ class Test_CapiRpc : public testing::Test MockParticipant mockParticipant; Test_CapiRpc() { - dummyCallHandle = std::make_unique(SilKit::Util::Uuid{ 1, 1 }); + dummyCallHandle = std::make_unique(SilKit::Util::Uuid{1, 1}); callHandlePtr = dummyCallHandle.get(); callHandle = reinterpret_cast(callHandlePtr); @@ -106,14 +116,12 @@ class Test_CapiRpc : public testing::Test void* dummyContextPtr; const char* mediaType; - }; -void SilKitCALL CallHandler(void* /*context*/, SilKit_RpcServer* /*server*/, const SilKit_RpcCallEvent* /*event*/) -{ -} +void SilKitCALL CallHandler(void* /*context*/, SilKit_RpcServer* /*server*/, const SilKit_RpcCallEvent* /*event*/) {} -void SilKitCALL CallReturnHandler(void* /*context*/, SilKit_RpcClient* /*client*/, const SilKit_RpcCallResultEvent* /*event*/) +void SilKitCALL CallReturnHandler(void* /*context*/, SilKit_RpcClient* /*client*/, + const SilKit_RpcCallResultEvent* /*event*/) { } @@ -133,7 +141,7 @@ TEST_F(Test_CapiRpc, rpc_client_function_mapping) &CallReturnHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - SilKit_ByteVector data = { 0, 0 }; + SilKit_ByteVector data = {0, 0}; EXPECT_CALL(mockRpcClient, Call(testing::_, nullptr)).Times(testing::Exactly(1)); returnCode = SilKit_RpcClient_Call((SilKit_RpcClient*)&mockRpcClient, &data, nullptr); @@ -155,7 +163,7 @@ TEST_F(Test_CapiRpc, rpc_server_function_mapping) { SilKit_ReturnCode returnCode; - + SilKit_RpcSpec rpcSpec; SilKit_Struct_Init(SilKit_RpcSpec, rpcSpec); rpcSpec.functionName = "TopicA"; @@ -164,8 +172,7 @@ TEST_F(Test_CapiRpc, rpc_server_function_mapping) rpcSpec.labelList.labels = 0; SilKit_RpcServer* server; - EXPECT_CALL(mockParticipant, CreateRpcServer("server", testing::_, testing::_)) - .Times(testing::Exactly(1)); + EXPECT_CALL(mockParticipant, CreateRpcServer("server", testing::_, testing::_)).Times(testing::Exactly(1)); returnCode = SilKit_RpcServer_Create(&server, (SilKit_Participant*)&mockParticipant, "server", &rpcSpec, nullptr, &CallHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); @@ -192,15 +199,15 @@ TEST_F(Test_CapiRpc, rpc_client_bad_parameters) dummyContextPtr, &CallReturnHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_RpcClient_Create(&client, nullptr, "client", &rpcSpec, dummyContextPtr, - &CallReturnHandler); + returnCode = SilKit_RpcClient_Create(&client, nullptr, "client", &rpcSpec, dummyContextPtr, &CallReturnHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_RpcClient_Create(&client, (SilKit_Participant*)&mockParticipant, nullptr, &rpcSpec, dummyContextPtr, &CallReturnHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_RpcClient_Create(&client, (SilKit_Participant*)&mockParticipant, "client", nullptr, dummyContextPtr, &CallReturnHandler); + returnCode = SilKit_RpcClient_Create(&client, (SilKit_Participant*)&mockParticipant, "client", nullptr, + dummyContextPtr, &CallReturnHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_RpcClient_Create(&client, (SilKit_Participant*)&mockParticipant, "client", &rpcSpec, @@ -245,18 +252,18 @@ TEST_F(Test_CapiRpc, rpc_server_bad_parameters) dummyContextPtr, &CallHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_RpcServer_Create(&server, nullptr, "server", &rpcSpec, dummyContextPtr, - &CallHandler); + returnCode = SilKit_RpcServer_Create(&server, nullptr, "server", &rpcSpec, dummyContextPtr, &CallHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_RpcServer_Create(&server, (SilKit_Participant*)&mockParticipant, "server", nullptr, dummyContextPtr, &CallHandler); + returnCode = SilKit_RpcServer_Create(&server, (SilKit_Participant*)&mockParticipant, "server", nullptr, + dummyContextPtr, &CallHandler); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_RpcServer_Create(&server, (SilKit_Participant*)&mockParticipant, "server", &rpcSpec, dummyContextPtr, nullptr); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - SilKit_ByteVector data = {0, 0}; + SilKit_ByteVector data = {0, 0}; returnCode = SilKit_RpcServer_SubmitResult(nullptr, callHandle, &data); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); returnCode = SilKit_RpcServer_SubmitResult((SilKit_RpcServer*)&mockRpcServer, nullptr, &data); @@ -273,7 +280,7 @@ TEST_F(Test_CapiRpc, rpc_client_call) uint8_t buffer[64]; int messageCounter = 1; size_t payloadSize = snprintf((char*)buffer, sizeof(buffer), "RPC %i", messageCounter); - SilKit_ByteVector data = { &buffer[0], payloadSize }; + SilKit_ByteVector data = {&buffer[0], payloadSize}; std::vector refData(&(data.data[0]), &(data.data[0]) + data.size); @@ -288,9 +295,9 @@ TEST_F(Test_CapiRpc, rpc_server_submit) { SilKit_ReturnCode returnCode = 0; // create payload - uint8_t buffer[64]; - int messageCounter = 1; - size_t payloadSize = snprintf((char*)buffer, sizeof(buffer), "RPC %i", messageCounter); + uint8_t buffer[64]; + int messageCounter = 1; + size_t payloadSize = snprintf((char*)buffer, sizeof(buffer), "RPC %i", messageCounter); SilKit_ByteVector data = {&buffer[0], payloadSize}; std::vector refData(&(data.data[0]), &(data.data[0]) + data.size); @@ -299,7 +306,8 @@ TEST_F(Test_CapiRpc, rpc_server_submit) EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); } -void SilKitCALL CallHandlerWithStringContext(void* context, SilKit_RpcServer* /*server*/, const SilKit_RpcCallEvent* /*event*/) +void SilKitCALL CallHandlerWithStringContext(void* context, SilKit_RpcServer* /*server*/, + const SilKit_RpcCallEvent* /*event*/) { if (context == nullptr) { @@ -316,16 +324,16 @@ TEST_F(Test_CapiRpc, rpc_server_set_call_handler_wraps_c_handler_and_passes_cont std::string context; EXPECT_CALL(mockRpcServer, SetCallHandler(testing::_)) .WillOnce(testing::Invoke([this, &context](RpcCallHandler handler) { - ASSERT_EQ(context, ""); - handler(&mockRpcServer, RpcCallEvent{}); - ASSERT_EQ(context, "CallHandlerWithStringContext"); - })); + ASSERT_EQ(context, ""); + handler(&mockRpcServer, RpcCallEvent{}); + ASSERT_EQ(context, "CallHandlerWithStringContext"); + })); SilKit_RpcServer_SetCallHandler(cRpcServer, &context, CallHandlerWithStringContext); } void SilKitCALL CallResultHandlerWithStringContext(void* context, SilKit_RpcClient* /*client*/, - const SilKit_RpcCallResultEvent* /*event*/) + const SilKit_RpcCallResultEvent* /*event*/) { if (context == nullptr) { @@ -342,10 +350,10 @@ TEST_F(Test_CapiRpc, rpc_client_set_call_result_handler_wraps_c_handler_and_pass std::string context; EXPECT_CALL(mockRpcClient, SetCallResultHandler(testing::_)) .WillOnce(testing::Invoke([this, &context](RpcCallResultHandler handler) { - ASSERT_EQ(context, ""); - handler(&mockRpcClient, RpcCallResultEvent{}); - ASSERT_EQ(context, "CallResultHandlerWithStringContext"); - })); + ASSERT_EQ(context, ""); + handler(&mockRpcClient, RpcCallResultEvent{}); + ASSERT_EQ(context, "CallResultHandlerWithStringContext"); + })); SilKit_RpcClient_SetCallResultHandler(cRpcClient, &context, CallResultHandlerWithStringContext); } diff --git a/SilKit/source/capi/Test_CapiSilKit.cpp b/SilKit/source/capi/Test_CapiSilKit.cpp index e98c259bd..152768a1f 100644 --- a/SilKit/source/capi/Test_CapiSilKit.cpp +++ b/SilKit/source/capi/Test_CapiSilKit.cpp @@ -65,84 +65,113 @@ const auto SILKIT_MALFORMED_CONFIG_STRING = R"aw( )aw"; - using namespace SilKit::Services::Can; +using namespace SilKit::Services::Can; - using SilKit::Core::Tests::DummyParticipant; +using SilKit::Core::Tests::DummyParticipant; - class Test_CapiSilKit : public testing::Test - { - public: - SilKit::Core::Tests::DummyParticipant mockParticipant; - Test_CapiSilKit() - { - - } - }; - - TEST_F(Test_CapiSilKit, silkit_function_mapping) - { - SilKit_ReturnCode returnCode; - - SilKit_ParticipantConfiguration* participantConfiguration = nullptr; - returnCode = SilKit_ParticipantConfiguration_FromString(&participantConfiguration, SILKIT_CONFIG_STRING); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_NE(participantConfiguration, nullptr); - - SilKit_Participant* participant = nullptr; - returnCode = SilKit_Participant_Create(&participant, participantConfiguration, "Participant1", "42"); - // since there is no SIL Kit Registry, the call should fail - EXPECT_EQ(returnCode, SilKit_ReturnCode_UNSPECIFIEDERROR); - EXPECT_TRUE(participant == nullptr); - - // since there is no SIL Kit Registry with which one could create a Participant, we check against nullptr - returnCode = SilKit_Participant_Destroy(nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - // destory the participant configuration to satisfy ASAN - returnCode = SilKit_ParticipantConfiguration_Destroy(participantConfiguration); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - } - - - TEST_F(Test_CapiSilKit, silkit_bad_params) - { - SilKit_ReturnCode returnCode; - - SilKit_ParticipantConfiguration* participantConfiguration = nullptr; - - returnCode = SilKit_ParticipantConfiguration_FromString(&participantConfiguration, SILKIT_CONFIG_STRING); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - EXPECT_NE(participantConfiguration, nullptr); - - SilKit_Participant* participant = nullptr; - returnCode = SilKit_Participant_Create(nullptr, participantConfiguration, "Participant1", "42"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_Participant_Create(&participant, nullptr, "Participant1", "42"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_Participant_Create(&participant, participantConfiguration, nullptr, "42"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - returnCode = SilKit_Participant_Create(&participant, participantConfiguration, "Participant1", nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - returnCode = - SilKit_Participant_Create(&participant, participantConfiguration, "ParticipantNotExisting", "42"); - EXPECT_EQ(returnCode, SilKit_ReturnCode_UNSPECIFIEDERROR); - - returnCode = SilKit_ParticipantConfiguration_Destroy(participantConfiguration); - EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); - - returnCode = SilKit_ParticipantConfiguration_Destroy(nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - - participantConfiguration = nullptr; +class Test_CapiSilKit : public testing::Test +{ +public: + SilKit::Core::Tests::DummyParticipant mockParticipant; + Test_CapiSilKit() {} +}; - returnCode = SilKit_ParticipantConfiguration_FromString(&participantConfiguration, SILKIT_MALFORMED_CONFIG_STRING); - EXPECT_EQ(returnCode, SilKit_ReturnCode_UNSPECIFIEDERROR); - EXPECT_EQ(participantConfiguration, nullptr); +TEST_F(Test_CapiSilKit, silkit_function_mapping) +{ + SilKit_ReturnCode returnCode; + + SilKit_ParticipantConfiguration* participantConfiguration = nullptr; + returnCode = SilKit_ParticipantConfiguration_FromString(&participantConfiguration, SILKIT_CONFIG_STRING); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + EXPECT_NE(participantConfiguration, nullptr); + + SilKit_ParticipantConfiguration* participantConfigurationFromFile = nullptr; + returnCode = SilKit_ParticipantConfiguration_FromFile(&participantConfigurationFromFile, + "ParticipantConfiguration_FullIncludes.yaml"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + EXPECT_NE(participantConfigurationFromFile, nullptr); + + SilKit_Participant* participant = nullptr; + returnCode = SilKit_Participant_Create(&participant, participantConfiguration, "Participant1", "42"); + // since there is no SIL Kit Registry, the call should fail + EXPECT_EQ(returnCode, SilKit_ReturnCode_UNSPECIFIEDERROR); + EXPECT_TRUE(participant == nullptr); + + // since there is no SIL Kit Registry with which one could create a Participant, we check against nullptr + returnCode = SilKit_Participant_Destroy(nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // destory the participant configuration to satisfy ASAN + returnCode = SilKit_ParticipantConfiguration_Destroy(participantConfiguration); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + returnCode = SilKit_ParticipantConfiguration_Destroy(participantConfigurationFromFile); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); +} - // since there is no SIL Kit Registry with which one could create a Participant, we check against nullptr - returnCode = SilKit_Participant_Destroy(nullptr); - EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); - } +TEST_F(Test_CapiSilKit, silkit_bad_params) +{ + SilKit_ReturnCode returnCode; + + SilKit_ParticipantConfiguration* participantConfiguration = nullptr; + + returnCode = SilKit_ParticipantConfiguration_FromString(&participantConfiguration, SILKIT_CONFIG_STRING); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + EXPECT_NE(participantConfiguration, nullptr); + + SilKit_ParticipantConfiguration* participantConfigurationFromAFile = nullptr; + returnCode = SilKit_ParticipantConfiguration_FromFile(&participantConfigurationFromAFile, + "ParticipantConfiguration_FullIncludes.yaml"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + EXPECT_NE(participantConfigurationFromAFile, nullptr); + returnCode = SilKit_ParticipantConfiguration_Destroy(participantConfigurationFromAFile); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + + SilKit_Participant* participant = nullptr; + returnCode = SilKit_Participant_Create(nullptr, participantConfiguration, "Participant1", "42"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Participant_Create(&participant, nullptr, "Participant1", "42"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Participant_Create(&participant, participantConfiguration, nullptr, "42"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_Participant_Create(&participant, participantConfiguration, "Participant1", nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // Bad Parameter ParticipantConfiguration_FromString + returnCode = SilKit_ParticipantConfiguration_FromString(&participantConfiguration, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_ParticipantConfiguration_FromString(nullptr, SILKIT_CONFIG_STRING); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + // Bad Parameter ParticipantConfiguration_FromFile + returnCode = SilKit_ParticipantConfiguration_FromFile(&participantConfigurationFromAFile, nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + returnCode = SilKit_ParticipantConfiguration_FromFile(nullptr, "ParticipantConfiguration_FullIncludes.yaml"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + returnCode = SilKit_Participant_Create(&participant, participantConfiguration, "ParticipantNotExisting", "42"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_UNSPECIFIEDERROR); + + returnCode = SilKit_ParticipantConfiguration_Destroy(participantConfiguration); + EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); + + returnCode = SilKit_ParticipantConfiguration_Destroy(nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); + + participantConfiguration = nullptr; + + returnCode = SilKit_ParticipantConfiguration_FromString(&participantConfiguration, SILKIT_MALFORMED_CONFIG_STRING); + EXPECT_EQ(returnCode, SilKit_ReturnCode_UNSPECIFIEDERROR); + EXPECT_EQ(participantConfiguration, nullptr); + + returnCode = SilKit_ParticipantConfiguration_FromFile(&participantConfiguration, "this_file_does_not_exist.yaml"); + EXPECT_EQ(returnCode, SilKit_ReturnCode_UNSPECIFIEDERROR); + EXPECT_EQ(participantConfiguration, nullptr); + + // since there is no SIL Kit Registry with which one could create a Participant, we check against nullptr + returnCode = SilKit_Participant_Destroy(nullptr); + EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); } + +} // namespace diff --git a/SilKit/source/capi/Test_CapiSymbols.cpp b/SilKit/source/capi/Test_CapiSymbols.cpp old mode 100755 new mode 100644 index ed80c28d4..a6ba2e2af --- a/SilKit/source/capi/Test_CapiSymbols.cpp +++ b/SilKit/source/capi/Test_CapiSymbols.cpp @@ -31,116 +31,118 @@ namespace { // should expose missing symbols at compile time, no need to execute this ==> Disabled TEST(Test_CapiSymbols, DISABLED_link_all_public_symbols) { -SilKit_HandlerId id; + SilKit_HandlerId id; -(void) SilKit_CanController_Create(nullptr, nullptr, "", ""); -(void) SilKit_CanController_Start(nullptr); -(void) SilKit_CanController_Stop(nullptr); -(void) SilKit_CanController_Reset(nullptr); -(void) SilKit_CanController_Sleep(nullptr); -(void) SilKit_CanController_SendFrame(nullptr, nullptr, nullptr); -(void) SilKit_CanController_SetBaudRate(nullptr, 0,0,0); -(void) SilKit_CanController_AddFrameTransmitHandler(nullptr, nullptr, nullptr,0,&id); -(void) SilKit_CanController_RemoveFrameTransmitHandler(nullptr,0); -(void) SilKit_CanController_AddFrameHandler(nullptr, nullptr, nullptr, 0, &id); -(void) SilKit_CanController_RemoveFrameHandler(nullptr, id); -(void) SilKit_CanController_AddStateChangeHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_CanController_RemoveStateChangeHandler(nullptr, id); -(void) SilKit_CanController_AddErrorStateChangeHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_CanController_RemoveErrorStateChangeHandler(nullptr, id); -(void) SilKit_DataPublisher_Create(nullptr, nullptr,"",nullptr,0); -(void) SilKit_DataSubscriber_Create(nullptr, nullptr, "", nullptr, nullptr, nullptr); -(void) SilKit_DataPublisher_Publish(nullptr, nullptr); -(void) SilKit_DataSubscriber_SetDataMessageHandler(nullptr, nullptr, nullptr); -(void) SilKit_EthernetController_Create(nullptr, nullptr, "", ""); -(void) SilKit_EthernetController_Activate(nullptr); -(void) SilKit_EthernetController_Deactivate(nullptr); -(void) SilKit_EthernetController_AddFrameHandler(nullptr,nullptr, nullptr, 0, &id); -(void) SilKit_EthernetController_RemoveFrameHandler(nullptr, id); -(void) -(void) SilKit_EthernetController_RemoveFrameTransmitHandler(nullptr, id); -(void) SilKit_EthernetController_AddStateChangeHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_EthernetController_RemoveStateChangeHandler(nullptr, id); -(void) -(void) SilKit_EthernetController_RemoveBitrateChangeHandler(nullptr, id); -(void) SilKit_EthernetController_SendFrame(nullptr, nullptr, nullptr); -(void) SilKit_FlexrayController_Create(nullptr,nullptr, nullptr, nullptr); -(void) SilKit_FlexrayController_Configure(nullptr, nullptr); -(void) SilKit_FlexrayController_ReconfigureTxBuffer(nullptr, 0, nullptr); -(void) SilKit_FlexrayController_UpdateTxBuffer(nullptr, nullptr); -(void) SilKit_FlexrayController_ExecuteCmd(nullptr, 0); -(void) SilKit_FlexrayController_AddFrameHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_FlexrayController_RemoveFrameHandler(nullptr, id); -(void) SilKit_FlexrayController_AddFrameTransmitHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_FlexrayController_RemoveFrameTransmitHandler(nullptr,id); -(void) SilKit_FlexrayController_AddWakeupHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_FlexrayController_RemoveWakeupHandler(nullptr,id); -(void) SilKit_FlexrayController_AddPocStatusHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_FlexrayController_RemovePocStatusHandler(nullptr, id); -(void) SilKit_FlexrayController_AddSymbolHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_FlexrayController_RemoveSymbolHandler(nullptr, id); -(void) -(void) SilKit_FlexrayController_RemoveSymbolTransmitHandler(nullptr, id); -(void) SilKit_FlexrayController_AddCycleStartHandler(nullptr,nullptr, nullptr, &id); -(void) SilKit_FlexrayController_RemoveCycleStartHandler(nullptr, id); -(void) SilKit_LinController_Create(nullptr, nullptr, nullptr, nullptr); -(void) SilKit_LinController_Init(nullptr, nullptr); -(void) SilKit_LinController_Status(nullptr, nullptr); -(void) SilKit_LinController_SendFrame(nullptr, nullptr, 0); -(void) SilKit_LinController_SendFrameHeader(nullptr, 0); -(void) SilKit_LinController_UpdateTxBuffer(nullptr, nullptr); -(void) SilKit_LinController_GoToSleep(nullptr); -(void) SilKit_LinController_GoToSleepInternal(nullptr); -(void) SilKit_LinController_Wakeup(nullptr); -(void) SilKit_LinController_WakeupInternal(nullptr); -(void) SilKit_Experimental_LinController_GetSlaveConfiguration(nullptr, nullptr); -(void) SilKit_LinController_AddFrameStatusHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_LinController_RemoveFrameStatusHandler(nullptr, id); -(void) SilKit_LinController_AddGoToSleepHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_LinController_RemoveGoToSleepHandler(nullptr, id); -(void) SilKit_LinController_AddWakeupHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_LinController_RemoveWakeupHandler(nullptr, id); -(void) SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler(nullptr, 0); -(void) SilKit_Logger_Log(nullptr, 0, ""); -(void) SilKit_Logger_GetLogLevel(nullptr, nullptr); -(void) SilKit_SystemMonitor_Create(nullptr, nullptr); -(void) SilKit_LifecycleService_Create(nullptr, nullptr, nullptr); -(void) SilKit_TimeSyncService_Create(nullptr, nullptr); -(void) SilKit_LifecycleService_SetCommunicationReadyHandler(nullptr, nullptr, nullptr); -(void) SilKit_LifecycleService_SetCommunicationReadyHandlerAsync(nullptr, nullptr, nullptr); -(void) SilKit_LifecycleService_CompleteCommunicationReadyHandlerAsync(nullptr); -(void) SilKit_LifecycleService_SetStartingHandler(nullptr, nullptr, nullptr); -(void) SilKit_LifecycleService_SetStopHandler(nullptr, nullptr, nullptr); -(void) SilKit_LifecycleService_SetShutdownHandler(nullptr, nullptr, nullptr); -(void) SilKit_LifecycleService_SetAbortHandler(nullptr, nullptr, nullptr); -(void) SilKit_TimeSyncService_SetSimulationStepHandler(nullptr, nullptr, nullptr, 0); -(void) SilKit_TimeSyncService_SetSimulationStepHandlerAsync(nullptr, nullptr, nullptr, 0); -(void) SilKit_TimeSyncService_CompleteSimulationStep(nullptr); -(void) SilKit_LifecycleService_Pause(nullptr, ""); -(void) SilKit_LifecycleService_Continue(nullptr); -(void) SilKit_LifecycleService_Stop(nullptr, ""); -(void) SilKit_SystemMonitor_GetParticipantStatus(nullptr, nullptr, ""); -(void) SilKit_SystemMonitor_GetSystemState(nullptr, nullptr); -(void) SilKit_SystemMonitor_AddSystemStateHandler(nullptr, nullptr, nullptr, &id); -(void) SilKit_SystemMonitor_RemoveSystemStateHandler(nullptr, 0); -(void) SilKit_SystemMonitor_AddParticipantStatusHandler(nullptr, nullptr, 0, nullptr); -(void) SilKit_SystemMonitor_RemoveParticipantStatusHandler(nullptr, 0); -(void) SilKit_LifecycleService_StartLifecycle(nullptr); -(void) SilKit_LifecycleService_WaitForLifecycleToComplete(nullptr, nullptr); -(void) SilKit_ParticipantConfiguration_FromString(nullptr, ""); -(void) SilKit_ParticipantConfiguration_Destroy(nullptr); -(void) SilKit_Participant_Create(nullptr, nullptr, "", ""); -(void) SilKit_Participant_Destroy(nullptr); -(void) SilKit_RpcServer_Create(nullptr, nullptr,"", nullptr, nullptr, nullptr); -(void) SilKit_RpcServer_SubmitResult(nullptr, nullptr, nullptr); -(void) SilKit_RpcServer_SetCallHandler(nullptr, nullptr, nullptr); -(void) SilKit_RpcClient_Create(nullptr, nullptr, "", nullptr, nullptr, nullptr); -(void) SilKit_RpcClient_Call(nullptr, nullptr, nullptr); -(void) SilKit_RpcClient_SetCallResultHandler(nullptr, nullptr, nullptr); -(void) SilKit_ReturnCodeToString(nullptr, SilKit_ReturnCode_BADPARAMETER); -(void) SilKit_Participant_GetLogger(nullptr, nullptr); -(void)SilKit_GetLastErrorString(); + (void)SilKit_CanController_Create(nullptr, nullptr, "", ""); + (void)SilKit_CanController_Start(nullptr); + (void)SilKit_CanController_Stop(nullptr); + (void)SilKit_CanController_Reset(nullptr); + (void)SilKit_CanController_Sleep(nullptr); + (void)SilKit_CanController_SendFrame(nullptr, nullptr, nullptr); + (void)SilKit_CanController_SetBaudRate(nullptr, 0, 0, 0); + (void)SilKit_CanController_AddFrameTransmitHandler(nullptr, nullptr, nullptr, 0, &id); + (void)SilKit_CanController_RemoveFrameTransmitHandler(nullptr, 0); + (void)SilKit_CanController_AddFrameHandler(nullptr, nullptr, nullptr, 0, &id); + (void)SilKit_CanController_RemoveFrameHandler(nullptr, id); + (void)SilKit_CanController_AddStateChangeHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_CanController_RemoveStateChangeHandler(nullptr, id); + (void)SilKit_CanController_AddErrorStateChangeHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_CanController_RemoveErrorStateChangeHandler(nullptr, id); + (void)SilKit_DataPublisher_Create(nullptr, nullptr, "", nullptr, 0); + (void)SilKit_DataSubscriber_Create(nullptr, nullptr, "", nullptr, nullptr, nullptr); + (void)SilKit_DataPublisher_Publish(nullptr, nullptr); + (void)SilKit_DataSubscriber_SetDataMessageHandler(nullptr, nullptr, nullptr); + (void)SilKit_EthernetController_Create(nullptr, nullptr, "", ""); + (void)SilKit_EthernetController_Activate(nullptr); + (void)SilKit_EthernetController_Deactivate(nullptr); + (void)SilKit_EthernetController_AddFrameHandler(nullptr, nullptr, nullptr, 0, &id); + (void)SilKit_EthernetController_RemoveFrameHandler(nullptr, id); + (void)(void)SilKit_EthernetController_RemoveFrameTransmitHandler(nullptr, id); + (void)SilKit_EthernetController_AddStateChangeHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_EthernetController_RemoveStateChangeHandler(nullptr, id); + (void)(void)SilKit_EthernetController_RemoveBitrateChangeHandler(nullptr, id); + (void)SilKit_EthernetController_SendFrame(nullptr, nullptr, nullptr); + (void)SilKit_FlexrayController_Create(nullptr, nullptr, nullptr, nullptr); + (void)SilKit_FlexrayController_Configure(nullptr, nullptr); + (void)SilKit_FlexrayController_ReconfigureTxBuffer(nullptr, 0, nullptr); + (void)SilKit_FlexrayController_UpdateTxBuffer(nullptr, nullptr); + (void)SilKit_FlexrayController_ExecuteCmd(nullptr, 0); + (void)SilKit_FlexrayController_AddFrameHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_FlexrayController_RemoveFrameHandler(nullptr, id); + (void)SilKit_FlexrayController_AddFrameTransmitHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_FlexrayController_RemoveFrameTransmitHandler(nullptr, id); + (void)SilKit_FlexrayController_AddWakeupHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_FlexrayController_RemoveWakeupHandler(nullptr, id); + (void)SilKit_FlexrayController_AddPocStatusHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_FlexrayController_RemovePocStatusHandler(nullptr, id); + (void)SilKit_FlexrayController_AddSymbolHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_FlexrayController_RemoveSymbolHandler(nullptr, id); + (void)(void)SilKit_FlexrayController_RemoveSymbolTransmitHandler(nullptr, id); + (void)SilKit_FlexrayController_AddCycleStartHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_FlexrayController_RemoveCycleStartHandler(nullptr, id); + (void)SilKit_LinController_Create(nullptr, nullptr, nullptr, nullptr); + (void)SilKit_LinController_Init(nullptr, nullptr); + (void)SilKit_LinController_Status(nullptr, nullptr); + (void)SilKit_LinController_SendFrame(nullptr, nullptr, 0); + (void)SilKit_LinController_SendFrameHeader(nullptr, 0); + (void)SilKit_LinController_UpdateTxBuffer(nullptr, nullptr); + (void)SilKit_LinController_GoToSleep(nullptr); + (void)SilKit_LinController_GoToSleepInternal(nullptr); + (void)SilKit_LinController_Wakeup(nullptr); + (void)SilKit_LinController_WakeupInternal(nullptr); + (void)SilKit_Experimental_LinController_GetSlaveConfiguration(nullptr, nullptr); + (void)SilKit_LinController_AddFrameStatusHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_LinController_RemoveFrameStatusHandler(nullptr, id); + (void)SilKit_LinController_AddGoToSleepHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_LinController_RemoveGoToSleepHandler(nullptr, id); + (void)SilKit_LinController_AddWakeupHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_LinController_RemoveWakeupHandler(nullptr, id); + (void)SilKit_Experimental_LinController_AddLinSlaveConfigurationHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_Experimental_LinController_RemoveLinSlaveConfigurationHandler(nullptr, 0); + (void)SilKit_Logger_Log(nullptr, 0, ""); + (void)SilKit_Logger_GetLogLevel(nullptr, nullptr); + (void)SilKit_SystemMonitor_Create(nullptr, nullptr); + (void)SilKit_LifecycleService_Create(nullptr, nullptr, nullptr); + (void)SilKit_TimeSyncService_Create(nullptr, nullptr); + (void)SilKit_LifecycleService_SetCommunicationReadyHandler(nullptr, nullptr, nullptr); + (void)SilKit_LifecycleService_SetCommunicationReadyHandlerAsync(nullptr, nullptr, nullptr); + (void)SilKit_LifecycleService_CompleteCommunicationReadyHandlerAsync(nullptr); + (void)SilKit_LifecycleService_SetStartingHandler(nullptr, nullptr, nullptr); + (void)SilKit_LifecycleService_SetStopHandler(nullptr, nullptr, nullptr); + (void)SilKit_LifecycleService_SetShutdownHandler(nullptr, nullptr, nullptr); + (void)SilKit_LifecycleService_SetAbortHandler(nullptr, nullptr, nullptr); + (void)SilKit_TimeSyncService_SetSimulationStepHandler(nullptr, nullptr, nullptr, 0); + (void)SilKit_TimeSyncService_SetSimulationStepHandlerAsync(nullptr, nullptr, nullptr, 0); + (void)SilKit_TimeSyncService_CompleteSimulationStep(nullptr); + (void)SilKit_LifecycleService_Pause(nullptr, ""); + (void)SilKit_LifecycleService_Continue(nullptr); + (void)SilKit_LifecycleService_Stop(nullptr, ""); + (void)SilKit_SystemMonitor_GetParticipantStatus(nullptr, nullptr, ""); + (void)SilKit_SystemMonitor_GetSystemState(nullptr, nullptr); + (void)SilKit_SystemMonitor_AddSystemStateHandler(nullptr, nullptr, nullptr, &id); + (void)SilKit_SystemMonitor_RemoveSystemStateHandler(nullptr, 0); + (void)SilKit_SystemMonitor_AddParticipantStatusHandler(nullptr, nullptr, 0, nullptr); + (void)SilKit_SystemMonitor_RemoveParticipantStatusHandler(nullptr, 0); + (void)SilKit_LifecycleService_StartLifecycle(nullptr); + (void)SilKit_LifecycleService_WaitForLifecycleToComplete(nullptr, nullptr); + (void)SilKit_ParticipantConfiguration_FromString(nullptr, ""); + (void)SilKit_ParticipantConfiguration_FromFile(nullptr, ""); + (void)SilKit_ParticipantConfiguration_Destroy(nullptr); + (void)SilKit_Participant_Create(nullptr, nullptr, "", ""); + (void)SilKit_Participant_Destroy(nullptr); + (void)SilKit_RpcServer_Create(nullptr, nullptr, "", nullptr, nullptr, nullptr); + (void)SilKit_RpcServer_SubmitResult(nullptr, nullptr, nullptr); + (void)SilKit_RpcServer_SetCallHandler(nullptr, nullptr, nullptr); + (void)SilKit_RpcClient_Create(nullptr, nullptr, "", nullptr, nullptr, nullptr); + (void)SilKit_RpcClient_Call(nullptr, nullptr, nullptr); + (void)SilKit_RpcClient_SetCallResultHandler(nullptr, nullptr, nullptr); + (void)SilKit_ReturnCodeToString(nullptr, SilKit_ReturnCode_BADPARAMETER); + (void)SilKit_Participant_GetLogger(nullptr, nullptr); + (void)SilKit_GetLastErrorString(); + (void)SilKit_Experimental_NetworkSimulator_Create(nullptr, nullptr); + (void)SilKit_Experimental_NetworkSimulator_Start(nullptr); + (void)SilKit_Experimental_NetworkSimulator_SimulateNetwork(nullptr, "", SilKit_NetworkType_Undefined, nullptr, + nullptr); } -} +} // namespace diff --git a/SilKit/source/capi/Test_CapiTimeSync.cpp b/SilKit/source/capi/Test_CapiTimeSync.cpp old mode 100755 new mode 100644 index cee92764f..53c33a529 --- a/SilKit/source/capi/Test_CapiTimeSync.cpp +++ b/SilKit/source/capi/Test_CapiTimeSync.cpp @@ -31,15 +31,14 @@ using SilKit::Core::Tests::DummyParticipant; class Test_CapiTimeSync : public testing::Test { -protected: +protected: SilKit::Core::Tests::DummyParticipant mockParticipant; Test_CapiTimeSync() {} - }; void SilKitCALL SimTask(void* /*context*/, SilKit_TimeSyncService* /*timeSyncService*/, SilKit_NanosecondsTime /*now*/, - SilKit_NanosecondsTime /*duration*/) + SilKit_NanosecondsTime /*duration*/) { } @@ -53,8 +52,7 @@ TEST_F(Test_CapiTimeSync, participant_state_handling_nullpointer_params) (SilKit_TimeSyncService*)(mockParticipant .CreateLifecycleService(LifecycleConfiguration{OperationMode::Coordinated}) ->CreateTimeSyncService()), - nullptr, - nullptr, 0); + nullptr, nullptr, 0); EXPECT_EQ(returnCode, SilKit_ReturnCode_BADPARAMETER); } @@ -62,16 +60,17 @@ TEST_F(Test_CapiTimeSync, participant_state_handling_function_mapping) { SilKit_ReturnCode returnCode; - EXPECT_CALL(mockParticipant.mockTimeSyncService, - SetSimulationStepHandler( - testing::Matcher(testing::_), testing ::_) - ).Times(testing::Exactly(1)); + EXPECT_CALL( + mockParticipant.mockTimeSyncService, + SetSimulationStepHandler( + testing::Matcher(testing::_), + testing ::_)) + .Times(testing::Exactly(1)); returnCode = SilKit_TimeSyncService_SetSimulationStepHandler( (SilKit_TimeSyncService*)(mockParticipant .CreateLifecycleService(LifecycleConfiguration{OperationMode::Coordinated}) ->CreateTimeSyncService()), - nullptr, - &SimTask, 1000000); + nullptr, &SimTask, 1000000); EXPECT_EQ(returnCode, SilKit_ReturnCode_SUCCESS); } diff --git a/SilKit/source/capi/Test_CapiVersion.cpp b/SilKit/source/capi/Test_CapiVersion.cpp index 3145b71dc..8046e937c 100644 --- a/SilKit/source/capi/Test_CapiVersion.cpp +++ b/SilKit/source/capi/Test_CapiVersion.cpp @@ -31,7 +31,7 @@ namespace { class Test_CapiVersion : public testing::Test { -protected: +protected: Test_CapiVersion() {} }; diff --git a/SilKit/source/config/CMakeLists.txt b/SilKit/source/config/CMakeLists.txt index a0d24d2e9..0239b3876 100644 --- a/SilKit/source/config/CMakeLists.txt +++ b/SilKit/source/config/CMakeLists.txt @@ -54,7 +54,7 @@ target_link_libraries(O_SilKit_Config PUBLIC I_SilKit_Config PRIVATE SilKitInterface - PUBLIC I_SilKit_Util + PRIVATE O_SilKit_Util_Filesystem PUBLIC yaml-cpp PRIVATE I_SilKit_Util_FileHelpers ) @@ -65,7 +65,7 @@ target_include_directories(O_SilKit_Config add_silkit_test_to_executable(SilKitUnitTests SOURCES Test_Validation.cpp - LIBS O_SilKit_Config + LIBS O_SilKit_Config S_SilKitImpl ) add_silkit_test_to_executable(SilKitUnitTests @@ -75,6 +75,22 @@ add_silkit_test_to_executable(SilKitUnitTests ParticipantConfiguration_Minimal.json ParticipantConfiguration_Full.json ParticipantConfiguration_Full.yaml + + TestParticipantConfigs/ParticipantConfiguration_FullIncludes.yaml + TestParticipantConfigs/ParticipantConfiguration_FullIncludes_Reference.yaml + + TestParticipantConfigs/ExtensionsIncludes.yaml + + TestParticipantConfigs/LoggingIncludes.yaml + + TestParticipantConfigs/ParticipantConfiguration_MultipleAcceptorUris.yaml + TestParticipantConfigs/MultipleAcceptorUrisInclude.yaml + + TestParticipantConfigs/ParticipantConfiguration_DuplicateControllerNames.yaml + TestParticipantConfigs/DuplicateEthernetControllerNames.yaml + + TestParticipantConfigs/ParticipantConfiguration_FromString_Reference.yaml + ParticipantConfiguration_Logging_Without_File.json ) @@ -88,7 +104,47 @@ add_silkit_test_to_executable(SilKitUnitTests LIBS O_SilKit_Config yaml-cpp ) +set(ParticipantTestCanConfigs + TestParticipantConfigs/CanIncludes.yaml + TestParticipantConfigs/CanInclude2.yaml + TestParticipantConfigs/CanInclude3.yaml + TestParticipantConfigs/CanInclude4.yaml + TestParticipantConfigs/CanInclude5.yaml + TestParticipantConfigs/CanInclude6.yaml +) +set(ParticipantTestMiddlewareConfigs + TestParticipantConfigs/MiddlewareInclude.yaml + TestParticipantConfigs/MoreMiddlewareIncludes.yaml +) + +add_custom_target(CopyTestConfigs) + +function(copy_participant_configs CopyTarget Configs ConfigsDir) + foreach(config ${Configs}) + get_filename_component(configPath "${config}" ABSOLUTE) + list(APPEND TEST_CONFIGS "${configPath}") + endforeach() + + add_custom_command(TARGET ${CopyTarget} POST_BUILD + COMMAND + ${CMAKE_COMMAND} -E make_directory + ${CMAKE_BINARY_DIR}/$/ConfigSnippets/${ConfigsDir} + ) + add_custom_command(TARGET ${CopyTarget} POST_BUILD + COMMAND + ${CMAKE_COMMAND} -E copy + "${TEST_CONFIGS}" + ${CMAKE_BINARY_DIR}/$/ConfigSnippets/${ConfigsDir} + COMMAND_EXPAND_LISTS + ) +endfunction() + +copy_participant_configs(CopyTestConfigs "${ParticipantTestCanConfigs}" "CAN") +copy_participant_configs(CopyTestConfigs "${ParticipantTestMiddlewareConfigs}" "Middleware") + if(SILKIT_BUILD_TESTS) + add_dependencies(SilKitUnitTests CopyTestConfigs) + add_library(I_SilKit_Config_TestUtils INTERFACE) target_include_directories(I_SilKit_Config_TestUtils diff --git a/SilKit/source/config/Configuration.cpp b/SilKit/source/config/Configuration.cpp index 0fe5d6737..533eb189e 100644 --- a/SilKit/source/config/Configuration.cpp +++ b/SilKit/source/config/Configuration.cpp @@ -27,7 +27,7 @@ namespace Config { inline namespace v1 { -} // inline namespace v1 +} // namespace v1 } // namespace Config } // namespace SilKit diff --git a/SilKit/source/config/Configuration.hpp b/SilKit/source/config/Configuration.hpp index c4f668ebc..f3ddb6713 100644 --- a/SilKit/source/config/Configuration.hpp +++ b/SilKit/source/config/Configuration.hpp @@ -68,16 +68,16 @@ struct Sink File }; - Type type{ Type::Remote }; - Services::Logging::Level level{ Services::Logging::Level::Info }; + Type type{Type::Remote}; + Services::Logging::Level level{Services::Logging::Level::Info}; std::string logName; }; //! \brief Logger service struct Logging { - bool logFromRemotes{ false }; - Services::Logging::Level flushLevel{ Services::Logging::Level::Off }; + bool logFromRemotes{false}; + Services::Logging::Level flushLevel{Services::Logging::Level::Off}; std::vector sinks; }; @@ -95,7 +95,7 @@ struct TraceSink Mdf4File }; - Type type{ Type::Undefined }; + Type type{Type::Undefined}; std::string name; std::string outputPath; }; @@ -109,7 +109,7 @@ struct TraceSource Mdf4File }; - Type type{ Type::Undefined }; + Type type{Type::Undefined}; std::string name; std::string inputPath; }; @@ -138,24 +138,26 @@ struct Replay Receive, Both, }; - Direction direction{ Direction::Undefined }; + Direction direction{Direction::Undefined}; MdfChannel mdfChannel; }; struct SimulatedNetwork { // This method allows for generic usage, along with ControllerConfigTs - auto GetNetworkType() -> NetworkType + auto GetNetworkType() -> NetworkType { return type; } std::string name; - NetworkType type{ NetworkType::Undefined }; + NetworkType type{NetworkType::Undefined}; std::vector useTraceSinks; Replay replay; }; inline bool operator==(const Sink& lhs, const Sink& rhs); +inline bool operator<(const Sink& lhs, const Sink& rhs); +inline bool operator>(const Sink& lhs, const Sink& rhs); inline bool operator==(const Logging& lhs, const Logging& rhs); inline bool operator==(const TraceSink& lhs, const TraceSink& rhs); inline bool operator==(const TraceSource& lhs, const TraceSource& rhs); @@ -181,7 +183,7 @@ auto to_string(TraceSink::Type sinkType) -> std::string case TraceSink::Type::Undefined: return "Undefined"; default: - throw SilKit::TypeConversionError{ "Invalid SinkType" }; + throw SilKit::TypeConversionError{"Invalid SinkType"}; } } @@ -189,65 +191,71 @@ auto to_string(NetworkType networkType) -> std::string { switch (networkType) { - case NetworkType::Undefined: return "Undefined"; - case NetworkType::Invalid: return "Invalid"; - case NetworkType::CAN: return "CAN"; - case NetworkType::LIN: return "LIN"; - case NetworkType::Ethernet: return "Ethernet"; - case NetworkType::FlexRay: return "FlexRay"; - case NetworkType::Data: return "Data"; - case NetworkType::RPC: return "RPC"; - default: return "Unknown"; + case NetworkType::Undefined: + return "Undefined"; + case NetworkType::Invalid: + return "Invalid"; + case NetworkType::CAN: + return "CAN"; + case NetworkType::LIN: + return "LIN"; + case NetworkType::Ethernet: + return "Ethernet"; + case NetworkType::FlexRay: + return "FlexRay"; + case NetworkType::Data: + return "Data"; + case NetworkType::RPC: + return "RPC"; + default: + return "Unknown"; } } bool operator==(const Sink& lhs, const Sink& rhs) { - return lhs.type == rhs.type - && lhs.level == rhs.level - && lhs.logName == rhs.logName; + return lhs.type == rhs.type && lhs.level == rhs.level && lhs.logName == rhs.logName; +} + +bool operator<(const Sink& lhs, const Sink& rhs) +{ + return lhs.logName.compare(rhs.logName) < 0; +} + +bool operator>(const Sink& lhs, const Sink& rhs) +{ + return rhs < lhs; } bool operator==(const Logging& lhs, const Logging& rhs) { - return lhs.logFromRemotes == rhs.logFromRemotes - && lhs.flushLevel == rhs.flushLevel - && lhs.sinks == rhs.sinks; + return lhs.logFromRemotes == rhs.logFromRemotes && lhs.flushLevel == rhs.flushLevel && lhs.sinks == rhs.sinks; } bool operator==(const TraceSink& lhs, const TraceSink& rhs) { - return lhs.name == rhs.name - && lhs.outputPath == rhs.outputPath - && lhs.type == rhs.type; + return lhs.name == rhs.name && lhs.outputPath == rhs.outputPath && lhs.type == rhs.type; } bool operator==(const TraceSource& lhs, const TraceSource& rhs) { - return lhs.inputPath == rhs.inputPath - && lhs.type == rhs.type - && lhs.name == rhs.name; + return lhs.inputPath == rhs.inputPath && lhs.type == rhs.type && lhs.name == rhs.name; } bool operator==(const Replay& lhs, const Replay& rhs) { - return lhs.useTraceSource == rhs.useTraceSource - && lhs.direction == rhs.direction - && lhs.mdfChannel == rhs.mdfChannel - ; + return lhs.useTraceSource == rhs.useTraceSource && lhs.direction == rhs.direction + && lhs.mdfChannel == rhs.mdfChannel; } bool operator==(const MdfChannel& lhs, const MdfChannel& rhs) { - return lhs.channelName == rhs.channelName - && lhs.channelSource == rhs.channelSource - && lhs.channelPath == rhs.channelPath - && lhs.groupName == rhs.groupName - && lhs.groupSource == rhs.groupSource - && lhs.groupPath == rhs.groupPath; + return lhs.channelName == rhs.channelName && lhs.channelSource == rhs.channelSource + && lhs.channelPath == rhs.channelPath && lhs.groupName == rhs.groupName && lhs.groupSource == rhs.groupSource + && lhs.groupPath == rhs.groupPath; } -} // inline namespace v1 +} // namespace v1 } // namespace Config } // namespace SilKit diff --git a/SilKit/source/config/ConfigurationTestUtils.hpp b/SilKit/source/config/ConfigurationTestUtils.hpp index 683d900c5..6bbeb8348 100644 --- a/SilKit/source/config/ConfigurationTestUtils.hpp +++ b/SilKit/source/config/ConfigurationTestUtils.hpp @@ -37,6 +37,8 @@ inline auto MakeEmptyParticipantConfiguration() -> std::shared_ptr std::shared_ptr; +inline auto MakeParticipantConfigurationStringWithLogging(Services::Logging::Level logLevel) -> std::string; + inline auto MakeEmptyParticipantConfigurationImpl() -> std::shared_ptr; inline auto MakeParticipantConfigurationWithLoggingImpl(Services::Logging::Level logLevel) @@ -57,15 +59,21 @@ auto MakeEmptyParticipantConfiguration() -> std::shared_ptr std::shared_ptr +auto MakeParticipantConfigurationStringWithLogging(Services::Logging::Level logLevel) -> std::string { std::ostringstream ss; ss << R"({"Logging": {"Sinks": [{"Type": "Stdout", "Level": ")"; ss << to_string(logLevel); ss << R"("}]}})"; - return SilKit::Config::ParticipantConfigurationFromString(ss.str()); + return ss.str(); +} + +auto MakeParticipantConfigurationWithLogging(Services::Logging::Level logLevel) + -> std::shared_ptr +{ + auto configString = MakeParticipantConfigurationStringWithLogging(logLevel); + return SilKit::Config::ParticipantConfigurationFromString(configString); } inline auto MakeEmptyParticipantConfigurationImpl() -> std::shared_ptr diff --git a/SilKit/source/config/ParticipantConfiguration.hpp b/SilKit/source/config/ParticipantConfiguration.hpp old mode 100755 new mode 100644 index 7c54182f5..4eaf8c045 --- a/SilKit/source/config/ParticipantConfiguration.hpp +++ b/SilKit/source/config/ParticipantConfiguration.hpp @@ -47,7 +47,10 @@ inline namespace v1 { //! \brief Generic dummy for all internal controllers - do not make available to public API! struct InternalController { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::Undefined; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::Undefined; + } std::string name; SilKit::Util::Optional network; @@ -60,7 +63,10 @@ struct InternalController //! \brief CAN controller service struct CanController { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::CAN; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::CAN; + } std::string name; SilKit::Util::Optional network; @@ -76,7 +82,10 @@ struct CanController //! \brief LIN controller service struct LinController { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::LIN; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::LIN; + } std::string name; SilKit::Util::Optional network; @@ -92,7 +101,10 @@ struct LinController //! \brief Ethernet controller service struct EthernetController { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::Ethernet; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::Ethernet; + } std::string name; SilKit::Util::Optional network; @@ -108,7 +120,10 @@ struct EthernetController //! \brief FlexRay controller service struct FlexrayController { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::FlexRay; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::FlexRay; + } std::string name; SilKit::Util::Optional network; @@ -128,13 +143,16 @@ struct FlexrayController //! \brief Publisher configuration for the Data communication service struct DataPublisher { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::Data; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::Data; + } std::string name; SilKit::Util::Optional topic; //! \brief History length of a DataPublisher. - SilKit::Util::Optional history{ 0 }; + SilKit::Util::Optional history{0}; std::vector useTraceSinks; Replay replay; @@ -143,7 +161,10 @@ struct DataPublisher //! \brief Subscriber configuration for the Data communication service struct DataSubscriber { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::Data; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::Data; + } std::string name; SilKit::Util::Optional topic; @@ -159,7 +180,10 @@ struct DataSubscriber //! \brief Server configuration for the RPC communication service struct RpcServer { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::RPC; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::RPC; + } std::string name; SilKit::Util::Optional functionName; @@ -171,7 +195,10 @@ struct RpcServer //! \brief Client configuration for the RPC communication service struct RpcClient { - static constexpr auto GetNetworkType() -> NetworkType { return NetworkType::RPC; } + static constexpr auto GetNetworkType() -> NetworkType + { + return NetworkType::RPC; + } std::string name; SilKit::Util::Optional functionName; @@ -220,17 +247,18 @@ struct Extensions struct Middleware { std::string registryUri{}; //!< Registry URI to connect to (configuration has priority) - int connectAttempts{ 1 }; //!< Number of connection attempts to the registry a participant should perform. - int tcpReceiveBufferSize{ -1 }; - int tcpSendBufferSize{ -1 }; - bool tcpNoDelay{ false }; //!< Disables Nagle's algorithm. - bool tcpQuickAck{ false }; //!< Setting this Linux specific flag disables delayed TCP/IP acknowledgements. - bool enableDomainSockets{ true }; //!< By default local domain socket is preferred to TCP/IP sockets. - std::vector acceptorUris{}; //!< Explicit list of endpoints this participant will accept connections on. + int connectAttempts{1}; //!< Number of connection attempts to the registry a participant should perform. + int tcpReceiveBufferSize{-1}; + int tcpSendBufferSize{-1}; + bool tcpNoDelay{false}; //!< Disables Nagle's algorithm. + bool tcpQuickAck{false}; //!< Setting this Linux specific flag disables delayed TCP/IP acknowledgements. + bool enableDomainSockets{true}; //!< By default local domain socket is preferred to TCP/IP sockets. + std::vector + acceptorUris{}; //!< Explicit list of endpoints this participant will accept connections on. //! By default, communication with other participants using the registry as a proxy is enabled. - bool registryAsFallbackProxy{ true }; + bool registryAsFallbackProxy{true}; //! By default, requesting connection of other participants, and honoring these requests by other participants is enabled. - bool experimentalRemoteParticipantConnection{ true }; + bool experimentalRemoteParticipantConnection{true}; //! Timeout for individual connection attempts (TCP, Local-Domain) and handshakes. double connectTimeoutSeconds{5.0}; }; @@ -240,8 +268,7 @@ struct Middleware // ================================================================================ //! \brief ParticipantConfiguration is the main configuration data object for a SILKIT participant. -struct ParticipantConfiguration - : public IParticipantConfiguration +struct ParticipantConfiguration : public IParticipantConfiguration { ParticipantConfiguration() = default; @@ -249,7 +276,7 @@ struct ParticipantConfiguration //virtual auto ToJsonString() -> std::string override; //! \brief Version of the JSON/YAML schema. - std::string schemaVersion{ "1" }; + std::string schemaVersion{"1"}; //! \brief An optional user description for documentation purposes. Currently unused. std::string description; //! \brief An optional file path. diff --git a/SilKit/source/config/ParticipantConfiguration.schema.json b/SilKit/source/config/ParticipantConfiguration.schema.json index 3d175d8da..a7604af2a 100644 --- a/SilKit/source/config/ParticipantConfiguration.schema.json +++ b/SilKit/source/config/ParticipantConfiguration.schema.json @@ -709,6 +709,28 @@ }, "additionalProperties": false }, + "Includes": { + "type": "object", + "description": "Optional configuration to include other participant configurations files", + "properties": { + "SearchPathHints": { + "type": "array", + "items": { + "type": "string", + "description": "A filesystem path to additionally search for files to be included", + "examples": [ "/urs/etc/sil-kit-configs/", "C:\\Temp\\sil-kit-configs\\" ] + } + }, + "Files": { + "type": "array", + "items": { + "type": "string", + "description": "Participant configuration files to be included", + "examples": [ "relative/path/to/included.silkit.yaml", "logging.silkit.yaml" ] + } + } + } + }, "Middleware": { "type": "object", "description": "Optional configuration of the SIL Kit middleware", @@ -740,9 +762,9 @@ "default": true }, "ConnectTimeoutSeconds": { - "type": "number", - "minimum": 0.0, - "default": 5.0 + "type": "number", + "minimum": 0.0, + "default": 5.0 } }, "additionalProperties": false diff --git a/SilKit/source/config/ParticipantConfigurationFromXImpl.cpp b/SilKit/source/config/ParticipantConfigurationFromXImpl.cpp index 93065cae4..e8978aa2e 100644 --- a/SilKit/source/config/ParticipantConfigurationFromXImpl.cpp +++ b/SilKit/source/config/ParticipantConfigurationFromXImpl.cpp @@ -20,11 +20,18 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ParticipantConfiguration.hpp" +#include "Filesystem.hpp" #include #include #include +#include +#include +#include +#include "FileHelpers.hpp" +#include "ParticipantConfigurationFromXImpl.hpp" +#include "silkit/services/logging/string_utils.hpp" #include "YamlParser.hpp" #include "YamlValidator.hpp" @@ -33,25 +40,60 @@ namespace Config { inline namespace v1 { -// ================================================================================ -// Helper functions -// ================================================================================ namespace { -auto ReadFile(const std::string& filename) -> std::string +// ================================================================================= +// Helper structs to keep metadata when processing/merging included config snippets +// ================================================================================= +using ConfigInclude = std::pair; +struct MiddlewareCache { - std::ifstream fs(filename); - - if (!fs.is_open()) - throw SilKit::ConfigurationError("the file could not be opened"); - - std::stringstream buffer; - buffer << fs.rdbuf(); + std::vector acceptorUris; + SilKit::Util::Optional registryUri; + SilKit::Util::Optional connectTimeoutSeconds; + SilKit::Util::Optional connectAttempts; + SilKit::Util::Optional tcpReceiveBufferSize; + SilKit::Util::Optional tcpSendBufferSize; + SilKit::Util::Optional tcpNoDelay; + SilKit::Util::Optional tcpQuickAck; + SilKit::Util::Optional enableDomainSockets; + SilKit::Util::Optional registryAsFallbackProxy; + SilKit::Util::Optional experimentalRemoteParticipantConnection; +}; + +struct GlobalLogCache +{ + SilKit::Util::Optional logFromRemotes; + SilKit::Util::Optional flushLevel; + std::set fileSinks; + std::set sinks; + std::set fileNames; +}; + +struct ConfigIncludeData +{ + std::set searchPaths; + std::set includeSet; + std::vector configBuffer; + MiddlewareCache middlewareCache; + GlobalLogCache logCache; + std::map canCache; + std::map linCache; + std::map ethCache; + std::map flexrayCache; + std::map subCache; + std::map pubCache; + std::map rpcServerCache; + std::map rpcClientCache; + std::map traceSinkCache; + std::map traceSourceCache; +}; - return buffer.str(); -} -auto Parse(const std::string& text) -> SilKit::Config::ParticipantConfiguration +// ================================================================================ +// Helper functions to work with text and YAML +// ================================================================================ +void Validate(const std::string& text) { std::stringstream warnings; SilKit::Config::YamlValidator validator; @@ -63,15 +105,466 @@ auto Parse(const std::string& text) -> SilKit::Config::ParticipantConfiguration { std::cout << "YAML validation returned warnings: \n" << warnings.str() << std::endl; } - YAML::Node doc = YAML::Load(text); +} +auto Parse(const YAML::Node& doc) -> SilKit::Config::ParticipantConfiguration +{ auto configuration = !doc.IsNull() ? SilKit::Config::from_yaml(doc) : SilKit::Config::v1::ParticipantConfiguration{}; configuration.configurationFilePath.clear(); - return configuration; } +void CollectIncludes(const YAML::Node& config, std::vector& levelIncludes) +{ + if (config["Includes"]) + { + for (const auto& include : config["Includes"]["Files"]) + { + levelIncludes.push_back(include.as()); + } + } +} + +// ================================================================================ +// Helper functions to find and open config snippets +// ================================================================================ +std::string GetConfigParentPath(const std::string& configFile) +{ + namespace fs = SilKit::Filesystem; + auto filePath = fs::concatenate_paths(fs::current_path().string(), configFile); + return fs::parent_path(filePath).string(); +} + +void AppendToSearchPaths(const YAML::Node& doc, ConfigIncludeData& configData) +{ + if (doc["Includes"]) + { + for (auto& searchPath : doc["Includes"]["SearchPathHints"]) + { + auto tmpString = searchPath.as(); + + if (tmpString.empty()) + { + std::cout << "Warning: Got empty SearchPathHint!"; + continue; + } + + std::string suffix = ""; + auto lastChar = tmpString.back(); + // We assume that the user provides a Path + // Make sure they have a seperator + if (lastChar != '/' && lastChar != '\\') + { + suffix = SilKit::Filesystem::path::preferred_separator; + } + configData.searchPaths.insert(searchPath.as() + suffix); + } + } +} + +std::string OpenFileWithSearchHints(const std::string& configFile, const std::set& searchPathHints) +{ + std::stringstream buffer; + std::string text; + + auto ifs = Util::OpenIFStream(configFile); + // Try cwd first + if (ifs.is_open()) + { + buffer << ifs.rdbuf(); + return buffer.str(); + } + + for (auto& searchPathHint : searchPathHints) + { + auto completePath = searchPathHint + configFile; + + ifs = Util::OpenIFStream(completePath); + + if (ifs.is_open()) + { + buffer << ifs.rdbuf(); + return buffer.str(); + } + } + + std::stringstream error_msg; + error_msg << "The config file " << configFile << " could not be opened!"; + throw SilKit::ConfigurationError(error_msg.str()); +} + +// ================================================================================ +// Helper functions to merge config fields/vectors/sets +// ================================================================================ +template +void MergeCacheField(const SilKit::Util::Optional& includeObject, FieldT& rootObject) +{ + if (includeObject.has_value()) + { + rootObject = includeObject.value(); + } +} + +template +void MergeNamedVector(const std::vector& child, const std::string& field_name, std::vector& parent, + std::map& cache) +{ + std::map parentState; + + for (const auto& element : child) + { + auto duplicate = cache.find(element.name); + if (duplicate == cache.end()) + { + parent.push_back(element); + cache[element.name] = element; + } + else + { + if (duplicate->second == element) + { + std::cout << "Warning: exact duplicate of " << element.name << " found already!" << std::endl; + } + else + { + std::stringstream error_msg; + error_msg << "Config element " << field_name << " with name " << element.name + << " but different config already exists!"; + throw SilKit::ConfigurationError(error_msg.str()); + } + } + } +} + +template +void MergeCacheSet(const std::set& cache, std::vector& root) +{ + for (auto& element : cache) + { + root.push_back(element); + } +} + +// ================================================================================ +// Helper functions to cache config entries with complicated merge strategies +// ================================================================================ +template +void PopulateCacheField(const YAML::Node& root, std::string rootname, const std::string& field, + SilKit::Util::Optional& obj) +{ + SilKit::Util::Optional tmpObj; + optional_decode(tmpObj, root, field); + + if (tmpObj.has_value()) + { + if (obj.has_value() && (obj != tmpObj)) + { + std::stringstream error_msg; + error_msg << "Config element " << field << "(" << tmpObj << ") for " << rootname << " already set to \'" + << obj.value() << "\'!"; + throw SilKit::ConfigurationError(error_msg.str()); + } + obj = tmpObj; + } +} + +void CacheMiddleware(const YAML::Node& root, MiddlewareCache& cache) +{ + if (root["AcceptorUris"]) + { + if (cache.acceptorUris.size() > 0) + { + throw SilKit::ConfigurationError{"AcceptorUris already defined!"}; + } + optional_decode(cache.acceptorUris, root, "AcceptorUris"); + } + + PopulateCacheField(root, "Middleware", "ConnectAttempts", cache.connectAttempts); + PopulateCacheField(root, "Middleware", "TcpNoDelay", cache.tcpNoDelay); + PopulateCacheField(root, "Middleware", "TcpQuickAck", cache.tcpQuickAck); + PopulateCacheField(root, "Middleware", "TcpReceiveBufferSize", cache.tcpReceiveBufferSize); + PopulateCacheField(root, "Middleware", "TcpSendBufferSize", cache.tcpSendBufferSize); + PopulateCacheField(root, "Middleware", "EnableDomainSockets", cache.enableDomainSockets); + PopulateCacheField(root, "Middleware", "RegistryAsFallbackProxy", cache.registryAsFallbackProxy); + PopulateCacheField(root, "Middleware", "RegistryUri", cache.registryUri); + PopulateCacheField(root, "Middleware", "ExperimentalRemoteParticipantConnection", + cache.experimentalRemoteParticipantConnection); + PopulateCacheField(root, "Middleware", "ConnectTimeoutSeconds", cache.connectTimeoutSeconds); +} + +void CacheLoggingOptions(const YAML::Node& root, GlobalLogCache& cache) +{ + PopulateCacheField(root, "Logging", "FlushLevel", cache.flushLevel); + PopulateCacheField(root, "Logging", "LogFromRemotes", cache.logFromRemotes); +} + +void CacheLoggingSinks(const YAML::Node& config, GlobalLogCache& cache) +{ + for (const auto& sinkNode : config["Sinks"]) + { + auto sink = parse_as(sinkNode); + if (sink.type == Sink::Type::Stdout) + { + if (cache.sinks.count(sink) == 0) + { + // Replace the already included sink with this one + // since we have not set it yet + cache.sinks.insert(sink); + } + else + { + std::stringstream error_msg; + error_msg << "Stdout Sink already exists!"; + throw SilKit::ConfigurationError(error_msg.str()); + } + } + else if (sink.type == Sink::Type::Remote) + { + if (cache.sinks.count(sink) == 0) + { + // Replace the already included sink with this one + // since we have not set it yet + cache.sinks.insert(sink); + } + else + { + std::stringstream error_msg; + error_msg << "Remote Sink already exists!"; + throw SilKit::ConfigurationError(error_msg.str()); + } + } + else + { + if (cache.fileNames.count(sink.logName) == 0) + { + cache.fileSinks.insert(sink); + cache.fileNames.insert(sink.logName); + } + else + { + std::stringstream error_msg; + error_msg << "Filesink " << sink.logName << " already exists!"; + throw SilKit::ConfigurationError(error_msg.str()); + } + } + } +} + +void PopulateCaches(const YAML::Node& config, ConfigIncludeData& configIncludeData) +{ + // Cache those config options that need to be default constructed, since we lose the information + // about default constructed vs. explicitly set to the default value later + if (config["Middleware"]) + { + CacheMiddleware(config["Middleware"], configIncludeData.middlewareCache); + } + + if (config["Logging"]) + { + CacheLoggingOptions(config["Logging"], configIncludeData.logCache); + CacheLoggingSinks(config["Logging"], configIncludeData.logCache); + } +} + +// ========================================================================================================================= +// Functions to merge the different fields +// ========================================================================================================================= +void MergeExtensions(const SilKit::Config::v1::Extensions& child, SilKit::Config::v1::Extensions& parent) +{ + parent.searchPathHints.insert(parent.searchPathHints.end(), child.searchPathHints.begin(), + child.searchPathHints.end()); +} + +void MergeHealthCheck(const SilKit::Config::HealthCheck& include, SilKit::Config::HealthCheck& healthCheck) +{ + if (include.softResponseTimeout.has_value()) + { + if (healthCheck.softResponseTimeout.has_value() + && (healthCheck.softResponseTimeout.value() == include.softResponseTimeout.value())) + { + std::stringstream error_msg; + error_msg << "HealthCheck.SoftResponseTimeout already set to: " + << healthCheck.softResponseTimeout.value().count() << "ms"; + throw SilKit::ConfigurationError(error_msg.str()); + } + + healthCheck.softResponseTimeout = include.softResponseTimeout; + } + + if (include.hardResponseTimeout.has_value()) + { + if (healthCheck.hardResponseTimeout.has_value() + && healthCheck.hardResponseTimeout.value() == include.hardResponseTimeout.value()) + { + std::stringstream error_msg; + error_msg << "HealthCheck.HardResponseTimeout already set to: " + << healthCheck.hardResponseTimeout.value().count() << "ms"; + throw SilKit::ConfigurationError(error_msg.str()); + } + + healthCheck.hardResponseTimeout = include.hardResponseTimeout; + } +} + +void MergeParticipantName(const SilKit::Config::ParticipantConfiguration& include, + SilKit::Config::ParticipantConfiguration& config) +{ + if (include.participantName.size()) + { + if (config.participantName.empty()) + { + config.participantName = include.participantName; + } + else + { + throw SilKit::ConfigurationError("Participant Name already set to " + config.participantName); + } + } +} + +void MergeMiddleware(const MiddlewareCache& cache, Middleware& middleware) +{ + MergeCacheField(cache.connectAttempts, middleware.connectAttempts); + MergeCacheField(cache.tcpNoDelay, middleware.tcpNoDelay); + MergeCacheField(cache.tcpQuickAck, middleware.tcpQuickAck); + MergeCacheField(cache.tcpSendBufferSize, middleware.tcpSendBufferSize); + MergeCacheField(cache.tcpReceiveBufferSize, middleware.tcpReceiveBufferSize); + MergeCacheField(cache.enableDomainSockets, middleware.enableDomainSockets); + MergeCacheField(cache.registryUri, middleware.registryUri); + MergeCacheField(cache.registryAsFallbackProxy, middleware.registryAsFallbackProxy); + MergeCacheField(cache.experimentalRemoteParticipantConnection, middleware.experimentalRemoteParticipantConnection); + MergeCacheField(cache.connectTimeoutSeconds, middleware.connectTimeoutSeconds); + + middleware.acceptorUris = cache.acceptorUris; +} + +void MergeLogCache(const GlobalLogCache& cache, Logging& logging) +{ + MergeCacheField(cache.flushLevel, logging.flushLevel); + MergeCacheField(cache.logFromRemotes, logging.logFromRemotes); + MergeCacheSet(cache.sinks, logging.sinks); + MergeCacheSet(cache.fileSinks, logging.sinks); +} + + +auto MergeConfigs(ConfigIncludeData& configIncludeData) -> SilKit::Config::ParticipantConfiguration +{ + SilKit::Config::ParticipantConfiguration config; + for (const auto& include : configIncludeData.configBuffer) + { + // Merge all vectors first! + MergeNamedVector(include.second.canControllers, "CanController", + config.canControllers, configIncludeData.canCache); + MergeNamedVector(include.second.linControllers, "LinController", + config.linControllers, configIncludeData.linCache); + MergeNamedVector(include.second.ethernetControllers, + "EthernetController", config.ethernetControllers, + configIncludeData.ethCache); + MergeNamedVector(include.second.flexrayControllers, "FlexRayController", + config.flexrayControllers, + configIncludeData.flexrayCache); + MergeNamedVector(include.second.dataSubscribers, "DataSubscriber", + config.dataSubscribers, configIncludeData.subCache); + MergeNamedVector(include.second.dataPublishers, "DataPublisher", + config.dataPublishers, configIncludeData.pubCache); + MergeNamedVector(include.second.rpcServers, "RpcServer", config.rpcServers, + configIncludeData.rpcServerCache); + MergeNamedVector(include.second.rpcClients, "RpcClient", config.rpcClients, + configIncludeData.rpcClientCache); + + MergeNamedVector(include.second.tracing.traceSinks, "TraceSink", + config.tracing.traceSinks, configIncludeData.traceSinkCache); + MergeNamedVector(include.second.tracing.traceSources, "TraceSource", + config.tracing.traceSources, + configIncludeData.traceSourceCache); + + // Merge "scalar" config fields + MergeExtensions(include.second.extensions, config.extensions); + MergeHealthCheck(include.second.healthCheck, config.healthCheck); + MergeParticipantName(include.second, config); + } + + MergeMiddleware(configIncludeData.middlewareCache, config.middleware); + MergeLogCache(configIncludeData.logCache, config.logging); + + return config; +} + +// ========================================================================================================================= +// Include Logic +// ========================================================================================================================= +void ProcessIncludes(const YAML::Node& config, ConfigIncludeData& configData) +{ + std::vector levelIncludes; + + CollectIncludes(config, levelIncludes); + PopulateCaches(config, configData); + + // Breadth first traversal, which means we collect all includes per "level" first + // and then use the collected includes as the "next level" + const auto upperbound = 127u; + + for (auto i = 0u; i < upperbound; ++i) + { + std::vector tmpIncludes; + for (const auto& include : levelIncludes) + { + if (configData.includeSet.count(include) > 0) + { + std::cout << "Warning: Config " << include << " already included!" << std::endl; + continue; + } + + // Get the next Include to be processed within this tree level + auto nextConfig = SilKit::Config::OpenFileWithSearchHints(include, configData.searchPaths); + SilKit::Config::Validate(nextConfig); + + // Load and Parse the file as Yaml + auto nextConfigNode = YAML::Load(nextConfig); + configData.configBuffer.push_back((ConfigInclude(include, SilKit::Config::Parse(nextConfigNode)))); + + // Append the config to our metadata buffer, so we can make informed decisions whether the compiled config is valid + configData.includeSet.insert(include); + AppendToSearchPaths(nextConfigNode, configData); + + // Collect Caches and Include for the next level within the tree + CollectIncludes(nextConfigNode, tmpIncludes); + PopulateCaches(nextConfigNode, configData); + } + + // Goto next Level + levelIncludes = tmpIncludes; + + if (levelIncludes.size() == 0) + { + break; + } + } +} + +auto ParticipantConfigurationFromXImpl(const std::string& text, + struct ConfigIncludeData& configData) -> SilKit::Config::ParticipantConfiguration +{ + SilKit::Config::Validate(text); + YAML::Node doc = YAML::Load(text); + + auto configuration = SilKit::Config::Parse(doc); + configData.configBuffer.push_back(ConfigInclude("root", configuration)); + + // Check search Paths + if (doc["Includes"]) + { + AppendToSearchPaths(doc, configData); + } + + // Get all configs + ProcessIncludes(doc, configData); + // Merge the root and included configs + return MergeConfigs(configData); +} + + } // anonymous namespace // ================================================================================ @@ -79,7 +572,8 @@ auto Parse(const std::string& text) -> SilKit::Config::ParticipantConfiguration // ================================================================================ bool operator==(const CanController& lhs, const CanController& rhs) { - return lhs.name == rhs.name && lhs.network == rhs.network; + return lhs.name == rhs.name && lhs.network == rhs.network && lhs.replay == rhs.replay + && lhs.useTraceSinks == rhs.useTraceSinks; } bool operator==(const LinController& lhs, const LinController& rhs) @@ -155,22 +649,38 @@ bool operator==(const ParticipantConfiguration& lhs, const ParticipantConfigurat && lhs.tracing == rhs.tracing && lhs.extensions == rhs.extensions; } -} // inline namespace v1 +} // namespace v1 + +// ============================================================================ +// Interface Layer functions +// ============================================================================ auto ParticipantConfigurationFromStringImpl(const std::string& text) --> std::shared_ptr + -> std::shared_ptr { - auto configuration = SilKit::Config::Parse(text); - + auto configData = ConfigIncludeData(); + auto configuration = SilKit::Config::ParticipantConfigurationFromXImpl(text, configData); return std::make_shared(std::move(configuration)); } auto ParticipantConfigurationFromFileImpl(const std::string& filename) --> std::shared_ptr + -> std::shared_ptr { - auto text = SilKit::Config::ReadFile(filename); - auto configuration = SilKit::Config::Parse(text); + auto configData = ConfigIncludeData(); + configData.searchPaths.insert(SilKit::Config::GetConfigParentPath(filename)); + + // Parse the root config + std::string text; + try + { + text = SilKit::Config::OpenFileWithSearchHints(filename, configData.searchPaths); + } + catch (...) + { + throw; + } + auto configuration = SilKit::Config::ParticipantConfigurationFromXImpl(text, configData); return std::make_shared(std::move(configuration)); } diff --git a/SilKit/source/config/SilKitYamlHelper.hpp b/SilKit/source/config/SilKitYamlHelper.hpp index 70ac6cb71..fddd094f4 100644 --- a/SilKit/source/config/SilKitYamlHelper.hpp +++ b/SilKit/source/config/SilKitYamlHelper.hpp @@ -38,11 +38,21 @@ using namespace SilKit::Config; template struct ParseTypeName { - static constexpr const char* Name() { return "Unknown Type"; } + static constexpr const char* Name() + { + return "Unknown Type"; + } }; #define DEFINE_SILKIT_PARSE_TYPE_NAME(TYPE) \ - template<> struct ParseTypeName { static constexpr const char* Name(){ return #TYPE;} } + template <> \ + struct ParseTypeName \ + { \ + static constexpr const char* Name() \ + { \ + return #TYPE; \ + } \ + } template struct ParseTypeName> @@ -57,14 +67,17 @@ struct ParseTypeName> struct Converter { // required for YAML::convert: - template + template static Node encode(const SilKitDataType& obj); - template + template static bool decode(const Node& node, SilKitDataType& obj); }; -#define DEFINE_SILKIT_CONVERT(TYPE)\ - template<> struct convert : public Converter { };\ +#define DEFINE_SILKIT_CONVERT(TYPE) \ + template <> \ + struct convert : public Converter \ + { \ + }; \ DEFINE_SILKIT_PARSE_TYPE_NAME(TYPE) // Other types used for parsing, required in ConversionError for helpful error messages @@ -123,8 +136,9 @@ auto parse_as(const YAML::Node& node) -> ValueT // Utility functions to encode/decode optional elements -template::value || std::is_same::value), bool>::type = true> +template ::value || std::is_same::value), + bool>::type = true> void optional_encode(const Util::Optional& value, YAML::Node& node, const std::string& fieldName) { if (value.has_value()) @@ -133,8 +147,9 @@ void optional_encode(const Util::Optional& value, YAML::Node& node, con } } -template::value || std::is_same::value), bool>::type = true> +template ::value || std::is_same::value), + bool>::type = true> void optional_encode(const SilKit::Util::Optional& value, YAML::Node& node, const std::string& fieldName) { if (value.has_value()) @@ -143,7 +158,7 @@ void optional_encode(const SilKit::Util::Optional& value, YAML::Node& n } } -template +template void optional_encode(const std::vector& value, YAML::Node& node, const std::string& fieldName) { if (value.size() > 0) @@ -153,7 +168,7 @@ void optional_encode(const std::vector& value, YAML::Node& node, const } -template +template void optional_decode(Util::Optional& value, const YAML::Node& node, const std::string& fieldName) { if (node.IsMap() && node[fieldName]) //operator[] does not modify node @@ -162,7 +177,7 @@ void optional_decode(Util::Optional& value, const YAML::Node& node, con } } -template +template void optional_decode(ConfigT& value, const YAML::Node& node, const std::string& fieldName) { if (node.IsMap() && node[fieldName]) //operator[] does not modify node @@ -179,9 +194,8 @@ void optional_decode_deprecated_alternative(ConfigT& value, const YAML::Node& no { std::vector presentDeprecatedFieldNames; std::copy_if(deprecatedFieldNames.begin(), deprecatedFieldNames.end(), - std::back_inserter(presentDeprecatedFieldNames), [&node](const auto& deprecatedFieldName) { - return node[deprecatedFieldName]; - }); + std::back_inserter(presentDeprecatedFieldNames), + [&node](const auto& deprecatedFieldName) { return node[deprecatedFieldName]; }); if (node[fieldName] && presentDeprecatedFieldNames.size() >= 1) { @@ -217,7 +231,7 @@ void optional_decode_deprecated_alternative(ConfigT& value, const YAML::Node& no template auto non_default_encode(const std::vector& values, YAML::Node& node, const std::string& fieldName, - const std::vector& defaultValue) + const std::vector& defaultValue) { // Only encode vectors that have members that deviate from a default-value. // And also ensure we only encode values that are user-defined. @@ -242,7 +256,7 @@ auto non_default_encode(const std::vector& values, YAML::Node& node, co template auto non_default_encode(const ConfigT& value, YAML::Node& node, const std::string& fieldName, - const ConfigT& defaultValue) + const ConfigT& defaultValue) { if (!(value == defaultValue)) { diff --git a/SilKit/source/config/TestParticipantConfigs/AdditionalSubIncludes.yaml b/SilKit/source/config/TestParticipantConfigs/AdditionalSubIncludes.yaml new file mode 100644 index 000000000..7a63db6f6 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/AdditionalSubIncludes.yaml @@ -0,0 +1,12 @@ +--- +Description: Additional Subs +schemaVersion: 0 +DataSubscribers: +- Name: Subscriber1 + Topic: Temperature + UseTraceSinks: + - Sink1 +- Name: Subscriber2 + Topic: Temperature + UseTraceSinks: + - Sink2 diff --git a/SilKit/source/config/TestParticipantConfigs/CanInclude2.yaml b/SilKit/source/config/TestParticipantConfigs/CanInclude2.yaml new file mode 100644 index 000000000..62eee8614 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/CanInclude2.yaml @@ -0,0 +1,3 @@ +--- +Description: Example include configuration for CAN Controllers +schemaVersion: 0 diff --git a/SilKit/source/config/TestParticipantConfigs/CanInclude3.yaml b/SilKit/source/config/TestParticipantConfigs/CanInclude3.yaml new file mode 100644 index 000000000..cded810c7 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/CanInclude3.yaml @@ -0,0 +1,7 @@ +--- +Description: Example Level2 Include for CAN Controllers +Includes: + Files: + - CanIncludes.yaml + - CanInclude4.yaml + - CanInclude5.yaml diff --git a/SilKit/source/config/TestParticipantConfigs/CanInclude4.yaml b/SilKit/source/config/TestParticipantConfigs/CanInclude4.yaml new file mode 100644 index 000000000..8e2dca181 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/CanInclude4.yaml @@ -0,0 +1,5 @@ +--- +Description: Example Level3 Include for CAN Controllers +Includes: + Files: + - CanInclude6.yaml diff --git a/SilKit/source/config/TestParticipantConfigs/CanInclude5.yaml b/SilKit/source/config/TestParticipantConfigs/CanInclude5.yaml new file mode 100644 index 000000000..7c812c7f0 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/CanInclude5.yaml @@ -0,0 +1,14 @@ +--- +Description: Example Level2 Include for CAN Controllers +CanControllers: +- Name: CAN64 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel64 + ChannelPath: path/to/myTestChannel64 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup64 + GroupSource: MyTestGroup diff --git a/SilKit/source/config/TestParticipantConfigs/CanInclude6.yaml b/SilKit/source/config/TestParticipantConfigs/CanInclude6.yaml new file mode 100644 index 000000000..d53f6cb30 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/CanInclude6.yaml @@ -0,0 +1,2 @@ +--- +Description: Example Level4 configuration for CAN Controllers diff --git a/SilKit/source/config/TestParticipantConfigs/CanIncludes.yaml b/SilKit/source/config/TestParticipantConfigs/CanIncludes.yaml new file mode 100644 index 000000000..0e0cfdf72 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/CanIncludes.yaml @@ -0,0 +1,23 @@ +--- +Description: Example include configuration for CAN Controllers +Includes: + Files: + - CanIncludes.yaml + - CanInclude2.yaml + - CanInclude3.yaml +CanControllers: +- Name: CAN1 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - Sink1 +- Name: MyCAN2 + Network: CAN2 diff --git a/SilKit/source/config/TestParticipantConfigs/DuplicateEthernetControllerNames.yaml b/SilKit/source/config/TestParticipantConfigs/DuplicateEthernetControllerNames.yaml new file mode 100644 index 000000000..01cc18f50 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/DuplicateEthernetControllerNames.yaml @@ -0,0 +1,17 @@ +--- +Description: Example configuration EthernetControllers with name +schemaVersion: 0 +EthernetControllers: +- Name: ETH0 + Replay: + UseTraceSource: Source1 + Direction: Receive + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - MyTraceSink1 diff --git a/SilKit/source/config/TestParticipantConfigs/ExtensionsIncludes.yaml b/SilKit/source/config/TestParticipantConfigs/ExtensionsIncludes.yaml new file mode 100644 index 000000000..73ee70c41 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/ExtensionsIncludes.yaml @@ -0,0 +1,8 @@ +--- +Description: Example included configs for Extension +Extensions: + SearchPathHints: + - path/to/extensions1 + - path/to/extensions3 + - path/to/extensions4 + - path/to/extensions5 diff --git a/SilKit/source/config/TestParticipantConfigs/LoggingIncludes.yaml b/SilKit/source/config/TestParticipantConfigs/LoggingIncludes.yaml new file mode 100644 index 000000000..5260f09a9 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/LoggingIncludes.yaml @@ -0,0 +1,9 @@ +--- +Description: Example include Logging configuration +Logging: + Sinks: + - Type: File + Level: Critical + LogName: MyLog2 + - Type: Stdout + Level: Trace diff --git a/SilKit/source/config/TestParticipantConfigs/MiddlewareInclude.yaml b/SilKit/source/config/TestParticipantConfigs/MiddlewareInclude.yaml new file mode 100644 index 000000000..15067c705 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/MiddlewareInclude.yaml @@ -0,0 +1,12 @@ +--- +Description: Example Middleware config include to test YAML Parser +schemaVersion: 0 +Includes: + Files: + - MoreMiddlewareIncludes.yaml +Middleware: + RegistryUri: silkit://example.com:1234 + ConnectAttempts: 12 + TcpNoDelay: true + TcpQuickAck: true + EnableDomainSockets: false diff --git a/SilKit/source/config/TestParticipantConfigs/MoreMiddlewareIncludes.yaml b/SilKit/source/config/TestParticipantConfigs/MoreMiddlewareIncludes.yaml new file mode 100644 index 000000000..837c53d61 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/MoreMiddlewareIncludes.yaml @@ -0,0 +1,6 @@ +--- +Description: Example Middleware config include to test YAML Parser +schemaVersion: 0 +Middleware: + TcpSendBufferSize: 3456 + TcpReceiveBufferSize: 3456 diff --git a/SilKit/source/config/TestParticipantConfigs/MultipleAcceptorUrisInclude.yaml b/SilKit/source/config/TestParticipantConfigs/MultipleAcceptorUrisInclude.yaml new file mode 100644 index 000000000..2add952e0 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/MultipleAcceptorUrisInclude.yaml @@ -0,0 +1,7 @@ +--- +Description: Example configuration Middleware with AcceptorURIS +Middleware: + AcceptorUris: + - The/Fourth/Uri/Found + ConnectAttempts: 9 + EnableDomainSockets: false diff --git a/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_DuplicateControllerNames.yaml b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_DuplicateControllerNames.yaml new file mode 100644 index 000000000..fc3d4f2d9 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_DuplicateControllerNames.yaml @@ -0,0 +1,20 @@ +--- +Description: Example configuration to test a broken configuration with duplicate Controller Names +schemaVersion: 0 +Includes: + Files: + - DuplicateEthernetControllerNames.yaml +EthernetControllers: +- Name: ETH0 + Replay: + UseTraceSource: Source2 + Direction: Send + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - MyTraceSink2 diff --git a/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FromString_Reference.yaml b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FromString_Reference.yaml new file mode 100644 index 000000000..cf2e11ae7 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FromString_Reference.yaml @@ -0,0 +1,18 @@ +--- +Description: Example include configuration for CAN Controllers +CanControllers: +- Name: CAN1 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - Sink1 +- Name: MyCAN2 + Network: CAN2 diff --git a/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FullIncludes.yaml b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FullIncludes.yaml new file mode 100644 index 000000000..86ebfee6b --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FullIncludes.yaml @@ -0,0 +1,160 @@ +--- +Description: Example configuration to test YAML Parser +schemaVersion: 0 +Includes: + SearchPathHints: + - ConfigSnippets/CAN + - ConfigSnippets/Middleware + Files: + - CanIncludes.yaml + - ExtensionsIncludes.yaml + - LoggingIncludes.yaml + - MiddlewareInclude.yaml +ParticipantName: Node0 +LinControllers: +- Name: SimpleEcu1_LIN1 + Network: LIN1 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - MyTraceSink1 +EthernetControllers: +- Name: ETH0 + Replay: + UseTraceSource: Source1 + Direction: Receive + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - MyTraceSink1 +FlexrayControllers: +- ClusterParameters: + gColdstartAttempts: 8 + gCycleCountMax: 63 + gListenNoise: 2 + gMacroPerCycle: 3636 + gMaxWithoutClockCorrectionFatal: 2 + gMaxWithoutClockCorrectionPassive: 2 + gNumberOfMiniSlots: 291 + gNumberOfStaticSlots: 70 + gPayloadLengthStatic: 16 + gSyncFrameIDCountMax: 15 + gdActionPointOffset: 2 + gdDynamicSlotIdlePhase: 1 + gdMiniSlot: 5 + gdMiniSlotActionPointOffset: 2 + gdStaticSlot: 31 + gdSymbolWindow: 1 + gdSymbolWindowActionPointOffset: 1 + gdTSSTransmitter: 9 + gdWakeupTxActive: 60 + gdWakeupTxIdle: 180 + Name: FlexRay1 + NodeParameters: + pAllowHaltDueToClock: 1 + pAllowPassiveToActive: 0 + pChannels: AB + pClusterDriftDamping: 2 + pKeySlotId: 10 + pKeySlotOnlyEnabled: 0 + pKeySlotUsedForStartup: 1 + pKeySlotUsedForSync: 0 + pLatestTx: 249 + pMacroInitialOffsetA: 3 + pMacroInitialOffsetB: 3 + pMicroInitialOffsetA: 6 + pMicroInitialOffsetB: 6 + pMicroPerCycle: 200000 + pOffsetCorrectionOut: 127 + pOffsetCorrectionStart: 3632 + pRateCorrectionOut: 81 + pSamplesPerMicrotick: 2 + pWakeupChannel: A + pWakeupPattern: 33 + pdAcceptedStartupRange: 212 + pdListenTimeout: 400162 + pdMicrotick: 25ns + TxBufferConfigurations: + - channels: A + headerCrc: 0 + offset: 0 + PPindicator: false + repetition: 0 + slotId: 0 + transmissionMode: Continuous + Replay: + Direction: Send + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSource: Source1 + UseTraceSinks: + - Sink1 +DataPublishers: +- Name: Publisher1 + Topic: Temperature + UseTraceSinks: + - Sink1 +DataSubscribers: +- Name: Subscriber3 + Topic: Temperature + UseTraceSinks: + - Sink1 +- Name: Subscriber1 + Topic: Temperature + UseTraceSinks: + - Sink1 +- Name: Subscriber2 + Topic: Temperature + UseTraceSinks: + - Sink2 +RpcServers: +- Name: Server1 + FunctionName: Function1 + UseTraceSinks: + - Sink1 +RpcClients: +- Name: Client1 + FunctionName: Function1 + UseTraceSinks: + - Sink1 +Logging: + Sinks: + - Type: File + Level: Critical + LogName: MyLog1 + FlushLevel: Warn + LogFromRemotes: false +HealthCheck: + SoftResponseTimeout: 500 + HardResponseTimeout: 5000 +Tracing: + TraceSinks: + - Name: Sink1 + OutputPath: FlexrayDemo_node0.mf4 + Type: Mdf4File + TraceSources: + - Name: Source1 + InputPath: path/to/Source1.mf4 + Type: Mdf4File +Extensions: + SearchPathHints: + - path/to/extensions1 + - path/to/extensions2 diff --git a/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FullIncludes_Reference.yaml b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FullIncludes_Reference.yaml new file mode 100644 index 000000000..d552e3d92 --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_FullIncludes_Reference.yaml @@ -0,0 +1,195 @@ +--- +Description: Example configuration to test YAML Parser +schemaVersion: 0 +ParticipantName: Node0 +CanControllers: +- Name: CAN1 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - Sink1 +- Name: MyCAN2 + Network: CAN2 +- Name: CAN64 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel64 + ChannelPath: path/to/myTestChannel64 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup64 + GroupSource: MyTestGroup +LinControllers: +- Name: SimpleEcu1_LIN1 + Network: LIN1 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - MyTraceSink1 +EthernetControllers: +- Name: ETH0 + Replay: + UseTraceSource: Source1 + Direction: Receive + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - MyTraceSink1 +FlexrayControllers: +- ClusterParameters: + gColdstartAttempts: 8 + gCycleCountMax: 63 + gListenNoise: 2 + gMacroPerCycle: 3636 + gMaxWithoutClockCorrectionFatal: 2 + gMaxWithoutClockCorrectionPassive: 2 + gNumberOfMiniSlots: 291 + gNumberOfStaticSlots: 70 + gPayloadLengthStatic: 16 + gSyncFrameIDCountMax: 15 + gdActionPointOffset: 2 + gdDynamicSlotIdlePhase: 1 + gdMiniSlot: 5 + gdMiniSlotActionPointOffset: 2 + gdStaticSlot: 31 + gdSymbolWindow: 1 + gdSymbolWindowActionPointOffset: 1 + gdTSSTransmitter: 9 + gdWakeupTxActive: 60 + gdWakeupTxIdle: 180 + Name: FlexRay1 + NodeParameters: + pAllowHaltDueToClock: 1 + pAllowPassiveToActive: 0 + pChannels: AB + pClusterDriftDamping: 2 + pKeySlotId: 10 + pKeySlotOnlyEnabled: 0 + pKeySlotUsedForStartup: 1 + pKeySlotUsedForSync: 0 + pLatestTx: 249 + pMacroInitialOffsetA: 3 + pMacroInitialOffsetB: 3 + pMicroInitialOffsetA: 6 + pMicroInitialOffsetB: 6 + pMicroPerCycle: 200000 + pOffsetCorrectionOut: 127 + pOffsetCorrectionStart: 3632 + pRateCorrectionOut: 81 + pSamplesPerMicrotick: 2 + pWakeupChannel: A + pWakeupPattern: 33 + pdAcceptedStartupRange: 212 + pdListenTimeout: 400162 + pdMicrotick: 25ns + TxBufferConfigurations: + - channels: A + headerCrc: 0 + offset: 0 + PPindicator: false + repetition: 0 + slotId: 0 + transmissionMode: Continuous + Replay: + Direction: Send + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSource: Source1 + UseTraceSinks: + - Sink1 +DataPublishers: +- Name: Publisher1 + Topic: Temperature + UseTraceSinks: + - Sink1 +DataSubscribers: +- Name: Subscriber3 + Topic: Temperature + UseTraceSinks: + - Sink1 +- Name: Subscriber1 + Topic: Temperature + UseTraceSinks: + - Sink1 +- Name: Subscriber2 + Topic: Temperature + UseTraceSinks: + - Sink2 +RpcServers: +- Name: Server1 + FunctionName: Function1 + UseTraceSinks: + - Sink1 +RpcClients: +- Name: Client1 + FunctionName: Function1 + UseTraceSinks: + - Sink1 +Logging: + Sinks: + - Type: File + Level: Critical + LogName: MyLog1 + - Type: Stdout + Level: Trace + - Type: File + Level: Critical + LogName: MyLog2 + FlushLevel: Warn + LogFromRemotes: false +HealthCheck: + SoftResponseTimeout: 500 + HardResponseTimeout: 5000 +Tracing: + TraceSinks: + - Name: Sink1 + OutputPath: FlexrayDemo_node0.mf4 + Type: Mdf4File + TraceSources: + - Name: Source1 + InputPath: path/to/Source1.mf4 + Type: Mdf4File +Extensions: + SearchPathHints: + - path/to/extensions1 + - path/to/extensions2 + - path/to/extensions1 + - path/to/extensions3 + - path/to/extensions4 + - path/to/extensions5 +Middleware: + RegistryUri: silkit://example.com:1234 + ConnectAttempts: 12 + TcpNoDelay: true + TcpQuickAck: true + EnableDomainSockets: false + TcpSendBufferSize: 3456 + TcpReceiveBufferSize: 3456 diff --git a/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_MultipleAcceptorUris.yaml b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_MultipleAcceptorUris.yaml new file mode 100644 index 000000000..53ae4d65f --- /dev/null +++ b/SilKit/source/config/TestParticipantConfigs/ParticipantConfiguration_MultipleAcceptorUris.yaml @@ -0,0 +1,14 @@ +--- +Description: Example configuration to test a broken configuration with multiple AcceptorURIs +schemaVersion: 0 +Includes: + Files: + - MultipleAcceptorUrisInclude.yaml +Middleware: + AcceptorUris: + - The/First/Uri/Found + - The/Second/Uri/Found + - The/Third/Uri/Found + RegistryUri: silkit://example.com:1234 + ConnectAttempts: 9 + EnableDomainSockets: false diff --git a/SilKit/source/config/Test_ParticipantConfiguration.cpp b/SilKit/source/config/Test_ParticipantConfiguration.cpp index 352107c3c..1dff1e549 100644 --- a/SilKit/source/config/Test_ParticipantConfiguration.cpp +++ b/SilKit/source/config/Test_ParticipantConfiguration.cpp @@ -61,8 +61,9 @@ class Test_ParticipantConfiguration : public testing::Test TEST_F(Test_ParticipantConfiguration, throw_if_logging_is_configured_without_filename) { - EXPECT_THROW(SilKit::Config::ParticipantConfigurationFromFileImpl("ParticipantConfiguration_Logging_Without_File.json"), - SilKit::ConfigurationError); + EXPECT_THROW( + SilKit::Config::ParticipantConfigurationFromFileImpl("ParticipantConfiguration_Logging_Without_File.json"), + SilKit::ConfigurationError); } TEST_F(Test_ParticipantConfiguration, minimal_configuration_file) @@ -77,6 +78,135 @@ TEST_F(Test_ParticipantConfiguration, full_configuration_file) CreateParticipantFromConfiguration(cfg); } +TEST_F(Test_ParticipantConfiguration, full_configuration_file_with_includes) +{ + auto cfg = SilKit::Config::ParticipantConfigurationFromFileImpl("ParticipantConfiguration_FullIncludes.yaml"); + auto ref_cfg = + SilKit::Config::ParticipantConfigurationFromFileImpl("ParticipantConfiguration_FullIncludes_Reference.yaml"); + + // cast to ParticipantConfiguration to use right equal operator + auto participantConfig = *std::dynamic_pointer_cast(cfg); + auto participantConfigRef = *std::dynamic_pointer_cast(ref_cfg); + + ASSERT_TRUE(participantConfig == participantConfigRef); +} + +TEST_F(Test_ParticipantConfiguration, participant_config_multiple_acceptor_uris) +{ + EXPECT_THROW( + SilKit::Config::ParticipantConfigurationFromFileImpl("ParticipantConfiguration_MultipleAcceptorUris.yaml"), + SilKit::ConfigurationError); +} + +TEST_F(Test_ParticipantConfiguration, participant_config_duplicate_controller_names) +{ + EXPECT_THROW( + SilKit::Config::ParticipantConfigurationFromFileImpl("ParticipantConfiguration_DuplicateControllerNames.yaml"), + SilKit::ConfigurationError); +} + +TEST_F(Test_ParticipantConfiguration, participant_config_from_string) +{ + const auto configString = R"raw( +--- +Description: Example include configuration for CAN Controllers +CanControllers: +- Name: CAN1 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - Sink1 +- Name: MyCAN2 + Network: CAN2 + )raw"; + + auto cfg = SilKit::Config::ParticipantConfigurationFromStringImpl(configString); + auto ref_cfg = + SilKit::Config::ParticipantConfigurationFromFileImpl("ParticipantConfiguration_FromString_Reference.yaml"); + + // cast to ParticipantConfiguration to use right equal operator + auto participantConfig = *std::dynamic_pointer_cast(cfg); + auto participantConfigRef = *std::dynamic_pointer_cast(ref_cfg); + + ASSERT_TRUE(participantConfig == participantConfigRef); +} +TEST_F(Test_ParticipantConfiguration, participant_config_from_string_includes) +{ + const auto configString = R"raw( +--- +Description: Example include configuration for CAN Controllers +Includes: + SearchPathHints: + - ConfigSnippets/CAN + Files: + - CanInclude5.yaml +CanControllers: +- Name: CAN1 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - Sink1 +- Name: MyCAN2 + Network: CAN2 + )raw"; + + const auto configStringRef = R"raw( +--- +Description: Example include configuration for CAN Controllers +CanControllers: +- Name: CAN1 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel1 + ChannelPath: path/to/myTestChannel1 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup1 + GroupSource: MyTestGroup + UseTraceSinks: + - Sink1 +- Name: MyCAN2 + Network: CAN2 +- Name: CAN64 + Replay: + UseTraceSource: Source1 + Direction: Both + MdfChannel: + ChannelName: MyTestChannel64 + ChannelPath: path/to/myTestChannel64 + ChannelSource: MyTestChannel + GroupName: MyTestGroup + GroupPath: path/to/myTestGroup64 + GroupSource: MyTestGroup + )raw"; + + auto cfg = SilKit::Config::ParticipantConfigurationFromStringImpl(configString); + auto cfgRef = SilKit::Config::ParticipantConfigurationFromStringImpl(configStringRef); + + // cast to ParticipantConfiguration to use right equal operator + auto config = *std::dynamic_pointer_cast(cfg); + auto configRef = *std::dynamic_pointer_cast(cfgRef); + ASSERT_TRUE(config == configRef); +} + /* Test whether json and yaml configurations are parsed equivalently */ diff --git a/SilKit/source/config/Test_YamlParser.cpp b/SilKit/source/config/Test_YamlParser.cpp index fa6bdd73a..95c47ca5c 100644 --- a/SilKit/source/config/Test_YamlParser.cpp +++ b/SilKit/source/config/Test_YamlParser.cpp @@ -221,13 +221,13 @@ TEST_F(Test_YamlParser, yaml_complete_configuration) EXPECT_TRUE(config.canControllers.at(0).name == "CAN1"); EXPECT_TRUE(!config.canControllers.at(0).network.has_value()); EXPECT_TRUE(config.canControllers.at(1).name == "MyCAN2"); - EXPECT_TRUE(config.canControllers.at(1).network.has_value() && - config.canControllers.at(1).network.value() == "CAN2"); + EXPECT_TRUE(config.canControllers.at(1).network.has_value() + && config.canControllers.at(1).network.value() == "CAN2"); EXPECT_TRUE(config.linControllers.size() == 1); EXPECT_TRUE(config.linControllers.at(0).name == "SimpleEcu1_LIN1"); - EXPECT_TRUE(config.linControllers.at(0).network.has_value() && - config.linControllers.at(0).network.value() == "LIN1"); + EXPECT_TRUE(config.linControllers.at(0).network.has_value() + && config.linControllers.at(0).network.value() == "LIN1"); EXPECT_TRUE(config.flexrayControllers.size() == 1); EXPECT_TRUE(config.flexrayControllers.at(0).name == "FlexRay1"); @@ -235,8 +235,8 @@ TEST_F(Test_YamlParser, yaml_complete_configuration) EXPECT_TRUE(config.dataPublishers.size() == 1); EXPECT_TRUE(config.dataPublishers.at(0).name == "Publisher1"); - EXPECT_TRUE(config.dataPublishers.at(0).topic.has_value() && - config.dataPublishers.at(0).topic.value() == "Temperature"); + EXPECT_TRUE(config.dataPublishers.at(0).topic.has_value() + && config.dataPublishers.at(0).topic.value() == "Temperature"); EXPECT_TRUE(config.logging.sinks.size() == 1); EXPECT_TRUE(config.logging.sinks.at(0).type == Sink::Type::File); @@ -275,17 +275,19 @@ const auto emptyConfiguration = R"raw( TEST_F(Test_YamlParser, yaml_empty_configuration) { auto node = YAML::Load(emptyConfiguration); - EXPECT_THROW({ - try + EXPECT_THROW( { - node.as(); - } - catch (const YAML::TypedBadConversion& e) - { - EXPECT_STREQ("bad conversion", e.what()); - throw; - } - }, YAML::TypedBadConversion); + try + { + node.as(); + } + catch (const YAML::TypedBadConversion& e) + { + EXPECT_STREQ("bad conversion", e.what()); + throw; + } + }, + YAML::TypedBadConversion); } const auto minimalConfiguration = R"raw( @@ -302,13 +304,13 @@ TEST_F(Test_YamlParser, yaml_minimal_configuration) TEST_F(Test_YamlParser, yaml_native_type_conversions) { { - uint16_t a{ 0x815 }; + uint16_t a{0x815}; auto node = to_yaml(a); uint16_t b = from_yaml(node); EXPECT_TRUE(a == b); } { - std::vector vec{ 0,1,3,4,5 }; + std::vector vec{0, 1, 3, 4, 5}; auto node = to_yaml(vec); auto vec2 = from_yaml>(node); EXPECT_TRUE(vec == vec2); @@ -380,8 +382,7 @@ TEST_F(Test_YamlParser, middleware_convert) TEST_F(Test_YamlParser, map_serdes) { std::map mapin{ - {"keya", "vala"}, {"keyb", "valb"}, {"keyc", ""}, {"", "vald"}, - {"keye\nwithlinebreak", "vale\nwithlinebreak"}}; + {"keya", "vala"}, {"keyb", "valb"}, {"keyc", ""}, {"", "vald"}, {"keye\nwithlinebreak", "vale\nwithlinebreak"}}; auto mapstr = SilKit::Config::Serialize>(mapin); auto mapout = SilKit::Config::Deserialize>(mapstr); EXPECT_EQ(mapin, mapout); diff --git a/SilKit/source/config/Test_YamlValidator.cpp b/SilKit/source/config/Test_YamlValidator.cpp index 72c7cad3d..5fd54a957 100644 --- a/SilKit/source/config/Test_YamlValidator.cpp +++ b/SilKit/source/config/Test_YamlValidator.cpp @@ -27,6 +27,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "gmock/gmock.h" #include "gtest/gtest.h" +#include + namespace { class Test_YamlValidator : public testing::Test @@ -135,7 +137,7 @@ Description: foo YamlValidator validator; bool yamlValid = validator.Validate(yamlString, warnings); EXPECT_FALSE(yamlValid) << "YamlValidator warnings: " << warnings.str(); - std::cout << "YamlValidator warnings: " << warnings.str() < 0); } diff --git a/SilKit/source/config/Validation.cpp b/SilKit/source/config/Validation.cpp index 9e7049411..24b75a692 100644 --- a/SilKit/source/config/Validation.cpp +++ b/SilKit/source/config/Validation.cpp @@ -42,28 +42,27 @@ void ValidateTraceSinks(const SilKit::Config::v1::ParticipantConfiguration& conf { if (sink.name.empty()) { - throw SilKit::ConfigurationError{ "On Participant " + configuration.participantName + - ": TraceSink \"Name\" must not be empty!" }; + throw SilKit::ConfigurationError{"On Participant " + configuration.participantName + + ": TraceSink \"Name\" must not be empty!"}; } if (sink.outputPath.empty()) { - throw SilKit::ConfigurationError{ "On Participant " + configuration.participantName + - ": TraceSink \"OutputPath\" must not be empty!" }; + throw SilKit::ConfigurationError{"On Participant " + configuration.participantName + + ": TraceSink \"OutputPath\" must not be empty!"}; } sinkNames.insert(sink.name); } if (sinkNames.size() != configuration.tracing.traceSinks.size()) { - throw SilKit::ConfigurationError{ "TraceSinks must have unique names!" }; + throw SilKit::ConfigurationError{"TraceSinks must have unique names!"}; } auto sinkExists = [&sinkNames](const auto& name) -> bool { return std::end(sinkNames) != std::find(sinkNames.cbegin(), sinkNames.cend(), name); }; - auto validateController = [&](const auto& controllers) - { + auto validateController = [&](const auto& controllers) { for (const auto& controller : controllers) { std::stringstream ss; @@ -74,12 +73,12 @@ void ValidateTraceSinks(const SilKit::Config::v1::ParticipantConfiguration& conf if (traceSink.empty()) { ss << "has an empty string in a UseTraceSinks field!"; - throw SilKit::ConfigurationError{ ss.str() }; + throw SilKit::ConfigurationError{ss.str()}; } if (!sinkExists(traceSink)) { ss << "has a UseTraceSinks field which refers to a non-existing TraceSink: " << traceSink; - throw SilKit::ConfigurationError{ ss.str() }; + throw SilKit::ConfigurationError{ss.str()}; } } } @@ -102,20 +101,20 @@ void ValidateTraceSources(const SilKit::Config::v1::ParticipantConfiguration& co { if (source.name.empty()) { - throw SilKit::ConfigurationError{ "On Participant " + configuration.participantName + - ": TraceSource \"Name\" must not be empty!" }; + throw SilKit::ConfigurationError{"On Participant " + configuration.participantName + + ": TraceSource \"Name\" must not be empty!"}; } if (source.inputPath.empty()) { - throw SilKit::ConfigurationError{ "On Participant " + configuration.participantName + - ": TraceSource \"InputPath\" must not be empty!" }; + throw SilKit::ConfigurationError{"On Participant " + configuration.participantName + + ": TraceSource \"InputPath\" must not be empty!"}; } auto ok = sourceNames.insert(source.name); if (!ok.second) { - throw SilKit::ConfigurationError{ "TraceSources must have a unique name: duplicate entry is " + source.name }; + throw SilKit::ConfigurationError{"TraceSources must have a unique name: duplicate entry is " + source.name}; } } @@ -123,8 +122,7 @@ void ValidateTraceSources(const SilKit::Config::v1::ParticipantConfiguration& co return std::end(sourceNames) != std::find(sourceNames.cbegin(), sourceNames.cend(), name); }; - auto validateController = [&](const auto& controllers) - { + auto validateController = [&](const auto& controllers) { for (const auto& controller : controllers) { std::stringstream ss; @@ -138,8 +136,8 @@ void ValidateTraceSources(const SilKit::Config::v1::ParticipantConfiguration& co if (!sourceExists(controller.replay.useTraceSource)) { ss << "has a Replay::UseTraceSource field which refers to a non-existing TraceSource: " - << controller.replay.useTraceSource; - throw SilKit::ConfigurationError{ ss.str() }; + << controller.replay.useTraceSource; + throw SilKit::ConfigurationError{ss.str()}; } } }; diff --git a/SilKit/source/config/YamlConversion.cpp b/SilKit/source/config/YamlConversion.cpp index a347b9379..900ac851b 100644 --- a/SilKit/source/config/YamlConversion.cpp +++ b/SilKit/source/config/YamlConversion.cpp @@ -46,35 +46,35 @@ void optional_encode(const Replay& value, YAML::Node& node, const std::string& f // YAML type conversion helpers for ParticipantConfiguration data types namespace YAML { -template<> +template <> Node Converter::encode(const std::chrono::milliseconds& obj) { Node node; node = obj.count(); return node; } -template<> +template <> bool Converter::decode(const Node& node, std::chrono::milliseconds& obj) { obj = std::chrono::milliseconds{parse_as(node)}; return true; } -template<> +template <> Node Converter::encode(const std::chrono::nanoseconds& obj) { Node node; node = obj.count(); return node; } -template<> +template <> bool Converter::decode(const Node& node, std::chrono::nanoseconds& obj) { obj = std::chrono::nanoseconds{parse_as(node)}; return true; } -template<> +template <> Node Converter::encode(const Logging& obj) { Node node; @@ -87,7 +87,7 @@ Node Converter::encode(const Logging& obj) return node; } -template<> +template <> bool Converter::decode(const Node& node, Logging& obj) { optional_decode(obj.logFromRemotes, node, "LogFromRemotes"); @@ -96,7 +96,7 @@ bool Converter::decode(const Node& node, Logging& obj) return true; } -template<> +template <> Node Converter::encode(const Sink& obj) { static const Sink defaultSink{}; @@ -107,7 +107,7 @@ Node Converter::encode(const Sink& obj) non_default_encode(obj.logName, node, "LogName", defaultSink.logName); return node; } -template<> +template <> bool Converter::decode(const Node& node, Sink& obj) { optional_decode(obj.type, node, "Type"); @@ -124,7 +124,7 @@ bool Converter::decode(const Node& node, Sink& obj) return true; } -template<> +template <> Node Converter::encode(const Sink::Type& obj) { Node node; @@ -144,7 +144,7 @@ Node Converter::encode(const Sink::Type& obj) } return node; } -template<> +template <> bool Converter::decode(const Node& node, Sink::Type& obj) { if (!node.IsScalar()) @@ -171,7 +171,7 @@ bool Converter::decode(const Node& node, Sink::Type& obj) return true; } -template<> +template <> Node Converter::encode(const Services::Logging::Level& obj) { Node node; @@ -201,13 +201,12 @@ Node Converter::encode(const Services::Logging::Level& obj) } return node; } -template<> +template <> bool Converter::decode(const Node& node, Services::Logging::Level& obj) { if (!node.IsScalar()) { - throw ConversionError(node, - "Level should be a string of Critical|Error|Warn|Info|Debug|Trace|Off."); + throw ConversionError(node, "Level should be a string of Critical|Error|Warn|Info|Debug|Trace|Off."); } auto&& str = parse_as(node); if (str == "Critical") @@ -231,7 +230,7 @@ bool Converter::decode(const Node& node, Services::Logging::Level& obj) return true; } -template<> +template <> Node Converter::encode(const MdfChannel& obj) { Node node; @@ -243,7 +242,7 @@ Node Converter::encode(const MdfChannel& obj) optional_encode(obj.groupSource, node, "GroupSource"); return node; } -template<> +template <> bool Converter::decode(const Node& node, MdfChannel& obj) { if (!node.IsMap()) @@ -259,7 +258,7 @@ bool Converter::decode(const Node& node, MdfChannel& obj) return true; } -template<> +template <> Node Converter::encode(const Replay& obj) { static const Replay defaultObj{}; @@ -269,7 +268,7 @@ Node Converter::encode(const Replay& obj) non_default_encode(obj.mdfChannel, node, "MdfChannel", defaultObj.mdfChannel); return node; } -template<> +template <> bool Converter::decode(const Node& node, Replay& obj) { obj.useTraceSource = parse_as(node["UseTraceSource"]); @@ -278,7 +277,7 @@ bool Converter::decode(const Node& node, Replay& obj) return true; } -template<> +template <> Node Converter::encode(const Replay::Direction& obj) { Node node; @@ -299,7 +298,7 @@ Node Converter::encode(const Replay::Direction& obj) } return node; } -template<> +template <> bool Converter::decode(const Node& node, Replay::Direction& obj) { auto&& str = parse_as(node); @@ -318,7 +317,7 @@ bool Converter::decode(const Node& node, Replay::Direction& obj) return true; } -template<> +template <> Node Converter::encode(const CanController& obj) { static const CanController defaultObj{}; @@ -329,7 +328,7 @@ Node Converter::encode(const CanController& obj) optional_encode(obj.replay, node, "Replay"); return node; } -template<> +template <> bool Converter::decode(const Node& node, CanController& obj) { obj.name = parse_as(node["Name"]); @@ -339,7 +338,7 @@ bool Converter::decode(const Node& node, CanController& obj) return true; } -template<> +template <> Node Converter::encode(const LinController& obj) { static const LinController defaultObj{}; @@ -350,7 +349,7 @@ Node Converter::encode(const LinController& obj) optional_encode(obj.replay, node, "Replay"); return node; } -template<> +template <> bool Converter::decode(const Node& node, LinController& obj) { obj.name = parse_as(node["Name"]); @@ -360,7 +359,7 @@ bool Converter::decode(const Node& node, LinController& obj) return true; } -template<> +template <> Node Converter::encode(const EthernetController& obj) { static const EthernetController defaultObj{}; @@ -372,7 +371,7 @@ Node Converter::encode(const EthernetController& obj) return node; } -template<> +template <> bool Converter::decode(const Node& node, EthernetController& obj) { obj.name = parse_as(node["Name"]); @@ -382,7 +381,7 @@ bool Converter::decode(const Node& node, EthernetController& obj) return true; } -template<> +template <> Node Converter::encode(const Services::Flexray::FlexrayClusterParameters& obj) { Node node; @@ -409,12 +408,11 @@ Node Converter::encode(const Services::Flexray::FlexrayClusterParameters& obj) node["gSyncFrameIDCountMax"] = static_cast(obj.gSyncFrameIDCountMax); return node; } -template<> +template <> bool Converter::decode(const Node& node, Services::Flexray::FlexrayClusterParameters& obj) { // Parse parameters as an int value; uint8_t would be interpreted as a character - auto parseInt = [&node](auto instance, auto name) - { + auto parseInt = [&node](auto instance, auto name) { return static_cast(parse_as(node[name])); }; obj.gColdstartAttempts = parseInt(obj.gColdstartAttempts, "gColdstartAttempts"); @@ -425,24 +423,24 @@ bool Converter::decode(const Node& node, Services::Flexray::FlexrayClusterParame obj.gdMiniSlotActionPointOffset = parseInt(obj.gdMiniSlotActionPointOffset, "gdMiniSlotActionPointOffset"); obj.gdStaticSlot = parseInt(obj.gdStaticSlot, "gdStaticSlot"); obj.gdSymbolWindow = parseInt(obj.gdSymbolWindow, "gdSymbolWindow"); - obj.gdSymbolWindowActionPointOffset = parseInt(obj.gdSymbolWindowActionPointOffset, - "gdSymbolWindowActionPointOffset"); + obj.gdSymbolWindowActionPointOffset = + parseInt(obj.gdSymbolWindowActionPointOffset, "gdSymbolWindowActionPointOffset"); obj.gdTSSTransmitter = parseInt(obj.gdTSSTransmitter, "gdTSSTransmitter"); obj.gdWakeupTxActive = parseInt(obj.gdWakeupTxActive, "gdWakeupTxActive"); obj.gdWakeupTxIdle = parseInt(obj.gdWakeupTxIdle, "gdWakeupTxIdle"); obj.gListenNoise = parseInt(obj.gListenNoise, "gListenNoise"); obj.gMacroPerCycle = parseInt(obj.gMacroPerCycle, "gMacroPerCycle"); - obj.gMaxWithoutClockCorrectionFatal = parseInt(obj.gMaxWithoutClockCorrectionFatal, - "gMaxWithoutClockCorrectionFatal"); - obj.gMaxWithoutClockCorrectionPassive = parseInt(obj.gMaxWithoutClockCorrectionPassive, - "gMaxWithoutClockCorrectionPassive"); + obj.gMaxWithoutClockCorrectionFatal = + parseInt(obj.gMaxWithoutClockCorrectionFatal, "gMaxWithoutClockCorrectionFatal"); + obj.gMaxWithoutClockCorrectionPassive = + parseInt(obj.gMaxWithoutClockCorrectionPassive, "gMaxWithoutClockCorrectionPassive"); obj.gNumberOfMiniSlots = parseInt(obj.gNumberOfMiniSlots, "gNumberOfMiniSlots"); obj.gNumberOfStaticSlots = parseInt(obj.gNumberOfStaticSlots, "gNumberOfStaticSlots"); obj.gPayloadLengthStatic = parseInt(obj.gPayloadLengthStatic, "gPayloadLengthStatic"); obj.gSyncFrameIDCountMax = parseInt(obj.gSyncFrameIDCountMax, "gSyncFrameIDCountMax"); return true; } -template<> +template <> Node Converter::encode(const Services::Flexray::FlexrayNodeParameters& obj) { Node node; @@ -471,11 +469,10 @@ Node Converter::encode(const Services::Flexray::FlexrayNodeParameters& obj) node["pChannels"] = obj.pChannels; return node; } -template<> +template <> bool Converter::decode(const Node& node, Services::Flexray::FlexrayNodeParameters& obj) { - auto parseInt = [&node](auto instance, auto name) - { + auto parseInt = [&node](auto instance, auto name) { return static_cast(parse_as(node[name])); }; obj.pAllowHaltDueToClock = parseInt(obj.pAllowHaltDueToClock, "pAllowHaltDueToClock"); @@ -504,7 +501,7 @@ bool Converter::decode(const Node& node, Services::Flexray::FlexrayNodeParameter return true; } -template<> +template <> Node Converter::encode(const Services::Flexray::FlexrayTxBufferConfig& obj) { Node node; @@ -517,7 +514,7 @@ Node Converter::encode(const Services::Flexray::FlexrayTxBufferConfig& obj) node["transmissionMode"] = obj.transmissionMode; return node; } -template<> +template <> bool Converter::decode(const Node& node, Services::Flexray::FlexrayTxBufferConfig& obj) { obj.channels = parse_as(node["channels"]); @@ -530,7 +527,7 @@ bool Converter::decode(const Node& node, Services::Flexray::FlexrayTxBufferConfi return true; } -template<> +template <> Node Converter::encode(const Services::Flexray::FlexrayChannel& obj) { Node node; @@ -543,7 +540,7 @@ Node Converter::encode(const Services::Flexray::FlexrayChannel& obj) node = "B"; break; case Services::Flexray::FlexrayChannel::AB: - node = "AB"; + node = "AB"; break; case Services::Flexray::FlexrayChannel::None: node = "None"; @@ -551,16 +548,16 @@ Node Converter::encode(const Services::Flexray::FlexrayChannel& obj) } return node; } -template<> +template <> bool Converter::decode(const Node& node, Services::Flexray::FlexrayChannel& obj) { auto&& str = parse_as(node); if (str == "A") - obj = Services::Flexray::FlexrayChannel::A; + obj = Services::Flexray::FlexrayChannel::A; else if (str == "B") - obj = Services::Flexray::FlexrayChannel::B; + obj = Services::Flexray::FlexrayChannel::B; else if (str == "AB") - obj = Services::Flexray::FlexrayChannel::AB; + obj = Services::Flexray::FlexrayChannel::AB; else if (str == "None" || str == "") obj = Services::Flexray::FlexrayChannel::None; else @@ -570,7 +567,7 @@ bool Converter::decode(const Node& node, Services::Flexray::FlexrayChannel& obj) return true; } -template<> +template <> Node Converter::encode(const Services::Flexray::FlexrayClockPeriod& obj) { Node node; @@ -580,7 +577,7 @@ Node Converter::encode(const Services::Flexray::FlexrayClockPeriod& obj) node = "12.5ns"; break; case Services::Flexray::FlexrayClockPeriod::T25NS: - node = "25ns"; + node = "25ns"; break; case Services::Flexray::FlexrayClockPeriod::T50NS: node = "50ns"; @@ -590,7 +587,7 @@ Node Converter::encode(const Services::Flexray::FlexrayClockPeriod& obj) } return node; } -template<> +template <> bool Converter::decode(const Node& node, Services::Flexray::FlexrayClockPeriod& obj) { auto&& str = parse_as(node); @@ -607,7 +604,7 @@ bool Converter::decode(const Node& node, Services::Flexray::FlexrayClockPeriod& return true; } -template<> +template <> Node Converter::encode(const Services::Flexray::FlexrayTransmissionMode& obj) { Node node; @@ -624,7 +621,7 @@ Node Converter::encode(const Services::Flexray::FlexrayTransmissionMode& obj) } return node; } -template<> +template <> bool Converter::decode(const Node& node, Services::Flexray::FlexrayTransmissionMode& obj) { auto&& str = parse_as(node); @@ -639,7 +636,7 @@ bool Converter::decode(const Node& node, Services::Flexray::FlexrayTransmissionM return true; } -template<> +template <> Node Converter::encode(const FlexrayController& obj) { static const FlexrayController defaultObj{}; @@ -661,7 +658,7 @@ Node Converter::encode(const FlexrayController& obj) optional_encode(obj.replay, node, "Replay"); return node; } -template<> +template <> bool Converter::decode(const Node& node, FlexrayController& obj) { obj.name = parse_as(node["Name"]); @@ -776,7 +773,7 @@ bool Converter::decode(const Node& node, HealthCheck& obj) return true; } -template<> +template <> Node Converter::encode(const Tracing& obj) { static const Tracing defaultObj{}; @@ -785,7 +782,7 @@ Node Converter::encode(const Tracing& obj) optional_encode(obj.traceSources, node, "TraceSources"); return node; } -template<> +template <> bool Converter::decode(const Node& node, Tracing& obj) { optional_decode(obj.traceSinks, node, "TraceSinks"); @@ -793,7 +790,7 @@ bool Converter::decode(const Node& node, Tracing& obj) return true; } -template<> +template <> Node Converter::encode(const TraceSink& obj) { Node node; @@ -808,7 +805,7 @@ Node Converter::encode(const TraceSink& obj) return node; } -template<> +template <> bool Converter::decode(const Node& node, TraceSink& obj) { obj.name = parse_as(node["Name"]); @@ -821,7 +818,7 @@ bool Converter::decode(const Node& node, TraceSink& obj) return true; } -template<> +template <> Node Converter::encode(const TraceSink::Type& obj) { Node node; @@ -840,11 +837,11 @@ Node Converter::encode(const TraceSink::Type& obj) node = "PcapPipe"; break; default: - throw ConfigurationError{ "Unknown TraceSink Type" }; + throw ConfigurationError{"Unknown TraceSink Type"}; } return node; } -template<> +template <> bool Converter::decode(const Node& node, TraceSink::Type& obj) { auto&& str = parse_as(node); @@ -863,7 +860,7 @@ bool Converter::decode(const Node& node, TraceSink::Type& obj) return true; } -template<> +template <> Node Converter::encode(const TraceSource& obj) { Node node; @@ -877,7 +874,7 @@ Node Converter::encode(const TraceSource& obj) //} return node; } -template<> +template <> bool Converter::decode(const Node& node, TraceSource& obj) { obj.name = parse_as(node["Name"]); @@ -890,7 +887,7 @@ bool Converter::decode(const Node& node, TraceSource& obj) return true; } -template<> +template <> Node Converter::encode(const TraceSource::Type& obj) { Node node; @@ -906,11 +903,11 @@ Node Converter::encode(const TraceSource::Type& obj) node = "PcapFile"; break; default: - throw ConfigurationError{ "Unknown TraceSource Type" }; + throw ConfigurationError{"Unknown TraceSource Type"}; } return node; } -template<> +template <> bool Converter::decode(const Node& node, TraceSource::Type& obj) { auto&& str = parse_as(node); @@ -927,7 +924,7 @@ bool Converter::decode(const Node& node, TraceSource::Type& obj) return true; } -template<> +template <> Node Converter::encode(const Extensions& obj) { static const Extensions defaultObj{}; @@ -935,7 +932,7 @@ Node Converter::encode(const Extensions& obj) non_default_encode(obj.searchPathHints, node, "SearchPathHints", defaultObj.searchPathHints); return node; } -template<> +template <> bool Converter::decode(const Node& node, Extensions& obj) { optional_decode(obj.searchPathHints, node, "SearchPathHints"); @@ -943,7 +940,7 @@ bool Converter::decode(const Node& node, Extensions& obj) } -template<> +template <> Node Converter::encode(const Middleware& obj) { Node node; @@ -956,12 +953,14 @@ Node Converter::encode(const Middleware& obj) non_default_encode(obj.tcpSendBufferSize, node, "TcpSendBufferSize", defaultObj.tcpSendBufferSize); non_default_encode(obj.enableDomainSockets, node, "EnableDomainSockets", defaultObj.enableDomainSockets); non_default_encode(obj.acceptorUris, node, "acceptorUris", defaultObj.acceptorUris); - non_default_encode(obj.registryAsFallbackProxy, node, "RegistryAsFallbackProxy", defaultObj.registryAsFallbackProxy); - non_default_encode(obj.experimentalRemoteParticipantConnection, node, "ExperimentalRemoteParticipantConnection", defaultObj.experimentalRemoteParticipantConnection); + non_default_encode(obj.registryAsFallbackProxy, node, "RegistryAsFallbackProxy", + defaultObj.registryAsFallbackProxy); + non_default_encode(obj.experimentalRemoteParticipantConnection, node, "ExperimentalRemoteParticipantConnection", + defaultObj.experimentalRemoteParticipantConnection); non_default_encode(obj.connectTimeoutSeconds, node, "ConnectTimeoutSeconds", defaultObj.connectTimeoutSeconds); return node; } -template<> +template <> bool Converter::decode(const Node& node, Middleware& obj) { optional_decode(obj.registryUri, node, "RegistryUri"); @@ -978,7 +977,7 @@ bool Converter::decode(const Node& node, Middleware& obj) return true; } -template<> +template <> Node Converter::encode(const ParticipantConfiguration& obj) { static const ParticipantConfiguration defaultObj{}; @@ -1009,7 +1008,7 @@ Node Converter::encode(const ParticipantConfiguration& obj) non_default_encode(obj.middleware, node, "Middleware", defaultObj.middleware); return node; } -template<> +template <> bool Converter::decode(const Node& node, ParticipantConfiguration& obj) { optional_decode(obj.schemaVersion, node, "SchemaVersion"); diff --git a/SilKit/source/config/YamlParser.cpp b/SilKit/source/config/YamlParser.cpp index 782707577..4c077e141 100644 --- a/SilKit/source/config/YamlParser.cpp +++ b/SilKit/source/config/YamlParser.cpp @@ -42,10 +42,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace { // Indentation helper -class Indent { +class Indent +{ public: Indent(int level) - : _level{ level } + : _level{level} { } int Level() const @@ -61,7 +62,8 @@ class Indent { void Dec() { _level -= _shift; - if (_level < 0) _level = 0; + if (_level < 0) + _level = 0; } std::size_t Row() const { @@ -73,9 +75,9 @@ class Indent { } private: - const int _shift{ 4 }; + const int _shift{4}; int _level; - std::size_t _row{ 0 }; + std::size_t _row{0}; }; // The ostream_wrapper keeps track of lines and write position @@ -95,7 +97,7 @@ inline YAML::ostream_wrapper& operator<<(YAML::ostream_wrapper& out, Indent& ind } // Ensure we can print any type that is supported by ostream::operator<< -template +template inline YAML::ostream_wrapper& operator<<(YAML::ostream_wrapper& out, const T& value) { std::stringstream buf; @@ -109,12 +111,13 @@ void EmitScalar(YAML::ostream_wrapper& out, YAML::Node val) { if (!val.IsScalar()) { - throw SilKit::SilKitError{ "YamlParser: EmitScalar on non-scalar type called" }; + throw SilKit::SilKitError{"YamlParser: EmitScalar on non-scalar type called"}; } //XXX we should be able to query the scalar's type, instead of // exception bombing our way to the final value. //out ; - try { + try + { out << (val.as() ? "true" : "false"); } catch (...) @@ -130,9 +133,10 @@ void EmitScalar(YAML::ostream_wrapper& out, YAML::Node val) }; const auto valStr = val.as(); //Warning: using the val.as does truncate type to char - int intNumber{ 0 }; - double floatNumber{ 0.0 }; - if (emitAs(valStr, intNumber)) { + int intNumber{0}; + double floatNumber{0.0}; + if (emitAs(valStr, intNumber)) + { out << intNumber; } else if (emitAs(valStr, floatNumber)) @@ -145,10 +149,10 @@ void EmitScalar(YAML::ostream_wrapper& out, YAML::Node val) } } } -void EmitValidJson(YAML::ostream_wrapper& out, YAML::Node& node, - YAML::NodeType::value parentType = YAML::NodeType::Undefined) +void EmitValidJson(YAML::ostream_wrapper& out, YAML::Node& node, + YAML::NodeType::value parentType = YAML::NodeType::Undefined) { - static Indent ind{ 0 }; + static Indent ind{0}; uint32_t seqNum = 0; const bool needComma = node.size() > 1; if (parentType == YAML::NodeType::Undefined) @@ -179,18 +183,17 @@ void EmitValidJson(YAML::ostream_wrapper& out, YAML::Node& node, else if (kv.second.IsDefined()) { // might be key:value kind of node - try { - out << ind << "\"" << kv.first.as() << "\": "; + try + { + out << ind << "\"" << kv.first.as() << "\": "; } catch (...) { - } val = kv.second; } if (val.IsDefined()) { - if (val.IsSequence()) { out << ind << "["; @@ -203,22 +206,21 @@ void EmitValidJson(YAML::ostream_wrapper& out, YAML::Node& node, ind.Inc(); EmitValidJson(out, val, YAML::NodeType::Map); ind.Dec(); - out << ind << "}"; + out << ind << "}"; } else if (val.IsScalar()) { out << ind; EmitScalar(out, val); } - } - if (needComma && (seqNum < (node.size()-1))) + if (needComma && (seqNum < (node.size() - 1))) { out << ind << ", "; - if(parentType != YAML::NodeType::Sequence) + if (parentType != YAML::NodeType::Sequence) { //break lines if in object (map or toplevel) - out << "\n"; + out << "\n"; } } else @@ -259,7 +261,7 @@ std::ostream& operator<<(std::ostream& out, const YAML::Mark& mark) auto yaml_to_json(YAML::Node node) -> std::string { std::stringstream buf; - YAML::ostream_wrapper out{ buf }; + YAML::ostream_wrapper out{buf}; EmitValidJson(out, node); return buf.str(); } diff --git a/SilKit/source/config/YamlParser.hpp b/SilKit/source/config/YamlParser.hpp index b0fe88fa6..3f0a3b449 100644 --- a/SilKit/source/config/YamlParser.hpp +++ b/SilKit/source/config/YamlParser.hpp @@ -41,7 +41,7 @@ namespace Config { //! Helper to print the YAML position in line and column format. std::ostream& operator<<(std::ostream& out, const YAML::Mark& mark); -template +template auto to_yaml(const SilKitConfigT& silkitValue) -> YAML::Node { YAML::Node node; @@ -53,12 +53,11 @@ auto to_yaml(const SilKitConfigT& silkitValue) -> YAML::Node catch (const YAML::Exception& ex) { std::stringstream ss; - ss << "YAML Error @ " << ex.mark - << ": " << ex.msg; - throw ConfigurationError{ ss.str() }; + ss << "YAML Error @ " << ex.mark << ": " << ex.msg; + throw ConfigurationError{ss.str()}; } } -template +template auto from_yaml(const YAML::Node& node) -> SilKitConfigT { try @@ -68,9 +67,8 @@ auto from_yaml(const YAML::Node& node) -> SilKitConfigT catch (const YAML::Exception& ex) { std::stringstream ss; - ss << "YAML Error @ " << ex.mark - << ": " << ex.msg; - throw ConfigurationError{ ss.str() }; + ss << "YAML Error @ " << ex.mark << ": " << ex.msg; + throw ConfigurationError{ss.str()}; } } diff --git a/SilKit/source/config/YamlSchema.cpp b/SilKit/source/config/YamlSchema.cpp index 277a457c6..2a9d438cd 100644 --- a/SilKit/source/config/YamlSchema.cpp +++ b/SilKit/source/config/YamlSchema.cpp @@ -30,124 +30,106 @@ auto MakeYamlSchema() -> YamlSchemaElem { // Note: Keep these definitions in sync with ParticipantConfiguration.schema.json, // which is currently the main reference for valid configuration files. - YamlSchemaElem replay("Replay", - { - {"UseTraceSource"}, - {"Direction"}, - {"MdfChannel", { - {"ChannelName"}, {"ChannelSource"}, {"ChannelPath"}, - {"GroupName"}, {"GroupSource"}, {"GroupPath"}, - } - } - } - ); - YamlSchemaElem traceSinks("TraceSinks", - { - {"Name"}, - {"OutputPath"}, - {"Type"}, - } - ); - YamlSchemaElem traceSources("TraceSources", - { - {"Name"}, - {"InputPath"}, - {"Type"}, - } - ); - YamlSchemaElem logging("Logging", - { - {"LogFromRemotes"}, - {"FlushLevel"}, - {"Sinks", { - {"Type"}, - {"Level"}, - {"LogName"}, - }, - }, + YamlSchemaElem replay("Replay", {{"UseTraceSource"}, + {"Direction"}, + {"MdfChannel", + { + {"ChannelName"}, + {"ChannelSource"}, + {"ChannelPath"}, + {"GroupName"}, + {"GroupSource"}, + {"GroupPath"}, + }}}); + YamlSchemaElem traceSinks("TraceSinks", { + {"Name"}, + {"OutputPath"}, + {"Type"}, + }); + YamlSchemaElem traceSources("TraceSources", { + {"Name"}, + {"InputPath"}, + {"Type"}, + }); + YamlSchemaElem logging("Logging", { + {"LogFromRemotes"}, + {"FlushLevel"}, + { + "Sinks", + { + {"Type"}, + {"Level"}, + {"LogName"}, + }, + }, - } - ); - YamlSchemaElem clusterParameters("ClusterParameters", - { - {"gColdstartAttempts"}, - {"gCycleCountMax"}, - {"gdActionPointOffset"}, - {"gdDynamicSlotIdlePhase"}, - {"gdMiniSlot"}, - {"gdMiniSlotActionPointOffset"}, - {"gdStaticSlot"}, - {"gdSymbolWindow"}, - {"gdSymbolWindowActionPointOffset"}, - {"gdTSSTransmitter"}, - {"gdWakeupTxActive"}, - {"gdWakeupTxIdle"}, - {"gListenNoise"}, - {"gMacroPerCycle"}, - {"gMaxWithoutClockCorrectionFatal"}, - {"gMaxWithoutClockCorrectionPassive"}, - {"gNumberOfMiniSlots"}, - {"gNumberOfStaticSlots"}, - {"gPayloadLengthStatic"}, - {"gSyncFrameIDCountMax"}, - } - ); - YamlSchemaElem nodeParameters("NodeParameters", - { - {"pAllowHaltDueToClock"}, - {"pAllowPassiveToActive"}, - {"pChannels"}, - {"pClusterDriftDamping"}, - {"pdAcceptedStartupRange"}, - {"pdListenTimeout"}, - {"pKeySlotId"}, - {"pKeySlotOnlyEnabled"}, - {"pKeySlotUsedForStartup"}, - {"pKeySlotUsedForSync"}, - {"pLatestTx"}, - {"pMacroInitialOffsetA"}, - {"pMacroInitialOffsetB"}, - {"pMicroInitialOffsetA"}, - {"pMicroInitialOffsetB"}, - {"pMicroPerCycle"}, - {"pOffsetCorrectionOut"}, - {"pOffsetCorrectionStart"}, - {"pRateCorrectionOut"}, - {"pWakeupChannel"}, - {"pWakeupPattern"}, - {"pdMicrotick"}, - {"pSamplesPerMicrotick"}, - } - ); - YamlSchemaElem txBufferConfigurations("TxBufferConfigurations", - { - {"channels"}, - {"slotId"}, - {"offset"}, - {"repetition"}, - {"PPindicator"}, - {"headerCrc"}, - {"transmissionMode"}, - } - ); + }); + YamlSchemaElem clusterParameters("ClusterParameters", { + {"gColdstartAttempts"}, + {"gCycleCountMax"}, + {"gdActionPointOffset"}, + {"gdDynamicSlotIdlePhase"}, + {"gdMiniSlot"}, + {"gdMiniSlotActionPointOffset"}, + {"gdStaticSlot"}, + {"gdSymbolWindow"}, + {"gdSymbolWindowActionPointOffset"}, + {"gdTSSTransmitter"}, + {"gdWakeupTxActive"}, + {"gdWakeupTxIdle"}, + {"gListenNoise"}, + {"gMacroPerCycle"}, + {"gMaxWithoutClockCorrectionFatal"}, + {"gMaxWithoutClockCorrectionPassive"}, + {"gNumberOfMiniSlots"}, + {"gNumberOfStaticSlots"}, + {"gPayloadLengthStatic"}, + {"gSyncFrameIDCountMax"}, + }); + YamlSchemaElem nodeParameters("NodeParameters", { + {"pAllowHaltDueToClock"}, + {"pAllowPassiveToActive"}, + {"pChannels"}, + {"pClusterDriftDamping"}, + {"pdAcceptedStartupRange"}, + {"pdListenTimeout"}, + {"pKeySlotId"}, + {"pKeySlotOnlyEnabled"}, + {"pKeySlotUsedForStartup"}, + {"pKeySlotUsedForSync"}, + {"pLatestTx"}, + {"pMacroInitialOffsetA"}, + {"pMacroInitialOffsetB"}, + {"pMicroInitialOffsetA"}, + {"pMicroInitialOffsetB"}, + {"pMicroPerCycle"}, + {"pOffsetCorrectionOut"}, + {"pOffsetCorrectionStart"}, + {"pRateCorrectionOut"}, + {"pWakeupChannel"}, + {"pWakeupPattern"}, + {"pdMicrotick"}, + {"pSamplesPerMicrotick"}, + }); + YamlSchemaElem txBufferConfigurations("TxBufferConfigurations", { + {"channels"}, + {"slotId"}, + {"offset"}, + {"repetition"}, + {"PPindicator"}, + {"headerCrc"}, + {"transmissionMode"}, + }); std::initializer_list flexrayControllerElements = { - {"Name"}, - {"Network"}, - {"UseTraceSinks"}, - clusterParameters, - nodeParameters, - txBufferConfigurations, - replay, + {"Name"}, {"Network"}, {"UseTraceSinks"}, clusterParameters, nodeParameters, txBufferConfigurations, replay, }; - YamlSchemaElem ethernetControllers("EthernetControllers", - { - {"Name"}, - {"Network"}, - {"UseTraceSinks"}, - replay, - } - ); + YamlSchemaElem ethernetControllers("EthernetControllers", { + {"Name"}, + {"Network"}, + {"UseTraceSinks"}, + replay, + }); // Root element of the YAML schema YamlSchemaElem yamlSchema{ @@ -157,84 +139,65 @@ auto MakeYamlSchema() -> YamlSchemaElem {"schemaVersion"}, // should be removed in the future (deprecated) {"Description"}, {"ParticipantName"}, - {"CanControllers", { - {"Name"}, - {"Network"}, - {"UseTraceSinks"}, - replay - } - }, - {"LinControllers", { - {"Name"}, - {"Network"}, - {"UseTraceSinks"}, - replay - } - }, + {"Includes", {{"SearchPathHints"}, {"Files"}}}, + {"CanControllers", {{"Name"}, {"Network"}, {"UseTraceSinks"}, replay}}, + {"LinControllers", {{"Name"}, {"Network"}, {"UseTraceSinks"}, replay}}, {"FlexrayControllers", flexrayControllerElements}, {"FlexRayControllers", flexrayControllerElements}, // deprecated (renamed to FlexrayControllers) ethernetControllers, - {"DataPublishers", { - {"Name"}, - {"Topic"}, - {"UseTraceSinks"}, - replay, - } - }, - {"DataSubscribers", { - {"Name"}, - {"Topic"}, - {"UseTraceSinks"}, - replay, - } - }, - {"RpcClients", { - {"Name"}, - {"FunctionName"}, - {"UseTraceSinks"}, - replay, - } - }, - {"RpcServers", { - {"Name"}, - {"FunctionName"}, - {"UseTraceSinks"}, - replay, - } - }, + {"DataPublishers", + { + {"Name"}, + {"Topic"}, + {"UseTraceSinks"}, + replay, + }}, + {"DataSubscribers", + { + {"Name"}, + {"Topic"}, + {"UseTraceSinks"}, + replay, + }}, + {"RpcClients", + { + {"Name"}, + {"FunctionName"}, + {"UseTraceSinks"}, + replay, + }}, + {"RpcServers", + { + {"Name"}, + {"FunctionName"}, + {"UseTraceSinks"}, + replay, + }}, logging, - {"HealthCheck", { - {"SoftResponseTimeout"}, - {"HardResponseTimeout"}, - } - }, - {"Tracing", { - traceSinks, - traceSources - } - }, - {"Extensions", { - {"SearchPathHints"} - } - }, - {"Middleware", { - {"RegistryUri"}, - {"ConnectAttempts"}, - {"TcpNoDelay"}, - {"TcpQuickAck"}, - {"TcpReceiveBufferSize"}, - {"TcpSendBufferSize"}, - {"EnableDomainSockets"}, - {"AcceptorUris"}, - {"RegistryAsFallbackProxy"}, - {"ExperimentalRemoteParticipantConnection"}, - {"ConnectTimeoutSeconds"}, - } - } - }; + {"HealthCheck", + { + {"SoftResponseTimeout"}, + {"HardResponseTimeout"}, + }}, + {"Tracing", {traceSinks, traceSources}}, + {"Extensions", {{"SearchPathHints"}}}, + {"Middleware", + { + {"RegistryUri"}, + {"ConnectAttempts"}, + {"TcpNoDelay"}, + {"TcpQuickAck"}, + {"TcpReceiveBufferSize"}, + {"TcpSendBufferSize"}, + {"EnableDomainSockets"}, + {"AcceptorUris"}, + {"RegistryAsFallbackProxy"}, + {"ExperimentalRemoteParticipantConnection"}, + {"ConnectTimeoutSeconds"}, + }}}; return yamlSchema; } -} // inline namespace v1 +} // namespace v1 } // namespace Config } // namespace SilKit diff --git a/SilKit/source/config/YamlSchema.hpp b/SilKit/source/config/YamlSchema.hpp index 52e32660f..e57983077 100644 --- a/SilKit/source/config/YamlSchema.hpp +++ b/SilKit/source/config/YamlSchema.hpp @@ -55,7 +55,7 @@ struct YamlSchemaElem inline namespace v1 { auto MakeYamlSchema() -> YamlSchemaElem; -} // inline namespace v1 +} // namespace v1 } // namespace Config } // namespace SilKit diff --git a/SilKit/source/config/YamlValidator.cpp b/SilKit/source/config/YamlValidator.cpp index 8c799091b..08f0e2ef2 100644 --- a/SilKit/source/config/YamlValidator.cpp +++ b/SilKit/source/config/YamlValidator.cpp @@ -31,8 +31,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace { //! Recursive validation helper to iterate through the YAML document -bool ValidateDoc(YAML::Node& doc, const SilKit::Config::YamlValidator& v, - std::ostream& warnings, const std::string& parent) +bool ValidateDoc(YAML::Node& doc, const SilKit::Config::YamlValidator& v, std::ostream& warnings, + const std::string& parent) { using namespace SilKit::Config; bool ok = true; @@ -46,21 +46,18 @@ bool ValidateDoc(YAML::Node& doc, const SilKit::Config::YamlValidator& v, { if (node.IsDefined()) { - if(node.IsScalar()) - { + if (node.IsScalar()) + { auto nodeName = v.MakeName(parent, node.Scalar()); - if (v.IsSchemaElement(nodeName) - && !v.IsSubelementOf(parent, nodeName)) + if (v.IsSchemaElement(nodeName) && !v.IsSubelementOf(parent, nodeName)) { - warnings << "At " << node.Mark() << ": Element \"" - << v.ElementName(nodeName) << "\"" - << " is not a valid sub-element of schema path \"" - << parent << "\"\n"; + warnings << "At " << node.Mark() << ": Element \"" << v.ElementName(nodeName) << "\"" + << " is not a valid sub-element of schema path \"" << parent << "\"\n"; ok &= false; } else { - // This is a user-defined value, that is, a subelement + // This is a user-defined value, that is, a subelement // with no corresponding schema element as parent } } @@ -86,12 +83,11 @@ bool ValidateDoc(YAML::Node& doc, const SilKit::Config::YamlValidator& v, if (!keyName.empty() && !v.IsSchemaElement(keyName)) { // Unknown elements, which are not found in the schema are only warnings - warnings << "At " << key.Mark() << ": Element \"" - << v.ElementName(keyName) << "\""; + warnings << "At " << key.Mark() << ": Element \"" << v.ElementName(keyName) << "\""; if (v.IsReservedElementName(keyName)) { warnings << " is a reserved element name and as such" - << " not a sub-element of schema path \""; + << " not a sub-element of schema path \""; // Misplacing a keyword is an error! ok &= false; } @@ -103,17 +99,13 @@ bool ValidateDoc(YAML::Node& doc, const SilKit::Config::YamlValidator& v, warnings << parent << "\"\n"; } // We are not a subelement of parent - else if (v.HasSubelements(parent) - && !v.IsSubelementOf(parent, keyName) - ) + else if (v.HasSubelements(parent) && !v.IsSubelementOf(parent, keyName)) { - warnings << "At " << key.Mark() << ": Element \"" - << v.ElementName(keyName) << "\"" - << " is not a valid sub-element of schema path \"" - << parent << "\"\n"; + warnings << "At " << key.Mark() << ": Element \"" << v.ElementName(keyName) << "\"" + << " is not a valid sub-element of schema path \"" << parent << "\"\n"; ok &= false; } - else if(value.IsMap() || value.IsSequence()) + else if (value.IsMap() || value.IsSequence()) { // Nested sequences and maps might have no key name std::string newParent = parent; // A fallback in case keyName is not given @@ -145,7 +137,7 @@ bool ValidateDoc(YAML::Node& doc, const SilKit::Config::YamlValidator& v, namespace SilKit { namespace Config { - + const std::string YamlValidator::_elementSeparator{"/"}; bool YamlValidator::LoadSchema(std::string schemaVersion) @@ -183,14 +175,15 @@ auto YamlValidator::ElementName(const std::string& elementName) const -> std::st { return {}; } - return elementName.substr(sep+1, elementName.size()); + return elementName.substr(sep + 1, elementName.size()); } -bool YamlValidator::Validate(const std::string& yamlString, std::ostream& warnings) +bool YamlValidator::Validate(const std::string& yamlString, std::ostream& warnings) { - try { + try + { auto yamlDoc = YAML::Load(yamlString); - if (yamlDoc.IsDefined() && yamlDoc.IsMap() && yamlDoc["SchemaVersion"]) + if (yamlDoc.IsDefined() && yamlDoc.IsMap() && yamlDoc["SchemaVersion"]) { auto version = yamlDoc["SchemaVersion"].as(); if (!LoadSchema(version)) @@ -204,9 +197,10 @@ bool YamlValidator::Validate(const std::string& yamlString, std::ostream& warnin // The document does not specify 'SchemaVersion', we're assuming version '1' LoadSchema("1"); } - return ValidateDoc(yamlDoc, *this, warnings, DocumentRoot()); + return ValidateDoc(yamlDoc, *this, warnings, DocumentRoot()); } - catch (const std::exception& ex) { + catch (const std::exception& ex) + { warnings << "Error: caught exception: " << ex.what() << "\n"; return false; } diff --git a/SilKit/source/config/YamlValidator.hpp b/SilKit/source/config/YamlValidator.hpp index adb98b6bb..e9319f09d 100644 --- a/SilKit/source/config/YamlValidator.hpp +++ b/SilKit/source/config/YamlValidator.hpp @@ -46,16 +46,16 @@ class YamlValidator //!< Check that the element has sub-elements. bool HasSubelements(const std::string& elementName) const; - + //!< Check that elementName is a sub-element of parentName bool IsSubelementOf(const std::string& parentName, const std::string& elementName) const; - + //!< Check that elementName has the document's root as parent. bool IsRootElement(const std::string& elementName) const; //!< Check if the elementName (which might be a suffix) is a reserved element name. // We want to discern unknown elements from misplaced elements in a document. - bool IsReservedElementName(const std::string& elementName) const ; + bool IsReservedElementName(const std::string& elementName) const; auto DocumentRoot() const -> std::string; diff --git a/SilKit/source/core/internal/CMakeLists.txt b/SilKit/source/core/internal/CMakeLists.txt index 6b91ed31d..e898f8580 100644 --- a/SilKit/source/core/internal/CMakeLists.txt +++ b/SilKit/source/core/internal/CMakeLists.txt @@ -43,6 +43,7 @@ target_link_libraries(I_SilKit_Core_Internal INTERFACE I_SilKit_Services_Lin INTERFACE I_SilKit_Services_Flexray INTERFACE I_SilKit_Services_Ethernet + INTERFACE I_SilKit_Experimental_NetworkSimulatorInternals ) diff --git a/SilKit/source/core/internal/EndpointAddress.hpp b/SilKit/source/core/internal/EndpointAddress.hpp index 787c9dc3b..68efe450e 100644 --- a/SilKit/source/core/internal/EndpointAddress.hpp +++ b/SilKit/source/core/internal/EndpointAddress.hpp @@ -59,20 +59,17 @@ inline bool operator<(SilKit::Core::EndpointAddress lhs, SilKit::Core::EndpointA // ================================================================================ bool operator==(SilKit::Core::EndpointAddress lhs, SilKit::Core::EndpointAddress rhs) { - return lhs.participant == rhs.participant - && lhs.endpoint == rhs.endpoint; + return lhs.participant == rhs.participant && lhs.endpoint == rhs.endpoint; } bool operator!=(SilKit::Core::EndpointAddress lhs, SilKit::Core::EndpointAddress rhs) { - return lhs.participant != rhs.participant - || lhs.endpoint != rhs.endpoint; + return lhs.participant != rhs.participant || lhs.endpoint != rhs.endpoint; } bool operator<(SilKit::Core::EndpointAddress lhs, SilKit::Core::EndpointAddress rhs) { - return lhs.participant < rhs.participant - || (lhs.participant == rhs.participant && lhs.endpoint < rhs.endpoint); + return lhs.participant < rhs.participant || (lhs.participant == rhs.participant && lhs.endpoint < rhs.endpoint); } } // namespace Core diff --git a/SilKit/source/core/internal/IMessageReceiver.hpp b/SilKit/source/core/internal/IMessageReceiver.hpp index 4b8746edb..20a9476c8 100644 --- a/SilKit/source/core/internal/IMessageReceiver.hpp +++ b/SilKit/source/core/internal/IMessageReceiver.hpp @@ -26,7 +26,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SilKit { namespace Core { -template +template class IMessageReceiver { public: diff --git a/SilKit/source/core/internal/IParticipantInternal.hpp b/SilKit/source/core/internal/IParticipantInternal.hpp old mode 100755 new mode 100644 index 3b1c061b8..91cdae5cb --- a/SilKit/source/core/internal/IParticipantInternal.hpp +++ b/SilKit/source/core/internal/IParticipantInternal.hpp @@ -25,6 +25,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "silkit/participant/IParticipant.hpp" #include "silkit/experimental/services/orchestration/ISystemController.hpp" +#include "silkit/experimental/netsim/NetworkSimulatorDatatypes.hpp" + #include "internal_fwd.hpp" #include "IServiceEndpoint.hpp" @@ -32,6 +34,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "RequestReplyDatatypes.hpp" #include "OrchestrationDatatypes.hpp" #include "LoggingDatatypesInternal.hpp" + #include "WireCanMessages.hpp" #include "WireDataMessages.hpp" #include "WireEthernetMessages.hpp" @@ -40,14 +43,15 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "WireRpcMessages.hpp" #include "ISimulator.hpp" - +#include "IReplayDataController.hpp" +#include "ITraceMessageSource.hpp" // forwards namespace SilKit { namespace Tracing { class ReplayScheduler; -} // end Tracing -} // end SilKit +} // namespace Tracing +} // namespace SilKit namespace SilKit { namespace Core { @@ -75,113 +79,185 @@ class IParticipantInternal : public IParticipant virtual void JoinSilKitSimulation() = 0; // For NetworkSimulator integration: - virtual void RegisterSimulator(ISimulator* busSim, const std::vector& networks) = 0 ; + virtual void RegisterSimulator(ISimulator* busSim, std::string networkName, + SilKit::Experimental::NetworkSimulation::SimulatedNetworkType networkType) = 0; + + virtual void AddTraceSinksToSource(ITraceMessageSource* traceSource, SilKit::Config::SimulatedNetwork config) = 0; // The SendMsgs are virtual functions so we can mock them in testing. // For performance reasons this may change in the future. virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Can::WireCanFrameEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Can::CanFrameTransmitEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Can::CanFrameTransmitEvent& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Can::CanControllerStatus& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Can::CanConfigureBaudrate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Can::CanSetControllerMode& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Ethernet::WireEthernetFrameEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Ethernet::EthernetFrameTransmitEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Can::CanConfigureBaudrate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Can::CanSetControllerMode& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Ethernet::WireEthernetFrameEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Ethernet::EthernetFrameTransmitEvent& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Ethernet::EthernetStatus& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Ethernet::EthernetSetMode& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::WireFlexrayFrameEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::FlexraySymbolEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::FlexraySymbolTransmitEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::FlexrayCycleStartEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::FlexrayHostCommand& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::FlexrayControllerConfig& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::WireFlexrayTxBufferUpdate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Flexray::FlexrayPocStatusEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Ethernet::EthernetSetMode& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::WireFlexrayFrameEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::FlexraySymbolEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::FlexraySymbolTransmitEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::FlexrayCycleStartEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::FlexrayHostCommand& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::FlexrayControllerConfig& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::WireFlexrayTxBufferUpdate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Flexray::FlexrayPocStatusEvent& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Lin::LinSendFrameRequest& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Lin::LinSendFrameHeaderRequest& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Lin::LinSendFrameHeaderRequest& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Lin::LinTransmission& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Lin::LinWakeupPulse& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Lin::WireLinControllerConfig& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Lin::LinControllerStatusUpdate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Lin::LinFrameResponseUpdate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Lin::WireLinControllerConfig& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Lin::LinControllerStatusUpdate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Lin::LinFrameResponseUpdate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::PubSub::WireDataMessageEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::PubSub::WireDataMessageEvent& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Rpc::FunctionCall& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, Services::Rpc::FunctionCall&& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Rpc::FunctionCallResponse& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Rpc::FunctionCallResponse& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, Services::Rpc::FunctionCallResponse&& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Orchestration::NextSimTask& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Orchestration::ParticipantStatus& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Orchestration::SystemCommand& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Orchestration::WorkflowConfiguration& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Orchestration::NextSimTask& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Orchestration::ParticipantStatus& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Orchestration::SystemCommand& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Services::Orchestration::WorkflowConfiguration& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Services::Logging::LogMsg& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, Services::Logging::LogMsg&& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Discovery::ParticipantDiscoveryEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const Discovery::ParticipantDiscoveryEvent& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const Discovery::ServiceDiscoveryEvent& msg) = 0; virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const RequestReply::RequestReplyCall& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const RequestReply::RequestReplyCallReturn& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, + const RequestReply::RequestReplyCallReturn& msg) = 0; // targeted messaging - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::WireCanFrameEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::CanFrameTransmitEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::CanControllerStatus& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::CanConfigureBaudrate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::CanSetControllerMode& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Ethernet::WireEthernetFrameEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Ethernet::EthernetFrameTransmitEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Ethernet::EthernetStatus& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Ethernet::EthernetSetMode& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayFrameEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexraySymbolEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexraySymbolTransmitEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayCycleStartEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayHostCommand& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayControllerConfig& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayTxBufferUpdate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayPocStatusEvent& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinSendFrameRequest& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinSendFrameHeaderRequest& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinTransmission& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinWakeupPulse& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::WireLinControllerConfig& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinControllerStatusUpdate& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinFrameResponseUpdate& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::PubSub::WireDataMessageEvent& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Rpc::FunctionCall& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, Services::Rpc::FunctionCall&& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Rpc::FunctionCallResponse& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, Services::Rpc::FunctionCallResponse&& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Orchestration::NextSimTask& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Orchestration::ParticipantStatus& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Orchestration::SystemCommand& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Orchestration::WorkflowConfiguration& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Logging::LogMsg& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, Services::Logging::LogMsg&& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Discovery::ParticipantDiscoveryEvent& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const Discovery::ServiceDiscoveryEvent& msg) = 0; - - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const RequestReply::RequestReplyCall& msg) = 0; - virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, const RequestReply::RequestReplyCallReturn& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::WireCanFrameEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::CanFrameTransmitEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::CanControllerStatus& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::CanConfigureBaudrate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::CanSetControllerMode& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Ethernet::WireEthernetFrameEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Ethernet::EthernetFrameTransmitEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Ethernet::EthernetStatus& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Ethernet::EthernetSetMode& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayFrameEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexraySymbolEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexraySymbolTransmitEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayCycleStartEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayHostCommand& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayControllerConfig& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayTxBufferUpdate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayPocStatusEvent& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinSendFrameRequest& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinSendFrameHeaderRequest& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinTransmission& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinWakeupPulse& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::WireLinControllerConfig& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinControllerStatusUpdate& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinFrameResponseUpdate& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::PubSub::WireDataMessageEvent& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Rpc::FunctionCall& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + Services::Rpc::FunctionCall&& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Rpc::FunctionCallResponse& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + Services::Rpc::FunctionCallResponse&& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Orchestration::NextSimTask& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Orchestration::ParticipantStatus& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Orchestration::SystemCommand& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Orchestration::WorkflowConfiguration& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Logging::LogMsg& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + Services::Logging::LogMsg&& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Discovery::ParticipantDiscoveryEvent& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const Discovery::ServiceDiscoveryEvent& msg) = 0; + + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const RequestReply::RequestReplyCall& msg) = 0; + virtual void SendMsg(const SilKit::Core::IServiceEndpoint* from, const std::string& targetParticipantName, + const RequestReply::RequestReplyCallReturn& msg) = 0; // For Connection/middleware support: virtual void OnAllMessagesDelivered(std::function callback) = 0; @@ -192,22 +268,20 @@ class IParticipantInternal : public IParticipant virtual auto GetServiceDiscovery() -> Discovery::IServiceDiscovery* = 0; // Request replay service for internal RPC and barriers virtual auto GetRequestReplyService() -> RequestReply::IRequestReplyService* = 0; - virtual auto GetParticipantRepliesProcedure()->RequestReply::IParticipantReplies* = 0; + virtual auto GetParticipantRepliesProcedure() -> RequestReply::IParticipantReplies* = 0; - // Internal DataSubscriber that is only created on a matching data connection + // Internal DataSubscriber that is only created on a matching data connection virtual auto CreateDataSubscriberInternal( - const std::string& topic, const std::string& linkName, - const std::string& mediaType, + const std::string& topic, const std::string& linkName, const std::string& mediaType, const std::vector& publisherLabels, Services::PubSub::DataMessageHandler callback, - Services::PubSub::IDataSubscriber* parent) -> Services::PubSub::DataSubscriberInternal* = 0; + Services::PubSub::IDataSubscriber* parent) -> Services::PubSub::DataSubscriberInternal* = 0; // Internal Rpc server that is only created on a matching rpc connection - virtual auto CreateRpcServerInternal(const std::string& functionName, const std::string& linkName, - const std::string& mediaType, - const std::vector& labels, - Services::Rpc::RpcCallHandler handler, Services::Rpc::IRpcServer* parent) - -> SilKit::Services::Rpc::RpcServerInternal* = 0; + virtual auto CreateRpcServerInternal( + const std::string& functionName, const std::string& linkName, const std::string& mediaType, + const std::vector& labels, Services::Rpc::RpcCallHandler handler, + Services::Rpc::IRpcServer* parent) -> SilKit::Services::Rpc::RpcServerInternal* = 0; //! \brief Return the ISystemMonitor at this SIL Kit participant. virtual auto GetSystemMonitor() -> Services::Orchestration::ISystemMonitor* = 0; @@ -225,23 +299,32 @@ class IParticipantInternal : public IParticipant virtual auto CreateTimeSyncService(Services::Orchestration::LifecycleService* lifecycleService) -> Services::Orchestration::TimeSyncService* = 0; + virtual auto CreateNetworkSimulator() -> Experimental::NetworkSimulation::INetworkSimulator* = 0; + // Register handlers for completion of async service creation - virtual void SetAsyncSubscriptionsCompletionHandler(std::function handler) = 0; - + virtual void AddAsyncSubscriptionsCompletionHandler(std::function handler) = 0; + virtual bool GetIsSystemControllerCreated() = 0; virtual void SetIsSystemControllerCreated(bool isCreated) = 0; + virtual bool GetIsNetworkSimulatorCreated() = 0; + virtual void SetIsNetworkSimulatorCreated(bool isCreated) = 0; + virtual size_t GetNumberOfConnectedParticipants() = 0; virtual size_t GetNumberOfRemoteReceivers(const IServiceEndpoint* service, const std::string& msgTypeName) = 0; virtual std::vector GetParticipantNamesOfRemoteReceivers(const IServiceEndpoint* service, - const std::string& msgTypeName) = 0; + const std::string& msgTypeName) = 0; virtual void NotifyShutdown() = 0; - virtual void RegisterReplayController(ISimulator* simulator, const SilKit::Core::ServiceDescriptor& service, const SilKit::Config::SimulatedNetwork& simulatedNetwork ) = 0; + virtual void RegisterReplayController(SilKit::Tracing::IReplayDataController* replayController, + const std::string& controllerName, + const SilKit::Config::SimulatedNetwork& simulatedNetwork) = 0; virtual bool ParticipantHasCapability(const std::string& participantName, const std::string& capability) const = 0; + + virtual std::string GetServiceDescriptorString( + SilKit::Experimental::NetworkSimulation::ControllerDescriptor controllerDescriptor) = 0; }; } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/internal/IReceiver.hpp b/SilKit/source/core/internal/IReceiver.hpp index 49eb03c70..3f9d8670c 100644 --- a/SilKit/source/core/internal/IReceiver.hpp +++ b/SilKit/source/core/internal/IReceiver.hpp @@ -27,7 +27,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SilKit { namespace Core { -template +template class IReceiver : public IMessageReceiver... { public: diff --git a/SilKit/source/core/internal/ISender.hpp b/SilKit/source/core/internal/ISender.hpp index cfa627a85..c47b543ef 100644 --- a/SilKit/source/core/internal/ISender.hpp +++ b/SilKit/source/core/internal/ISender.hpp @@ -26,7 +26,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SilKit { namespace Core { -template +template class ISender { public: diff --git a/SilKit/source/core/internal/ISimulator.hpp b/SilKit/source/core/internal/ISimulator.hpp index 4a27e70ec..4f49306ac 100644 --- a/SilKit/source/core/internal/ISimulator.hpp +++ b/SilKit/source/core/internal/ISimulator.hpp @@ -35,12 +35,11 @@ class ISimulator , public SilKit::Services::Ethernet::IMsgForEthSimulator , public SilKit::Services::Flexray::IMsgForFlexraySimulator , public SilKit::Services::Lin::IMsgForLinSimulator + , public Core::IServiceEndpoint { public: virtual ~ISimulator() = default; - virtual void SetReplayActive(SilKit::Config::NetworkType networkType, bool state) = 0; }; -}//Core -}//SilKit - +} // namespace Core +} // namespace SilKit diff --git a/SilKit/source/core/internal/ITimeProvider.hpp b/SilKit/source/core/internal/ITimeProvider.hpp old mode 100755 new mode 100644 index f8444cb20..2e9333568 --- a/SilKit/source/core/internal/ITimeProvider.hpp +++ b/SilKit/source/core/internal/ITimeProvider.hpp @@ -50,8 +50,7 @@ class ITimeProvider //! \brief Name of the time provider, for debugging purposes. virtual auto TimeProviderName() const -> const std::string& = 0; - using NextSimStepHandler = std::function; + using NextSimStepHandler = std::function; /*! \brief Register a handler that is executed when the next simulation step is started. * diff --git a/SilKit/source/core/internal/InternalSerdes.hpp b/SilKit/source/core/internal/InternalSerdes.hpp index ca1f1a373..6633c80fc 100644 --- a/SilKit/source/core/internal/InternalSerdes.hpp +++ b/SilKit/source/core/internal/InternalSerdes.hpp @@ -29,15 +29,13 @@ namespace Core { inline MessageBuffer& operator<<(MessageBuffer& buffer, const EndpointAddress& addr) { - buffer << addr.participant - << addr.endpoint; + buffer << addr.participant << addr.endpoint; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, EndpointAddress& addr) { - buffer >> addr.participant - >> addr.endpoint; + buffer >> addr.participant >> addr.endpoint; return buffer; } diff --git a/SilKit/source/core/internal/MessageBuffer.hpp b/SilKit/source/core/internal/MessageBuffer.hpp old mode 100755 new mode 100644 index 72f249dfd..c9793d6e3 --- a/SilKit/source/core/internal/MessageBuffer.hpp +++ b/SilKit/source/core/internal/MessageBuffer.hpp @@ -41,7 +41,9 @@ namespace SilKit { namespace Core { // The protocol version is directly tied to the MessageBuffer for backward compatibility in Ser/Des -struct end_of_buffer : public std::exception {}; +struct end_of_buffer : public std::exception +{ +}; class MessageBuffer; @@ -52,7 +54,7 @@ class MessageBuffer; class MessageBufferPeeker { public: - inline MessageBufferPeeker(MessageBuffer & messageBuffer); + inline MessageBufferPeeker(MessageBuffer& messageBuffer); inline ~MessageBufferPeeker(); private: @@ -87,7 +89,7 @@ class MessageBuffer // Public methods for backward compatibility. // peek into raw data, e.g. for retrieving headers without modifying the buffer - inline auto PeekData() const -> SilKit::Util::Span; + inline auto PeekData() const -> SilKit::Util::Span; inline auto ReadPos() const -> size_t; //! Set the format version to use for ser/des. @@ -103,13 +105,14 @@ class MessageBuffer //! \brief Return the underlying data storage by std::move and reset pointers inline auto ReleaseStorage() -> std::vector; inline auto RemainingBytesLeft() const noexcept -> size_t; + public: // ---------------------------------------- // Elementary streaming operators // ---------------------------------------- // Integral Types - template::value, int> = 0> + template ::value, int> = 0> inline MessageBuffer& operator<<(IntegerT t) { if (_wPos + sizeof(IntegerT) > _storage.size()) @@ -122,7 +125,7 @@ class MessageBuffer return *this; } - template::value, int> = 0> + template ::value, int> = 0> inline MessageBuffer& operator>>(IntegerT& t) { if (_rPos + sizeof(IntegerT) > _storage.size()) @@ -136,10 +139,11 @@ class MessageBuffer // ---------------------------------------- // Floating-Point Types - template::value, int> = 0> + template ::value, int> = 0> inline MessageBuffer& operator<<(DoubleT t) { - static_assert(std::numeric_limits::is_iec559, "This compiler does not support IEEE 754 standard for floating points."); + static_assert(std::numeric_limits::is_iec559, + "This compiler does not support IEEE 754 standard for floating points."); if (_wPos + sizeof(DoubleT) > _storage.size()) { @@ -151,10 +155,11 @@ class MessageBuffer return *this; } - template::value, int> = 0> + template ::value, int> = 0> inline MessageBuffer& operator>>(DoubleT& t) { - static_assert(std::numeric_limits::is_iec559, "This compiler does not support IEEE 754 standard for floating points."); + static_assert(std::numeric_limits::is_iec559, + "This compiler does not support IEEE 754 standard for floating points."); if (_rPos + sizeof(DoubleT) > _storage.size()) throw end_of_buffer{}; @@ -167,12 +172,12 @@ class MessageBuffer // -------------------------------------------------------------------------------- // Enums - template::value, int> = 0> + template ::value, int> = 0> inline MessageBuffer& operator<<(T t) { return operator<<(static_cast>(t)); } - template::value, int> = 0> + template ::value, int> = 0> inline MessageBuffer& operator>>(T& t) { return operator>>(reinterpret_cast&>(t)); @@ -193,9 +198,9 @@ class MessageBuffer inline MessageBuffer& operator>>(std::vector& vector); // -------------------------------------------------------------------------------- // std::vector - template + template inline MessageBuffer& operator<<(const std::vector& vector); - template + template inline MessageBuffer& operator>>(std::vector& vector); // -------------------------------------------------------------------------------- // Util::SharedVector @@ -212,15 +217,15 @@ class MessageBuffer // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // std::array - template + template inline MessageBuffer& operator<<(const std::array& array); - template + template inline MessageBuffer& operator>>(std::array& array); // -------------------------------------------------------------------------------- // std::array - template + template inline MessageBuffer& operator<<(const std::array& array); - template + template inline MessageBuffer& operator>>(std::array& array); // -------------------------------------------------------------------------------- // std::chrono::duration and system_clock::time_point @@ -250,8 +255,9 @@ class MessageBuffer public: void IncreaseCapacity(size_t capacity) { - _storage.reserve( _storage.size() + capacity); + _storage.reserve(_storage.size() + capacity); } + private: // ---------------------------------------- // private members @@ -341,7 +347,7 @@ MessageBuffer& MessageBuffer::operator>>(std::vector& vector) // -------------------------------------------------------------------------------- // std::vector -template +template MessageBuffer& MessageBuffer::operator<<(const std::vector& vector) { if (vector.size() > std::numeric_limits::max()) @@ -358,7 +364,7 @@ MessageBuffer& MessageBuffer::operator<<(const std::vector& vector) return *this; } -template +template MessageBuffer& MessageBuffer::operator>>(std::vector& vector) { uint32_t vectorSize{0u}; @@ -445,7 +451,7 @@ inline MessageBuffer& MessageBuffer::operator>>(Util::SharedVector& shar // -------------------------------------------------------------------------------- // std::array -template +template MessageBuffer& MessageBuffer::operator<<(const std::array& array) { if (array.size() > std::numeric_limits::max()) @@ -461,7 +467,7 @@ MessageBuffer& MessageBuffer::operator<<(const std::array& array) return *this; } -template +template MessageBuffer& MessageBuffer::operator>>(std::array& array) { if (_rPos + array.size() > _storage.size()) @@ -475,7 +481,7 @@ MessageBuffer& MessageBuffer::operator>>(std::array& array) // -------------------------------------------------------------------------------- // std::array -template +template MessageBuffer& MessageBuffer::operator<<(const std::array& array) { if (array.size() > std::numeric_limits::max()) @@ -486,7 +492,7 @@ MessageBuffer& MessageBuffer::operator<<(const std::array& array) return *this; } -template +template MessageBuffer& MessageBuffer::operator>>(std::array& array) { if (_rPos + array.size() > _storage.size()) @@ -564,17 +570,15 @@ inline MessageBuffer& MessageBuffer::operator<<(const std::map(msg.size()); for (auto&& kv : msg) { - *this << kv.first - << kv.second - ; + *this << kv.first << kv.second; } return *this; } -inline MessageBuffer& MessageBuffer::operator>>(std::map& updatedMsg) +inline MessageBuffer& MessageBuffer::operator>>(std::map& updatedMsg) { - std::map tmp;// do not modify updatedMsg until we validated the input - uint32_t numElements{ 0 }; + std::map tmp; // do not modify updatedMsg until we validated the input + uint32_t numElements{0}; *this >> numElements; for (auto i = 0u; i < numElements; i++) @@ -620,7 +624,7 @@ inline auto MessageBuffer::GetProtocolVersion() -> ProtocolVersion } -inline auto MessageBuffer::PeekData() const -> SilKit::Util::Span +inline auto MessageBuffer::PeekData() const -> SilKit::Util::Span { return _storage; } diff --git a/SilKit/source/core/internal/ProtocolVersion.hpp b/SilKit/source/core/internal/ProtocolVersion.hpp index 9852e1758..e61545ca4 100644 --- a/SilKit/source/core/internal/ProtocolVersion.hpp +++ b/SilKit/source/core/internal/ProtocolVersion.hpp @@ -43,9 +43,7 @@ inline constexpr auto CurrentProtocolVersion() -> ProtocolVersion inline bool operator==(const ProtocolVersion& lhs, const ProtocolVersion& rhs) { - return lhs.major == rhs.major - && lhs.minor == rhs.minor - ; + return lhs.major == rhs.major && lhs.minor == rhs.minor; } inline bool operator!=(const ProtocolVersion& lhs, const ProtocolVersion& rhs) diff --git a/SilKit/source/core/internal/ServiceConfigKeys.hpp b/SilKit/source/core/internal/ServiceConfigKeys.hpp index e911fe6e5..dbf7e543d 100644 --- a/SilKit/source/core/internal/ServiceConfigKeys.hpp +++ b/SilKit/source/core/internal/ServiceConfigKeys.hpp @@ -32,8 +32,7 @@ const std::string controllerType = "controller.type"; // simulatedController-specific keys // remark: simulated controllers have all attributes of regular controllers in addition to the following -const std::string simulatedControllerOriginalParticipantName = - "controller.netsim.originalParticipantName"; +const std::string simulatedControllerOriginalParticipantName = "controller.netsim.originalParticipantName"; // controllerType-specific values // Bus types diff --git a/SilKit/source/core/internal/ServiceDescriptor.hpp b/SilKit/source/core/internal/ServiceDescriptor.hpp index 6cb5d3d59..ec747f3ef 100644 --- a/SilKit/source/core/internal/ServiceDescriptor.hpp +++ b/SilKit/source/core/internal/ServiceDescriptor.hpp @@ -48,12 +48,18 @@ inline std::string to_string(const ServiceType& serviceType) { switch (serviceType) { - default: return "Unknown"; - case ServiceType::Undefined: return "Undefined"; - case ServiceType::Link: return "Link"; - case ServiceType::Controller: return "Controller"; - case ServiceType::SimulatedController: return "SimulatedController"; - case ServiceType::InternalController: return "InternalController"; + default: + return "Unknown"; + case ServiceType::Undefined: + return "Undefined"; + case ServiceType::Link: + return "Link"; + case ServiceType::Controller: + return "Controller"; + case ServiceType::SimulatedController: + return "SimulatedController"; + case ServiceType::InternalController: + return "InternalController"; } } @@ -85,7 +91,7 @@ class ServiceDescriptor inline auto GetServiceName() const -> const std::string&; inline void SetServiceName(std::string val); - inline auto GetServiceId() const -> SilKit::Core::EndpointId ; + inline auto GetServiceId() const -> SilKit::Core::EndpointId; inline void SetServiceId(SilKit::Core::EndpointId val); inline auto GetSupplementalData() const -> SupplementalData; @@ -104,13 +110,16 @@ class ServiceDescriptor ServiceDescriptor& operator=(ServiceDescriptor&&) = default; ServiceDescriptor& operator=(const ServiceDescriptor&) = default; // for unit tests - inline ServiceDescriptor(std::string participantName, std::string networkName, std::string serviceName, EndpointId serviceId); + inline ServiceDescriptor(std::string participantName, std::string networkName, std::string serviceName, + EndpointId serviceId); + private: // Ser/Des friend auto operator<<(SilKit::Core::MessageBuffer& buffer, - const SilKit::Core::ServiceDescriptor& msg) -> SilKit::Core::MessageBuffer&; + const SilKit::Core::ServiceDescriptor& msg) -> SilKit::Core::MessageBuffer&; friend auto operator>>(SilKit::Core::MessageBuffer& buffer, - SilKit::Core::ServiceDescriptor& updatedMsg) -> SilKit::Core::MessageBuffer&; + SilKit::Core::ServiceDescriptor& updatedMsg) -> SilKit::Core::MessageBuffer&; + private: std::string _participantName; //!< name of the participant ParticipantId _participantId{0}; @@ -125,8 +134,8 @@ class ServiceDescriptor ////////////////////////////////////////////////////////////////////// // Inline Implementations ////////////////////////////////////////////////////////////////////// - -bool ServiceDescriptor::GetSupplementalDataItem(const std::string& key, std::string& value) const + +bool ServiceDescriptor::GetSupplementalDataItem(const std::string& key, std::string& value) const { auto valueIter = _supplementalData.find(key); if (valueIter == _supplementalData.end()) @@ -139,7 +148,7 @@ bool ServiceDescriptor::GetSupplementalDataItem(const std::string& key, std::str void ServiceDescriptor::SetSupplementalDataItem(std::string key, std::string val) { - _supplementalData[key] = std::move(val); + _supplementalData[key] = std::move(val); } auto ServiceDescriptor::GetParticipantId() const -> ParticipantId @@ -213,7 +222,7 @@ void ServiceDescriptor::SetServiceId(SilKit::Core::EndpointId val) _serviceId = std::move(val); } -auto ServiceDescriptor::GetSupplementalData() const -> SupplementalData +auto ServiceDescriptor::GetSupplementalData() const -> SupplementalData { return _supplementalData; } @@ -244,7 +253,7 @@ void ServiceDescriptor::SetSimulationName(const std::string& simulationName) //Ctors ServiceDescriptor::ServiceDescriptor(std::string participantName, std::string networkName, std::string serviceName, - EndpointId serviceId) + EndpointId serviceId) { SetParticipantNameAndComputeId(std::move(participantName)); SetNetworkName(std::move(networkName)); @@ -255,12 +264,8 @@ ServiceDescriptor::ServiceDescriptor(std::string participantName, std::string ne // operators inline bool ServiceDescriptor::operator==(const ServiceDescriptor& rhs) const { - return - GetParticipantId() == rhs.GetParticipantId() - && GetNetworkName() == rhs.GetNetworkName() - && GetServiceType() == rhs.GetServiceType() - && GetServiceId() == rhs.GetServiceId() - ; + return GetParticipantId() == rhs.GetParticipantId() && GetNetworkName() == rhs.GetNetworkName() + && GetServiceType() == rhs.GetServiceType() && GetServiceId() == rhs.GetServiceId(); } inline bool ServiceDescriptor::operator!=(const ServiceDescriptor& rhs) const @@ -270,24 +275,15 @@ inline bool ServiceDescriptor::operator!=(const ServiceDescriptor& rhs) const std::string ServiceDescriptor::to_string() const { - const std::string separator{ "/" }; + const std::string separator{"/"}; std::string controllerTypeName; // common std::stringstream ss; - ss - << GetParticipantName() - << separator - << SilKit::Core::to_string(GetServiceType()) - ; + ss << GetParticipantName() << separator << SilKit::Core::to_string(GetServiceType()); switch (GetServiceType()) { case ServiceType::Link: - ss - << separator - << Config::to_string(GetNetworkType()) - << separator - << GetNetworkName() - ; + ss << separator << Config::to_string(GetNetworkType()) << separator << GetNetworkName(); break; case ServiceType::Controller: case ServiceType::SimulatedController: @@ -296,29 +292,14 @@ std::string ServiceDescriptor::to_string() const throw LogicError("supplementalData.size() > 0"); } - ss - << separator - << controllerTypeName - << separator - << GetNetworkName() - << separator - << GetServiceName() - ; + ss << separator << controllerTypeName << separator << GetNetworkName() << separator << GetServiceName(); break; case ServiceType::InternalController: - ss - << separator - << GetServiceName() - ; + ss << separator << GetServiceName(); break; case ServiceType::Undefined: - ss - << separator - << GetNetworkName() - << separator - << GetServiceName() - ; - break; + ss << separator << GetNetworkName() << separator << GetServiceName(); + break; } return ss.str(); } diff --git a/SilKit/source/core/internal/TestDataTraits.hpp b/SilKit/source/core/internal/TestDataTraits.hpp index 04bb0d5dd..c3514fd32 100644 --- a/SilKit/source/core/internal/TestDataTraits.hpp +++ b/SilKit/source/core/internal/TestDataTraits.hpp @@ -31,16 +31,16 @@ namespace Core { // Traits for internal testing data types for wire protocol versioning and evolution ////////////////////////////////////////////////////////////////////// DefineSilKitMsgTrait_TypeName(SilKit::Core::Tests::Version1, TestMessage) -DefineSilKitMsgTrait_SerdesName(SilKit::Core::Tests::Version1::TestMessage, "TESTMESSAGE"); + DefineSilKitMsgTrait_SerdesName(SilKit::Core::Tests::Version1::TestMessage, "TESTMESSAGE"); DefineSilKitMsgTrait_Version(SilKit::Core::Tests::Version1::TestMessage, 1); DefineSilKitMsgTrait_TypeName(SilKit::Core::Tests::Version2, TestMessage) -DefineSilKitMsgTrait_SerdesName(SilKit::Core::Tests::Version2::TestMessage, "TESTMESSAGE"); + DefineSilKitMsgTrait_SerdesName(SilKit::Core::Tests::Version2::TestMessage, "TESTMESSAGE"); DefineSilKitMsgTrait_Version(SilKit::Core::Tests::Version2::TestMessage, 2); DefineSilKitMsgTrait_TypeName(SilKit::Core::Tests, TestFrameEvent) -//The renamed TestMessage must have the same SerdesName as the previous struct -DefineSilKitMsgTrait_SerdesName(SilKit::Core::Tests::TestFrameEvent, "TESTMESSAGE"); + //The renamed TestMessage must have the same SerdesName as the previous struct + DefineSilKitMsgTrait_SerdesName(SilKit::Core::Tests::TestFrameEvent, "TESTMESSAGE"); DefineSilKitMsgTrait_Version(SilKit::Core::Tests::TestFrameEvent, 3); } // namespace Core diff --git a/SilKit/source/core/internal/TestDataTypes.hpp b/SilKit/source/core/internal/TestDataTypes.hpp index 4c7fc1ec7..606ae8658 100644 --- a/SilKit/source/core/internal/TestDataTypes.hpp +++ b/SilKit/source/core/internal/TestDataTypes.hpp @@ -61,25 +61,25 @@ struct TestFrameEvent // String Utils ////////////////////////////////////////////////////////////////////// -namespace Version1 { -inline std::ostream& operator<<(std::ostream& out , const TestMessage& msg) +namespace Version1 { +inline std::ostream& operator<<(std::ostream& out, const TestMessage& msg) { - out <<"version1:TestMessage{" << msg.integer <<",\"" << msg.str << "\"}"; + out << "version1:TestMessage{" << msg.integer << ",\"" << msg.str << "\"}"; return out; } } // namespace Version1 inline namespace Version2 { -inline std::ostream& operator<<(std::ostream& out , const TestMessage& msg) +inline std::ostream& operator<<(std::ostream& out, const TestMessage& msg) { - out <<"version2:TestMessage{" << msg.integer <<",\"" << msg.str << "\"}"; + out << "version2:TestMessage{" << msg.integer << ",\"" << msg.str << "\"}"; return out; } } // namespace Version2 -inline std::ostream& operator<<(std::ostream& out , const TestFrameEvent& msg) +inline std::ostream& operator<<(std::ostream& out, const TestFrameEvent& msg) { - out <<"TestFrameEvent{" << msg.integer <<",\"" << msg.str << "\"}"; + out << "TestFrameEvent{" << msg.integer << ",\"" << msg.str << "\"}"; return out; } diff --git a/SilKit/source/core/internal/Test_InternalSerdes.cpp b/SilKit/source/core/internal/Test_InternalSerdes.cpp index 910dbd3a6..a987ed065 100644 --- a/SilKit/source/core/internal/Test_InternalSerdes.cpp +++ b/SilKit/source/core/internal/Test_InternalSerdes.cpp @@ -27,9 +27,9 @@ TEST(Test_InternalSerdes, Mw_EndpointAddress) { SilKit::Core::MessageBuffer buffer; - SilKit::Core::EndpointAddress in{3,7}; - SilKit::Core::EndpointAddress out{1,1}; - + SilKit::Core::EndpointAddress in{3, 7}; + SilKit::Core::EndpointAddress out{1, 1}; + buffer << in; buffer >> out; @@ -40,13 +40,13 @@ TEST(Test_InternalSerdes, Mw_EndpointAddress_multiple) { SilKit::Core::MessageBuffer buffer; - SilKit::Core::EndpointAddress in1{3,7}; - SilKit::Core::EndpointAddress in2{4,8}; - SilKit::Core::EndpointAddress in3{5,9}; + SilKit::Core::EndpointAddress in1{3, 7}; + SilKit::Core::EndpointAddress in2{4, 8}; + SilKit::Core::EndpointAddress in3{5, 9}; - SilKit::Core::EndpointAddress out1{1,1}; - SilKit::Core::EndpointAddress out2{2,2}; - SilKit::Core::EndpointAddress out3{3,3}; + SilKit::Core::EndpointAddress out1{1, 1}; + SilKit::Core::EndpointAddress out2{2, 2}; + SilKit::Core::EndpointAddress out3{3, 3}; buffer << in1 << in2 << in3; buffer >> out1 >> out2 >> out3; @@ -55,4 +55,3 @@ TEST(Test_InternalSerdes, Mw_EndpointAddress_multiple) EXPECT_EQ(in2, out2); EXPECT_EQ(in3, out3); } - diff --git a/SilKit/source/core/internal/Test_MessageBuffer.cpp b/SilKit/source/core/internal/Test_MessageBuffer.cpp index c05164c46..ff1f73ed7 100644 --- a/SilKit/source/core/internal/Test_MessageBuffer.cpp +++ b/SilKit/source/core/internal/Test_MessageBuffer.cpp @@ -33,7 +33,7 @@ TEST(Test_MessageBuffer, integral_types) int32_t in{7}; int32_t out{1}; - + buffer << in; buffer >> out; @@ -45,7 +45,7 @@ TEST(Test_MessageBuffer, integral_types_multiple) { SilKit::Core::MessageBuffer buffer; - std::vector in{1,2,3,4,5,6,7}; + std::vector in{1, 2, 3, 4, 5, 6, 7}; std::vector out(in.size(), -1); for (auto i : in) @@ -53,7 +53,7 @@ TEST(Test_MessageBuffer, integral_types_multiple) for (auto& o : out) buffer >> o; - + EXPECT_EQ(in, out); } @@ -74,7 +74,7 @@ TEST(Test_MessageBuffer, floating_types_multiple) { SilKit::Core::MessageBuffer buffer; - std::vector in{1,2,3,4,5,6,7}; + std::vector in{1, 2, 3, 4, 5, 6, 7}; std::vector out(in.size(), -1); for (auto i : in) @@ -154,7 +154,7 @@ TEST(Test_MessageBuffer, std_array_uint8_t) { SilKit::Core::MessageBuffer buffer; - std::array in{ 'A', 2, 3, 4, '.'}; + std::array in{'A', 2, 3, 4, '.'}; std::array out; buffer << in; @@ -195,7 +195,8 @@ TEST(Test_MessageBuffer, std_chrono_system_time) auto now = std::chrono::system_clock::now(); - decltype(now) in = std::chrono::system_clock::time_point{std::chrono::duration_cast(now.time_since_epoch())}; + decltype(now) in = std::chrono::system_clock::time_point{ + std::chrono::duration_cast(now.time_since_epoch())}; decltype(in) out; buffer << in; @@ -205,7 +206,8 @@ TEST(Test_MessageBuffer, std_chrono_system_time) } namespace { -struct TestData { +struct TestData +{ double doub; uint32_t ui32; int16_t i16; @@ -216,13 +218,10 @@ struct TestData { bool operator==(const TestData& lhs, const TestData& rhs) { - return lhs.ui32 == rhs.ui32 - && lhs.i16 == rhs.i16 - && lhs.e == rhs.e - && lhs.duration == rhs.duration - && lhs.str == rhs.str; -} + return lhs.ui32 == rhs.ui32 && lhs.i16 == rhs.i16 && lhs.e == rhs.e && lhs.duration == rhs.duration + && lhs.str == rhs.str; } +} // namespace TEST(Test_MessageBuffer, mixed_types) { diff --git a/SilKit/source/core/internal/internal_fwd.hpp b/SilKit/source/core/internal/internal_fwd.hpp index 1894d8e48..29c519b55 100644 --- a/SilKit/source/core/internal/internal_fwd.hpp +++ b/SilKit/source/core/internal/internal_fwd.hpp @@ -62,5 +62,9 @@ class IRequestReplyService; class IParticipantReplies; } // namespace RequestReply } // namespace Core +namespace Experimental { +namespace NetworkSimulation { +class INetworkSimulator; +} // namespace NetworkSimulation +} // namespace Experimental } // namespace SilKit - diff --git a/SilKit/source/core/internal/string_utils_internal.hpp b/SilKit/source/core/internal/string_utils_internal.hpp index 0b92dd12d..401867110 100644 --- a/SilKit/source/core/internal/string_utils_internal.hpp +++ b/SilKit/source/core/internal/string_utils_internal.hpp @@ -46,9 +46,7 @@ std::string to_string(const SilKit::Core::EndpointAddress& address) std::ostream& operator<<(std::ostream& out, const SilKit::Core::EndpointAddress& address) { - out << "Addr{" << address.participant - << ", " << address.endpoint - << "}"; + out << "Addr{" << address.participant << ", " << address.endpoint << "}"; return out; } diff --git a/SilKit/source/core/internal/string_utils_sync.hpp b/SilKit/source/core/internal/string_utils_sync.hpp index 2ad40e7f0..5d35f73fa 100644 --- a/SilKit/source/core/internal/string_utils_sync.hpp +++ b/SilKit/source/core/internal/string_utils_sync.hpp @@ -52,9 +52,7 @@ std::ostream& operator<<(std::ostream& out, const NextSimTask& nextTask) { auto tp = std::chrono::duration_cast>(nextTask.timePoint); auto duration = std::chrono::duration_cast>(nextTask.duration); - out << "Orchestration::NextSimTask{tp=" << tp.count() - << "ms, duration=" << duration.count() - << "ms}"; + out << "Orchestration::NextSimTask{tp=" << tp.count() << "ms, duration=" << duration.count() << "ms}"; return out; } @@ -62,8 +60,10 @@ std::string to_string(SystemCommand::Kind command) { switch (command) { - case SystemCommand::Kind::Invalid: return "Invalid"; - case SystemCommand::Kind::AbortSimulation: return "AbortSimulation"; + case SystemCommand::Kind::Invalid: + return "Invalid"; + case SystemCommand::Kind::AbortSimulation: + return "AbortSimulation"; } throw SilKit::TypeConversionError{}; } diff --git a/SilKit/source/core/internal/traits/SilKitMsgSerdesName.hpp b/SilKit/source/core/internal/traits/SilKitMsgSerdesName.hpp index c5b1ee1b2..28d85cc83 100644 --- a/SilKit/source/core/internal/traits/SilKitMsgSerdesName.hpp +++ b/SilKit/source/core/internal/traits/SilKitMsgSerdesName.hpp @@ -28,50 +28,58 @@ namespace Core { // The SerdesName must not change, even when the C++ struct's name changes. // This ensures the stability of the wire format of the vasio ser/des. -template struct SilKitMsgTraitSerdesName { static constexpr const char* SerdesName(); }; +template +struct SilKitMsgTraitSerdesName +{ + static constexpr const char* SerdesName(); +}; //helper to reduce boilerplate #define DefineSilKitMsgTrait_SerdesName(TYPE_NAME, SERDES_NAME) \ - template<> \ - struct SilKitMsgTraitSerdesName {\ - static constexpr const char* SerdesName() { return SERDES_NAME; }\ + template <> \ + struct SilKitMsgTraitSerdesName \ + { \ + static constexpr const char* SerdesName() \ + { \ + return SERDES_NAME; \ + } \ } -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Logging::LogMsg, "LOGMSG" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Orchestration::SystemCommand, "SYSTEMCOMMAND" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Orchestration::ParticipantStatus, "PARTICIPANTSTATUS" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Orchestration::WorkflowConfiguration, "WORKFLOWCONFIGURATION" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Orchestration::NextSimTask, "NEXTSIMTASK" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::PubSub::WireDataMessageEvent, "DATAMESSAGEEVENT" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Rpc::FunctionCall, "FUNCTIONCALL" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Rpc::FunctionCallResponse, "FUNCTIONCALLRESPONSE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::WireCanFrameEvent, "CANFRAMEEVENT" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::CanFrameTransmitEvent, "CANFRAMETRANSMITEVENT" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::CanControllerStatus, "CANCONTROLLERSTATUS" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::CanConfigureBaudrate, "CANCONFIGUREBAUDRATE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::CanSetControllerMode, "CANSETCONTROLLERMODE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Ethernet::WireEthernetFrameEvent, "ETHERNETFRAMEEVENT" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Ethernet::EthernetFrameTransmitEvent, "ETHERNETFRAMETRANSMITEVENT" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Ethernet::EthernetStatus, "ETHERNETSTATUS" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Ethernet::EthernetSetMode, "ETHERNETSETMODE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinSendFrameRequest, "SENDFRAMEREQUEST" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinSendFrameHeaderRequest, "SENDFRAMEHEADERREQUEST" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinTransmission, "TRANSMISSION" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinWakeupPulse, "WAKEUPPULSE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::WireLinControllerConfig, "CONTROLLERCONFIG" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinControllerStatusUpdate, "CONTROLLERSTATUSUPDATE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinFrameResponseUpdate, "FRAMERESPONSEUPDATE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::WireFlexrayFrameEvent, "FRMESSAGE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::WireFlexrayFrameTransmitEvent, "FRMESSAGEACK" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexraySymbolEvent, "FRSYMBOL" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexraySymbolTransmitEvent, "FRSYMBOLACK" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayCycleStartEvent, "CYCLESTART" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayHostCommand, "HOSTCOMMAND" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayControllerConfig, "CONTROLLERCONFIG" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayTxBufferConfigUpdate, "TXBUFFERCONFIGUPDATE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::WireFlexrayTxBufferUpdate, "TXBUFFERUPDATE" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayPocStatusEvent, "POCSTATUS" ); -DefineSilKitMsgTrait_SerdesName(SilKit::Core::Discovery::ParticipantDiscoveryEvent, "SERVICEANNOUNCEMENT" ); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Logging::LogMsg, "LOGMSG"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Orchestration::SystemCommand, "SYSTEMCOMMAND"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Orchestration::ParticipantStatus, "PARTICIPANTSTATUS"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Orchestration::WorkflowConfiguration, "WORKFLOWCONFIGURATION"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Orchestration::NextSimTask, "NEXTSIMTASK"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::PubSub::WireDataMessageEvent, "DATAMESSAGEEVENT"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Rpc::FunctionCall, "FUNCTIONCALL"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Rpc::FunctionCallResponse, "FUNCTIONCALLRESPONSE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::WireCanFrameEvent, "CANFRAMEEVENT"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::CanFrameTransmitEvent, "CANFRAMETRANSMITEVENT"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::CanControllerStatus, "CANCONTROLLERSTATUS"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::CanConfigureBaudrate, "CANCONFIGUREBAUDRATE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Can::CanSetControllerMode, "CANSETCONTROLLERMODE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Ethernet::WireEthernetFrameEvent, "ETHERNETFRAMEEVENT"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Ethernet::EthernetFrameTransmitEvent, "ETHERNETFRAMETRANSMITEVENT"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Ethernet::EthernetStatus, "ETHERNETSTATUS"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Ethernet::EthernetSetMode, "ETHERNETSETMODE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinSendFrameRequest, "SENDFRAMEREQUEST"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinSendFrameHeaderRequest, "SENDFRAMEHEADERREQUEST"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinTransmission, "TRANSMISSION"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinWakeupPulse, "WAKEUPPULSE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::WireLinControllerConfig, "CONTROLLERCONFIG"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinControllerStatusUpdate, "CONTROLLERSTATUSUPDATE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Lin::LinFrameResponseUpdate, "FRAMERESPONSEUPDATE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::WireFlexrayFrameEvent, "FRMESSAGE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::WireFlexrayFrameTransmitEvent, "FRMESSAGEACK"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexraySymbolEvent, "FRSYMBOL"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexraySymbolTransmitEvent, "FRSYMBOLACK"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayCycleStartEvent, "CYCLESTART"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayHostCommand, "HOSTCOMMAND"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayControllerConfig, "CONTROLLERCONFIG"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayTxBufferConfigUpdate, "TXBUFFERCONFIGUPDATE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::WireFlexrayTxBufferUpdate, "TXBUFFERUPDATE"); +DefineSilKitMsgTrait_SerdesName(SilKit::Services::Flexray::FlexrayPocStatusEvent, "POCSTATUS"); +DefineSilKitMsgTrait_SerdesName(SilKit::Core::Discovery::ParticipantDiscoveryEvent, "SERVICEANNOUNCEMENT"); DefineSilKitMsgTrait_SerdesName(SilKit::Core::Discovery::ServiceDiscoveryEvent, "SERVICEDISCOVERYEVENT"); DefineSilKitMsgTrait_SerdesName(SilKit::Core::RequestReply::RequestReplyCall, "REQUESTREPLYCALL"); DefineSilKitMsgTrait_SerdesName(SilKit::Core::RequestReply::RequestReplyCallReturn, "REQUESTREPLYCALLRETURN"); diff --git a/SilKit/source/core/internal/traits/SilKitMsgTraits.hpp b/SilKit/source/core/internal/traits/SilKitMsgTraits.hpp old mode 100755 new mode 100644 index c7146acb2..6c077163e --- a/SilKit/source/core/internal/traits/SilKitMsgTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitMsgTraits.hpp @@ -46,13 +46,39 @@ struct HasTimestamp>().time // the silkit messages type traits -template struct SilKitMsgTraitTypeName { static constexpr const char *TypeName(); }; -template struct SilKitMsgTraitHistSize { static constexpr std::size_t HistSize() { return 0; } }; -template struct SilKitMsgTraitEnforceSelfDelivery { static constexpr bool IsSelfDeliveryEnforced() { return false; } }; -template struct SilKitMsgTraitForbidSelfDelivery { static constexpr bool IsSelfDeliveryForbidden() { return false; } }; +template +struct SilKitMsgTraitTypeName +{ + static constexpr const char* TypeName(); +}; +template +struct SilKitMsgTraitHistSize +{ + static constexpr std::size_t HistSize() + { + return 0; + } +}; +template +struct SilKitMsgTraitEnforceSelfDelivery +{ + static constexpr bool IsSelfDeliveryEnforced() + { + return false; + } +}; +template +struct SilKitMsgTraitForbidSelfDelivery +{ + static constexpr bool IsSelfDeliveryForbidden() + { + return false; + } +}; // The final message traits -template struct SilKitMsgTraits +template +struct SilKitMsgTraits : SilKitMsgTraitTypeName , SilKitMsgTraitHistSize , SilKitMsgTraitEnforceSelfDelivery @@ -62,71 +88,126 @@ template struct SilKitMsgTraits { }; -#define DefineSilKitMsgTrait_TypeName(Namespace, MsgName) template<> struct SilKitMsgTraitTypeName{\ - static constexpr const char* TypeName() { return #Namespace "::" #MsgName; }\ +#define DefineSilKitMsgTrait_TypeName(Namespace, MsgName) \ + template <> \ + struct SilKitMsgTraitTypeName \ + { \ + static constexpr const char* TypeName() \ + { \ + return #Namespace "::" #MsgName; \ + } \ }; -#define DefineSilKitMsgTrait_HistSize(Namespace, MsgName, HistorySize) template<> struct SilKitMsgTraitHistSize{\ - static constexpr std::size_t HistSize() { return HistorySize; } \ +#define DefineSilKitMsgTrait_HistSize(Namespace, MsgName, HistorySize) \ + template <> \ + struct SilKitMsgTraitHistSize \ + { \ + static constexpr std::size_t HistSize() \ + { \ + return HistorySize; \ + } \ }; -#define DefineSilKitMsgTrait_EnforceSelfDelivery(Namespace, MsgName) template<> struct SilKitMsgTraitEnforceSelfDelivery{\ - static constexpr bool IsSelfDeliveryEnforced() { return true; }\ +#define DefineSilKitMsgTrait_EnforceSelfDelivery(Namespace, MsgName) \ + template <> \ + struct SilKitMsgTraitEnforceSelfDelivery \ + { \ + static constexpr bool IsSelfDeliveryEnforced() \ + { \ + return true; \ + } \ }; -#define DefineSilKitMsgTrait_ForbidSelfDelivery(Namespace, MsgName) template<> struct SilKitMsgTraitForbidSelfDelivery{\ - static constexpr bool IsSelfDeliveryForbidden() { return true; }\ +#define DefineSilKitMsgTrait_ForbidSelfDelivery(Namespace, MsgName) \ + template <> \ + struct SilKitMsgTraitForbidSelfDelivery \ + { \ + static constexpr bool IsSelfDeliveryForbidden() \ + { \ + return true; \ + } \ }; -DefineSilKitMsgTrait_TypeName(SilKit::Services::Logging, LogMsg) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Orchestration, SystemCommand) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Orchestration, ParticipantStatus) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Orchestration, WorkflowConfiguration) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Orchestration, NextSimTask) -DefineSilKitMsgTrait_TypeName(SilKit::Services::PubSub, WireDataMessageEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Rpc, FunctionCall) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Rpc, FunctionCallResponse) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Can, WireCanFrameEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Can, CanFrameTransmitEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Can, CanControllerStatus) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Can, CanConfigureBaudrate) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Can, CanSetControllerMode) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Ethernet, WireEthernetFrameEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Ethernet, EthernetFrameTransmitEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Ethernet, EthernetStatus) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Ethernet, EthernetSetMode) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, LinSendFrameRequest) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, LinSendFrameHeaderRequest) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, LinTransmission) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, LinWakeupPulse) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, WireLinControllerConfig) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, LinControllerStatusUpdate) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, LinFrameResponseUpdate) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, WireFlexrayFrameEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, WireFlexrayFrameTransmitEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, FlexraySymbolEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, FlexraySymbolTransmitEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, FlexrayCycleStartEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, FlexrayHostCommand) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, FlexrayControllerConfig) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, FlexrayTxBufferConfigUpdate) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, WireFlexrayTxBufferUpdate) -DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, FlexrayPocStatusEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Core::Discovery, ParticipantDiscoveryEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Core::Discovery, ServiceDiscoveryEvent) -DefineSilKitMsgTrait_TypeName(SilKit::Core::RequestReply, RequestReplyCall) -DefineSilKitMsgTrait_TypeName(SilKit::Core::RequestReply, RequestReplyCallReturn) - -// Messages with history -DefineSilKitMsgTrait_HistSize(SilKit::Services::Orchestration, ParticipantStatus, 1) -DefineSilKitMsgTrait_HistSize(SilKit::Core::Discovery, ParticipantDiscoveryEvent, 1) -DefineSilKitMsgTrait_HistSize(SilKit::Services::PubSub, WireDataMessageEvent, 1) -DefineSilKitMsgTrait_HistSize(SilKit::Services::Orchestration, WorkflowConfiguration, 1) -DefineSilKitMsgTrait_HistSize(SilKit::Services::Lin, WireLinControllerConfig, 1) - -// Messages with enforced self delivery -DefineSilKitMsgTrait_EnforceSelfDelivery(SilKit::Services::Orchestration, ParticipantStatus) -DefineSilKitMsgTrait_EnforceSelfDelivery(SilKit::Services::Lin, LinSendFrameHeaderRequest) - -// Messages with forbidden self delivery -DefineSilKitMsgTrait_ForbidSelfDelivery(SilKit::Services::Orchestration, SystemCommand) +DefineSilKitMsgTrait_TypeName(SilKit::Services::Logging, LogMsg) DefineSilKitMsgTrait_TypeName( + SilKit::Services::Orchestration, + SystemCommand) DefineSilKitMsgTrait_TypeName(SilKit::Services::Orchestration, + ParticipantStatus) DefineSilKitMsgTrait_TypeName(SilKit::Services:: + Orchestration, + WorkflowConfiguration) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Orchestration, NextSimTask) DefineSilKitMsgTrait_TypeName( + SilKit::Services::PubSub, WireDataMessageEvent) DefineSilKitMsgTrait_TypeName(SilKit::Services::Rpc, + FunctionCall) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Rpc, FunctionCallResponse) DefineSilKitMsgTrait_TypeName( + SilKit::Services::Can, WireCanFrameEvent) DefineSilKitMsgTrait_TypeName(SilKit::Services::Can, + CanFrameTransmitEvent) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Can, CanControllerStatus) DefineSilKitMsgTrait_TypeName( + SilKit::Services::Can, CanConfigureBaudrate) DefineSilKitMsgTrait_TypeName(SilKit::Services::Can, + CanSetControllerMode) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Ethernet, + WireEthernetFrameEvent) DefineSilKitMsgTrait_TypeName(SilKit::Services::Ethernet, + EthernetFrameTransmitEvent) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Ethernet, + EthernetStatus) DefineSilKitMsgTrait_TypeName(SilKit::Services::Ethernet, EthernetSetMode) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Lin, + LinSendFrameRequest) DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, + LinSendFrameHeaderRequest) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Lin, + LinTransmission) DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, LinWakeupPulse) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Lin, + WireLinControllerConfig) DefineSilKitMsgTrait_TypeName(SilKit::Services::Lin, + LinControllerStatusUpdate) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Lin, + LinFrameResponseUpdate) DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, + WireFlexrayFrameEvent) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, + WireFlexrayFrameTransmitEvent) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, FlexraySymbolEvent) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, + FlexraySymbolTransmitEvent) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, + FlexrayCycleStartEvent) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, + FlexrayHostCommand) + DefineSilKitMsgTrait_TypeName(SilKit::Services::Flexray, + FlexrayControllerConfig) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Flexray, + FlexrayTxBufferConfigUpdate) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Flexray, + WireFlexrayTxBufferUpdate) + DefineSilKitMsgTrait_TypeName( + SilKit::Services::Flexray, + FlexrayPocStatusEvent) + DefineSilKitMsgTrait_TypeName( + SilKit::Core::Discovery, + ParticipantDiscoveryEvent) + DefineSilKitMsgTrait_TypeName( + SilKit::Core::Discovery, + ServiceDiscoveryEvent) + DefineSilKitMsgTrait_TypeName( + SilKit::Core::RequestReply, + RequestReplyCall) + DefineSilKitMsgTrait_TypeName( + SilKit::Core::RequestReply, + RequestReplyCallReturn) + + // Messages with history + DefineSilKitMsgTrait_HistSize(SilKit::Services::Orchestration, ParticipantStatus, 1) + DefineSilKitMsgTrait_HistSize(SilKit::Core::Discovery, ParticipantDiscoveryEvent, 1) + DefineSilKitMsgTrait_HistSize(SilKit::Services::PubSub, WireDataMessageEvent, 1) + DefineSilKitMsgTrait_HistSize(SilKit::Services::Orchestration, WorkflowConfiguration, 1) + DefineSilKitMsgTrait_HistSize(SilKit::Services::Lin, WireLinControllerConfig, 1) + + // Messages with enforced self delivery + DefineSilKitMsgTrait_EnforceSelfDelivery(SilKit::Services::Orchestration, ParticipantStatus) + DefineSilKitMsgTrait_EnforceSelfDelivery(SilKit::Services::Lin, LinSendFrameHeaderRequest) + + // Messages with forbidden self delivery + DefineSilKitMsgTrait_ForbidSelfDelivery(SilKit::Services::Orchestration, SystemCommand) } // namespace Core } // namespace SilKit diff --git a/SilKit/source/core/internal/traits/SilKitMsgVersion.hpp b/SilKit/source/core/internal/traits/SilKitMsgVersion.hpp old mode 100755 new mode 100644 index e78ad1c12..aba7ccda9 --- a/SilKit/source/core/internal/traits/SilKitMsgVersion.hpp +++ b/SilKit/source/core/internal/traits/SilKitMsgVersion.hpp @@ -27,13 +27,21 @@ namespace Core { // the silkit messages type traits using VersionT = uint32_t; -template struct SilKitMsgTraitVersion { static constexpr VersionT Version(); }; +template +struct SilKitMsgTraitVersion +{ + static constexpr VersionT Version(); +}; //helper to reduce boilerplate #define DefineSilKitMsgTrait_Version(TYPE_NAME, VERSION) \ - template<> \ - struct SilKitMsgTraitVersion {\ - static constexpr VersionT Version() { return VERSION; }\ + template <> \ + struct SilKitMsgTraitVersion \ + { \ + static constexpr VersionT Version() \ + { \ + return VERSION; \ + } \ } DefineSilKitMsgTrait_Version(SilKit::Services::Logging::LogMsg, 1); diff --git a/SilKit/source/core/internal/traits/SilKitServiceConfigTraits.hpp b/SilKit/source/core/internal/traits/SilKitServiceConfigTraits.hpp index 0e8081d80..bd22da556 100644 --- a/SilKit/source/core/internal/traits/SilKitServiceConfigTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitServiceConfigTraits.hpp @@ -30,17 +30,19 @@ namespace SilKit { //Trait: associate a configuration type to the service type ////////////////////////////////////////////////////////////////////// template -struct SilKitServiceTraitConfigType { +struct SilKitServiceTraitConfigType +{ // not defined by default: using type = SomeType using type = void; }; -template +template using SilKitServiceTraitConfigType_t = typename SilKitServiceTraitConfigType::type; #define DefineSilKitServiceTrait_ConfigType(SERVICE_NAME, CONFIG_TYPE) \ - template<> \ - struct SilKitServiceTraitConfigType{\ + template <> \ + struct SilKitServiceTraitConfigType \ + { \ using type = CONFIG_TYPE; \ } @@ -59,12 +61,16 @@ DefineSilKitServiceTrait_ConfigType(SilKit::Services::Rpc::RpcServerInternal, Si DefineSilKitServiceTrait_ConfigType(SilKit::Services::Logging::LogMsgReceiver, SilKit::Config::InternalController); DefineSilKitServiceTrait_ConfigType(SilKit::Services::Logging::LogMsgSender, SilKit::Config::InternalController); -DefineSilKitServiceTrait_ConfigType(SilKit::Services::Orchestration::TimeSyncService, SilKit::Config::InternalController); -DefineSilKitServiceTrait_ConfigType(SilKit::Services::Orchestration::LifecycleService, SilKit::Config::InternalController); +DefineSilKitServiceTrait_ConfigType(SilKit::Services::Orchestration::TimeSyncService, + SilKit::Config::InternalController); +DefineSilKitServiceTrait_ConfigType(SilKit::Services::Orchestration::LifecycleService, + SilKit::Config::InternalController); DefineSilKitServiceTrait_ConfigType(SilKit::Services::Orchestration::SystemMonitor, SilKit::Config::InternalController); -DefineSilKitServiceTrait_ConfigType(SilKit::Services::Orchestration::SystemController, SilKit::Config::InternalController); +DefineSilKitServiceTrait_ConfigType(SilKit::Services::Orchestration::SystemController, + SilKit::Config::InternalController); DefineSilKitServiceTrait_ConfigType(SilKit::Core::Discovery::ServiceDiscovery, SilKit::Config::InternalController); -DefineSilKitServiceTrait_ConfigType(SilKit::Core::RequestReply::RequestReplyService, SilKit::Config::InternalController); +DefineSilKitServiceTrait_ConfigType(SilKit::Core::RequestReply::RequestReplyService, + SilKit::Config::InternalController); ////////////////////////////////////////////////////////////////////// @@ -72,27 +78,38 @@ DefineSilKitServiceTrait_ConfigType(SilKit::Core::RequestReply::RequestReplyServ ////////////////////////////////////////////////////////////////////// template -struct SilKitServiceTraitServiceType { - constexpr static auto GetServiceType() -> Core::ServiceType { +struct SilKitServiceTraitServiceType +{ + constexpr static auto GetServiceType() -> Core::ServiceType + { return Core::ServiceType::Controller; // Most services are actual controllers } }; #define DefineSilKitServiceTrait_ServiceType(SERVICE_NAME, SERVICE_TYPE_VALUE) \ - template<> \ - struct SilKitServiceTraitServiceType{\ + template <> \ + struct SilKitServiceTraitServiceType \ + { \ constexpr static auto GetServiceType() -> Core::ServiceType \ { \ return SERVICE_TYPE_VALUE; \ } \ } -DefineSilKitServiceTrait_ServiceType(SilKit::Core::Discovery::ServiceDiscovery, SilKit::Core::ServiceType::InternalController); -DefineSilKitServiceTrait_ServiceType(SilKit::Services::Orchestration::SystemController, SilKit::Core::ServiceType::InternalController); -DefineSilKitServiceTrait_ServiceType(SilKit::Services::Orchestration::SystemMonitor, SilKit::Core::ServiceType::InternalController); -DefineSilKitServiceTrait_ServiceType(SilKit::Services::Orchestration::TimeSyncService, SilKit::Core::ServiceType::InternalController); -DefineSilKitServiceTrait_ServiceType(SilKit::Services::Orchestration::LifecycleService, SilKit::Core::ServiceType::InternalController); -DefineSilKitServiceTrait_ServiceType(SilKit::Services::Logging::LogMsgReceiver, SilKit::Core::ServiceType::InternalController); -DefineSilKitServiceTrait_ServiceType(SilKit::Services::Logging::LogMsgSender, SilKit::Core::ServiceType::InternalController); -DefineSilKitServiceTrait_ServiceType(SilKit::Core::RequestReply::RequestReplyService, SilKit::Core::ServiceType::InternalController); +DefineSilKitServiceTrait_ServiceType(SilKit::Core::Discovery::ServiceDiscovery, + SilKit::Core::ServiceType::InternalController); +DefineSilKitServiceTrait_ServiceType(SilKit::Services::Orchestration::SystemController, + SilKit::Core::ServiceType::InternalController); +DefineSilKitServiceTrait_ServiceType(SilKit::Services::Orchestration::SystemMonitor, + SilKit::Core::ServiceType::InternalController); +DefineSilKitServiceTrait_ServiceType(SilKit::Services::Orchestration::TimeSyncService, + SilKit::Core::ServiceType::InternalController); +DefineSilKitServiceTrait_ServiceType(SilKit::Services::Orchestration::LifecycleService, + SilKit::Core::ServiceType::InternalController); +DefineSilKitServiceTrait_ServiceType(SilKit::Services::Logging::LogMsgReceiver, + SilKit::Core::ServiceType::InternalController); +DefineSilKitServiceTrait_ServiceType(SilKit::Services::Logging::LogMsgSender, + SilKit::Core::ServiceType::InternalController); +DefineSilKitServiceTrait_ServiceType(SilKit::Core::RequestReply::RequestReplyService, + SilKit::Core::ServiceType::InternalController); } // namespace SilKit diff --git a/SilKit/source/core/internal/traits/SilKitServiceTraits.hpp b/SilKit/source/core/internal/traits/SilKitServiceTraits.hpp index 2ea63794b..2938daec6 100644 --- a/SilKit/source/core/internal/traits/SilKitServiceTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitServiceTraits.hpp @@ -27,26 +27,39 @@ namespace Core { // the silkit services type traits template -struct SilKitServiceTraitUseAsyncRegistration { - static constexpr bool UseAsyncRegistration() { +struct SilKitServiceTraitUseAsyncRegistration +{ + static constexpr bool UseAsyncRegistration() + { return false; } }; // The final service traits -template struct SilKitServiceTraits - : SilKitServiceTraitUseAsyncRegistration +template +struct SilKitServiceTraits : SilKitServiceTraitUseAsyncRegistration { }; -#define DefineSilKitServiceTrait_UseAsyncRegistration(Namespace, ServiceName) template<> struct SilKitServiceTraitUseAsyncRegistration{\ - static constexpr bool UseAsyncRegistration() { return true;}\ +#define DefineSilKitServiceTrait_UseAsyncRegistration(Namespace, ServiceName) \ + template <> \ + struct SilKitServiceTraitUseAsyncRegistration \ + { \ + static constexpr bool UseAsyncRegistration() \ + { \ + return true; \ + } \ } -// Services that are registered asynchronously (= not in main thread but in IO-Worker thread on an incoming SilKitMessage) +// Services that are registered asynchronously (= not in main thread but in IO-Worker thread on an incoming SilKitMessage) DefineSilKitServiceTrait_UseAsyncRegistration(SilKit::Services::PubSub, DataSubscriberInternal); DefineSilKitServiceTrait_UseAsyncRegistration(SilKit::Services::Rpc, RpcServerInternal); +DefineSilKitServiceTrait_UseAsyncRegistration(SilKit::Services::Can, IMsgForCanSimulator); +DefineSilKitServiceTrait_UseAsyncRegistration(SilKit::Services::Ethernet, IMsgForEthSimulator); +DefineSilKitServiceTrait_UseAsyncRegistration(SilKit::Services::Flexray, IMsgForFlexraySimulator); +DefineSilKitServiceTrait_UseAsyncRegistration(SilKit::Services::Lin, IMsgForLinSimulator); + } // namespace Core } // namespace SilKit diff --git a/SilKit/source/core/internal/traits/SilKitServices_fwd.hpp b/SilKit/source/core/internal/traits/SilKitServices_fwd.hpp index be291c592..65a18e3f1 100644 --- a/SilKit/source/core/internal/traits/SilKitServices_fwd.hpp +++ b/SilKit/source/core/internal/traits/SilKitServices_fwd.hpp @@ -33,17 +33,17 @@ struct RpcClient; struct RpcServer; struct DataPublisher; struct DataSubscriber; -} //v1 -}//Config +} // namespace v1 +} // namespace Config namespace Core { namespace Discovery { class ServiceDiscovery; -}//Discovery +} // namespace Discovery namespace RequestReply { class RequestReplyService; -} //RequestReply -}//Core +} // namespace RequestReply +} // namespace Core namespace Services { namespace Orchestration { @@ -51,34 +51,34 @@ class TimeSyncService; class LifecycleService; class SystemMonitor; class SystemController; -}//Orchestration +} // namespace Orchestration namespace Logging { class LogMsgReceiver; class LogMsgSender; -} //Logging +} // namespace Logging namespace Ethernet { class EthController; -} //Can +} // namespace Ethernet namespace Can { class CanController; -} //Can +} // namespace Can namespace Lin { class LinController; -} //Lin +} // namespace Lin namespace Flexray { class FlexrayController; -} //Flexray +} // namespace Flexray namespace PubSub { class DataPublisher; -class DataSubscriber ; +class DataSubscriber; class DataSubscriberInternal; -} //PubSub +} // namespace PubSub namespace Rpc { class RpcServer; -class RpcClient ; +class RpcClient; class RpcServerInternal; -} //Rpc +} // namespace Rpc -} //Services +} // namespace Services } // namespace SilKit diff --git a/SilKit/source/core/mock/nullconnection/NullConnectionParticipant.cpp b/SilKit/source/core/mock/nullconnection/NullConnectionParticipant.cpp old mode 100755 new mode 100644 index 6b6f3fb9c..365e79c86 --- a/SilKit/source/core/mock/nullconnection/NullConnectionParticipant.cpp +++ b/SilKit/source/core/mock/nullconnection/NullConnectionParticipant.cpp @@ -32,8 +32,8 @@ namespace Core { namespace { struct NullConnection { - NullConnection(SilKit::Core::IParticipantInternal*, SilKit::Config::ParticipantConfiguration /*config*/, std::string /*participantName*/, - SilKit::Core::ParticipantId /*participantId*/, + NullConnection(SilKit::Core::IParticipantInternal*, SilKit::Config::ParticipantConfiguration /*config*/, + std::string /*participantName*/, SilKit::Core::ParticipantId /*participantId*/, SilKit::Core::Orchestration::ITimeProvider* /*timeProvider*/, ProtocolVersion) { } @@ -48,13 +48,19 @@ struct NullConnection } template - inline void SetHistoryLengthForLink(size_t /*history*/, SilKitServiceT* /*service*/) {} + inline void SetHistoryLengthForLink(size_t /*history*/, SilKitServiceT* /*service*/) + { + } - template - void SendMsg(const Core::IServiceEndpoint* /*from*/, SilKitMessageT&& /*msg*/) {} + template + void SendMsg(const Core::IServiceEndpoint* /*from*/, SilKitMessageT&& /*msg*/) + { + } - template - void SendMsg(const Core::IServiceEndpoint* /*from*/, const std::string& /*target*/, SilKitMessageT&& /*msg*/) {} + template + void SendMsg(const Core::IServiceEndpoint* /*from*/, const std::string& /*target*/, SilKitMessageT&& /*msg*/) + { + } void OnAllMessagesDelivered(std::function /*callback*/) {} void FlushSendBuffers() {} @@ -64,15 +70,19 @@ struct NullConnection void RegisterMessageReceiver(std::function /*callback*/) {} void RegisterPeerShutdownCallback(std::function /*callback*/) {} - void SetAsyncSubscriptionsCompletionHandler(std::function /*completionHandler*/) {} + void AddAsyncSubscriptionsCompletionHandler(std::function /*completionHandler*/) {} - size_t GetNumberOfConnectedParticipants() { return 0; } + size_t GetNumberOfConnectedParticipants() + { + return 0; + } size_t GetNumberOfRemoteReceivers(const IServiceEndpoint* /*service*/, const std::string& /*msgTypeName*/) { return 0; }; - std::vector GetParticipantNamesOfRemoteReceivers(const IServiceEndpoint* /*service*/, const std::string& /*msgTypeName*/) + std::vector GetParticipantNamesOfRemoteReceivers(const IServiceEndpoint* /*service*/, + const std::string& /*msgTypeName*/) { return {}; }; @@ -83,7 +93,7 @@ struct NullConnection } }; } // anonymous namespace - + auto CreateNullConnectionParticipantImpl(std::shared_ptr participantConfig, const std::string& participantName) -> std::unique_ptr { @@ -93,4 +103,3 @@ auto CreateNullConnectionParticipantImpl(std::shared_ptr participantConfig, const std::string& participantName) - -> std::unique_ptr; +auto CreateNullConnectionParticipantImpl(std::shared_ptr participantConfig, + const std::string& participantName) -> std::unique_ptr; } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/mock/participant/MockParticipant.hpp b/SilKit/source/core/mock/participant/MockParticipant.hpp old mode 100755 new mode 100644 index 7dd7a0918..cb5908089 --- a/SilKit/source/core/mock/participant/MockParticipant.hpp +++ b/SilKit/source/core/mock/participant/MockParticipant.hpp @@ -42,6 +42,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "silkit/services/pubsub/PubSubDatatypes.hpp" #include "silkit/services/rpc/RpcDatatypes.hpp" +#include "silkit/experimental/netsim/INetworkSimulator.hpp" + #include "IParticipantInternal.hpp" #include "IServiceDiscovery.hpp" #include "IRequestReplyService.hpp" @@ -61,12 +63,13 @@ using SilKit::Util::HandlerId; using SilKit::Services::Logging::MockLogger; -class MockLifecycleService - : public Services::Orchestration::ILifecycleService +class MockLifecycleService : public Services::Orchestration::ILifecycleService { public: - MOCK_METHOD(void, SetCommunicationReadyHandler, (SilKit::Services::Orchestration::CommunicationReadyHandler), (override)); - MOCK_METHOD(void, SetCommunicationReadyHandlerAsync, (SilKit::Services::Orchestration::CommunicationReadyHandler), (override)); + MOCK_METHOD(void, SetCommunicationReadyHandler, (SilKit::Services::Orchestration::CommunicationReadyHandler), + (override)); + MOCK_METHOD(void, SetCommunicationReadyHandlerAsync, (SilKit::Services::Orchestration::CommunicationReadyHandler), + (override)); MOCK_METHOD(void, CompleteCommunicationReadyHandlerAsync, (), (override)); MOCK_METHOD(void, SetStartingHandler, (SilKit::Services::Orchestration::StartingHandler), (override)); MOCK_METHOD(void, SetStopHandler, (SilKit::Services::Orchestration::StopHandler), (override)); @@ -81,21 +84,23 @@ class MockLifecycleService MOCK_METHOD(Services::Orchestration::ParticipantStatus&, Status, (), (override, const)); MOCK_METHOD(Services::Orchestration::ITimeSyncService*, GetTimeSyncService, (), ()); MOCK_METHOD(Services::Orchestration::ITimeSyncService*, CreateTimeSyncService, (), (override)); - MOCK_METHOD(void, SetAsyncSubscriptionsCompletionHandler, (std::function /*handler*/)); + MOCK_METHOD(void, AddAsyncSubscriptionsCompletionHandler, (std::function /*handler*/)); MOCK_METHOD(Services::Orchestration::OperationMode, GetOperationMode, (), (const)); }; class MockTimeSyncService : public Services::Orchestration::ITimeSyncService { public: - MOCK_METHOD(void, SetSimulationStepHandler, (SimulationStepHandler task, std::chrono::nanoseconds initialStepSize), (override)); - MOCK_METHOD(void, SetSimulationStepHandlerAsync, (SimulationStepHandler task, std::chrono::nanoseconds initialStepSize), + MOCK_METHOD(void, SetSimulationStepHandler, (SimulationStepHandler task, std::chrono::nanoseconds initialStepSize), (override)); + MOCK_METHOD(void, SetSimulationStepHandlerAsync, + (SimulationStepHandler task, std::chrono::nanoseconds initialStepSize), (override)); MOCK_METHOD(void, CompleteSimulationStep, (), (override)); MOCK_METHOD(std::chrono::nanoseconds, Now, (), (override, const)); }; -class MockSystemMonitor : public Services::Orchestration::ISystemMonitor { +class MockSystemMonitor : public Services::Orchestration::ISystemMonitor +{ public: MOCK_METHOD(HandlerId, AddSystemStateHandler, (SystemStateHandler)); MOCK_METHOD(void, RemoveSystemStateHandler, (HandlerId)); @@ -103,20 +108,23 @@ class MockSystemMonitor : public Services::Orchestration::ISystemMonitor { MOCK_METHOD(HandlerId, AddParticipantStatusHandler, (ParticipantStatusHandler)); MOCK_METHOD(void, RemoveParticipantStatusHandler, (HandlerId)); - MOCK_CONST_METHOD0(SystemState, Services::Orchestration::SystemState()); - MOCK_CONST_METHOD1(ParticipantStatus, const Services::Orchestration::ParticipantStatus&(const std::string& participantName)); + MOCK_CONST_METHOD0(SystemState, Services::Orchestration::SystemState()); + MOCK_CONST_METHOD1(ParticipantStatus, + const Services::Orchestration::ParticipantStatus&(const std::string& participantName)); MOCK_METHOD(void, SetParticipantConnectedHandler, (ParticipantConnectedHandler handler), (override)); MOCK_METHOD(void, SetParticipantDisconnectedHandler, (ParticipantDisconnectedHandler handler), (override)); MOCK_METHOD(bool, IsParticipantConnected, (const std::string& participantName), (const, override)); }; -class MockSystemController : public Experimental::Services::Orchestration::ISystemController { +class MockSystemController : public Experimental::Services::Orchestration::ISystemController +{ public: MOCK_CONST_METHOD0(Run, void()); MOCK_CONST_METHOD0(Stop, void()); MOCK_CONST_METHOD0(AbortSimulation, void()); - MOCK_METHOD((void), SetWorkflowConfiguration, (const SilKit::Services::Orchestration::WorkflowConfiguration& workflowConfiguration)); + MOCK_METHOD((void), SetWorkflowConfiguration, + (const SilKit::Services::Orchestration::WorkflowConfiguration& workflowConfiguration)); }; class MockServiceDiscovery : public Discovery::IServiceDiscovery @@ -124,14 +132,14 @@ class MockServiceDiscovery : public Discovery::IServiceDiscovery public: MOCK_METHOD(void, NotifyServiceCreated, (const ServiceDescriptor& serviceDescriptor), (override)); MOCK_METHOD(void, NotifyServiceRemoved, (const ServiceDescriptor& serviceDescriptor), (override)); - MOCK_METHOD(void, RegisterServiceDiscoveryHandler, (SilKit::Core::Discovery::ServiceDiscoveryHandler handler), (override)); + MOCK_METHOD(void, RegisterServiceDiscoveryHandler, (SilKit::Core::Discovery::ServiceDiscoveryHandler handler), + (override)); MOCK_METHOD(void, RegisterSpecificServiceDiscoveryHandler, (SilKit::Core::Discovery::ServiceDiscoveryHandler handler, const std::string& controllerType, const std::string& topic, const std::vector& labels), (override)); MOCK_METHOD(std::vector, GetServices, (), (const, override)); MOCK_METHOD(void, OnParticpantRemoval, (const std::string& participantName), (override)); - }; class MockRequestReplyService : public RequestReply::IRequestReplyService @@ -149,87 +157,98 @@ class MockRequestReplyService : public RequestReply::IRequestReplyService class MockParticipantReplies : public RequestReply::IParticipantReplies { public: - void CallAfterAllParticipantsReplied(std::function completionFunction) override - { + { // Directly trigger completionFunction(); } }; +class DummyNetworkSimulator : public Experimental::NetworkSimulation::INetworkSimulator +{ +public: + void SimulateNetwork( + const std::string& /*networkName*/, Experimental::NetworkSimulation::SimulatedNetworkType /*networkType*/, + std::unique_ptr /*simulatedNetwork*/) override + { + } + + void Start() override {} +}; + class DummyParticipant : public IParticipantInternal { public: DummyParticipant() { - ON_CALL(mockLifecycleService, GetTimeSyncService) - .WillByDefault(testing::Return(&mockTimeSyncService)); - ON_CALL(mockLifecycleService, CreateTimeSyncService) - .WillByDefault(testing::Return(&mockTimeSyncService)); - ON_CALL(logger, GetLogLevel()) - .WillByDefault(testing::Return(Services::Logging::Level::Debug)); + ON_CALL(mockLifecycleService, GetTimeSyncService).WillByDefault(testing::Return(&mockTimeSyncService)); + ON_CALL(mockLifecycleService, CreateTimeSyncService).WillByDefault(testing::Return(&mockTimeSyncService)); + ON_CALL(logger, GetLogLevel()).WillByDefault(testing::Return(Services::Logging::Level::Debug)); } - auto CreateCanController(const std::string& /*canonicalName*/, const std::string & /*networkName*/) - -> Services::Can::ICanController* override + auto CreateCanController(const std::string& /*canonicalName*/, + const std::string& /*networkName*/) -> Services::Can::ICanController* override { return nullptr; } - auto CreateEthernetController(const std::string & /*canonicalName*/, const std::string& /*networkName*/) -> Services::Ethernet::IEthernetController* override + auto CreateEthernetController(const std::string& /*canonicalName*/, const std::string& /*networkName*/) + -> Services::Ethernet::IEthernetController* override { return nullptr; } - auto CreateFlexrayController(const std::string& /*canonicalName*/, const std::string & /*networkName*/) - -> Services::Flexray::IFlexrayController* override + auto CreateFlexrayController(const std::string& /*canonicalName*/, + const std::string& /*networkName*/) -> Services::Flexray::IFlexrayController* override { return nullptr; } - auto CreateLinController(const std::string& /*canonicalName*/, const std::string & /*networkName*/) - -> Services::Lin::ILinController* override + auto CreateLinController(const std::string& /*canonicalName*/, + const std::string& /*networkName*/) -> Services::Lin::ILinController* override { return nullptr; } - auto CreateDataPublisher(const std::string& /*canonicalName*/, const SilKit::Services::PubSub::PubSubSpec& /*dataSpec*/, + auto CreateDataPublisher(const std::string& /*canonicalName*/, + const SilKit::Services::PubSub::PubSubSpec& /*dataSpec*/, size_t /*history*/ = 0) -> SilKit::Services::PubSub::IDataPublisher* override { return nullptr; } - auto CreateDataSubscriber(const std::string& /*canonicalName*/, const SilKit::Services::PubSub::PubSubSpec& /*dataSpec*/, + auto CreateDataSubscriber(const std::string& /*canonicalName*/, + const SilKit::Services::PubSub::PubSubSpec& /*dataSpec*/, Services::PubSub::DataMessageHandler /*dataMessageHandler*/) -> SilKit::Services::PubSub::IDataSubscriber* override { return nullptr; } - auto CreateDataSubscriberInternal(const std::string& /*topic*/, const std::string& /*linkName*/, - const std::string& /*mediaType*/, - const std::vector& /*publisherLabels*/, - Services::PubSub::DataMessageHandler /*callback*/, - Services::PubSub::IDataSubscriber* /*parent*/) - -> Services::PubSub::DataSubscriberInternal* override + auto CreateDataSubscriberInternal( + const std::string& /*topic*/, const std::string& /*linkName*/, const std::string& /*mediaType*/, + const std::vector& /*publisherLabels*/, + Services::PubSub::DataMessageHandler /*callback*/, + Services::PubSub::IDataSubscriber* /*parent*/) -> Services::PubSub::DataSubscriberInternal* override { return nullptr; } auto CreateRpcClient(const std::string& /*controllerName*/, const SilKit::Services::Rpc::RpcSpec& /*dataSpec*/, - SilKit::Services::Rpc::RpcCallResultHandler /*handler*/) -> SilKit::Services::Rpc::IRpcClient* override + SilKit::Services::Rpc::RpcCallResultHandler /*handler*/) + -> SilKit::Services::Rpc::IRpcClient* override { return nullptr; } auto CreateRpcServer(const std::string& /*controllerName*/, const SilKit::Services::Rpc::RpcSpec& /*dataSpec*/, - SilKit::Services::Rpc::RpcCallHandler /*handler*/) -> SilKit::Services::Rpc::IRpcServer* override + SilKit::Services::Rpc::RpcCallHandler /*handler*/) + -> SilKit::Services::Rpc::IRpcServer* override { return nullptr; } - auto CreateRpcServerInternal(const std::string& /*functionName*/, const std::string& /*linkName*/, - const std::string& /*mediaType*/, - const std::vector& /*labels*/, - Services::Rpc::RpcCallHandler /*handler*/, Services::Rpc::IRpcServer* /*parent*/) - -> SilKit::Services::Rpc::RpcServerInternal* override + auto CreateRpcServerInternal( + const std::string& /*functionName*/, const std::string& /*linkName*/, const std::string& /*mediaType*/, + const std::vector& /*labels*/, Services::Rpc::RpcCallHandler /*handler*/, + Services::Rpc::IRpcServer* /*parent*/) -> SilKit::Services::Rpc::RpcServerInternal* override { return nullptr; } - auto GetLifecycleService() -> Services::Orchestration::ILifecycleService* override + auto GetLifecycleService() -> Services::Orchestration::ILifecycleService* override { return &mockLifecycleService; } @@ -239,14 +258,37 @@ class DummyParticipant : public IParticipantInternal return &mockLifecycleService; } - MOCK_METHOD(Services::Orchestration::TimeSyncService*, CreateTimeSyncService, (Services::Orchestration::LifecycleService*), (override)); - auto GetSystemMonitor() -> Services::Orchestration::ISystemMonitor* override { return &mockSystemMonitor; } - auto CreateSystemMonitor() -> Services::Orchestration::ISystemMonitor* override { return &mockSystemMonitor; } - auto GetSystemController() -> Experimental::Services::Orchestration::ISystemController* override { return &mockSystemController; } + auto CreateNetworkSimulator() -> Experimental::NetworkSimulation::INetworkSimulator* override + { + return &mockNetworkSimulator; + } - auto GetLogger() -> Services::Logging::ILogger* override { return &logger; } + MOCK_METHOD(Services::Orchestration::TimeSyncService*, CreateTimeSyncService, + (Services::Orchestration::LifecycleService*), (override)); + auto GetSystemMonitor() -> Services::Orchestration::ISystemMonitor* override + { + return &mockSystemMonitor; + } + auto CreateSystemMonitor() -> Services::Orchestration::ISystemMonitor* override + { + return &mockSystemMonitor; + } + auto GetSystemController() -> Experimental::Services::Orchestration::ISystemController* override + { + return &mockSystemController; + } + + auto GetLogger() -> Services::Logging::ILogger* override + { + return &logger; + } - void RegisterSimulator(Core::ISimulator*, const std::vector& /*networks*/) override {} + void RegisterSimulator(Core::ISimulator*, std::string, + Experimental::NetworkSimulation::SimulatedNetworkType) override + { + } + + void AddTraceSinksToSource(ITraceMessageSource*, SilKit::Config::SimulatedNetwork) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Services::Can::WireCanFrameEvent& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Services::Can::CanFrameTransmitEvent& /*msg*/) override {} @@ -254,20 +296,38 @@ class DummyParticipant : public IParticipantInternal void SendMsg(const IServiceEndpoint* /*from*/, const Services::Can::CanConfigureBaudrate& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Services::Can::CanSetControllerMode& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Ethernet::WireEthernetFrameEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Ethernet::EthernetFrameTransmitEvent& /*msg*/) override {} + void SendMsg(const IServiceEndpoint* /*from*/, const Services::Ethernet::WireEthernetFrameEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, + const Services::Ethernet::EthernetFrameTransmitEvent& /*msg*/) override + { + } void SendMsg(const IServiceEndpoint* /*from*/, const Services::Ethernet::EthernetStatus& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Services::Ethernet::EthernetSetMode& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::WireFlexrayFrameEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::WireFlexrayFrameTransmitEvent& /*msg*/) override {} + void SendMsg(const IServiceEndpoint* /*from*/, + const Services::Flexray::WireFlexrayFrameTransmitEvent& /*msg*/) override + { + } void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::FlexraySymbolEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::FlexraySymbolTransmitEvent& /*msg*/) override {} + void SendMsg(const IServiceEndpoint* /*from*/, + const Services::Flexray::FlexraySymbolTransmitEvent& /*msg*/) override + { + } void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::FlexrayCycleStartEvent& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::FlexrayHostCommand& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::FlexrayControllerConfig& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::FlexrayTxBufferConfigUpdate& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::WireFlexrayTxBufferUpdate& /*msg*/) override {} + void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::FlexrayControllerConfig& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, + const Services::Flexray::FlexrayTxBufferConfigUpdate& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::WireFlexrayTxBufferUpdate& /*msg*/) override + { + } void SendMsg(const IServiceEndpoint* /*from*/, const Services::Flexray::FlexrayPocStatusEvent& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Services::Lin::LinSendFrameRequest& /*msg*/) override {} @@ -286,12 +346,17 @@ class DummyParticipant : public IParticipantInternal void SendMsg(const IServiceEndpoint* /*from*/, Services::Rpc::FunctionCallResponse&& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Services::Orchestration::NextSimTask& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Orchestration::ParticipantStatus& /*msg*/) override{} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Orchestration::SystemCommand& /*msg*/) override{} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Orchestration::WorkflowConfiguration& /*msg*/) override{} + void SendMsg(const IServiceEndpoint* /*from*/, const Services::Orchestration::ParticipantStatus& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const Services::Orchestration::SystemCommand& /*msg*/) override {} + void SendMsg(const IServiceEndpoint* /*from*/, + const Services::Orchestration::WorkflowConfiguration& /*msg*/) override + { + } - void SendMsg(const IServiceEndpoint* /*from*/, Services::Logging::LogMsg&& /*msg*/) override{} - void SendMsg(const IServiceEndpoint* /*from*/, const Services::Logging::LogMsg& /*msg*/) override{} + void SendMsg(const IServiceEndpoint* /*from*/, Services::Logging::LogMsg&& /*msg*/) override {} + void SendMsg(const IServiceEndpoint* /*from*/, const Services::Logging::LogMsg& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Discovery::ParticipantDiscoveryEvent& /*msg*/) override {} void SendMsg(const IServiceEndpoint* /*from*/, const Discovery::ServiceDiscoveryEvent& /*msg*/) override {} @@ -301,56 +366,179 @@ class DummyParticipant : public IParticipantInternal // targeted messaging - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Can::WireCanFrameEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Can::CanFrameTransmitEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Can::CanControllerStatus& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Can::CanConfigureBaudrate& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Can::CanSetControllerMode& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Ethernet::WireEthernetFrameEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Ethernet::EthernetFrameTransmitEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Ethernet::EthernetStatus& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Ethernet::EthernetSetMode& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::WireFlexrayFrameEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::WireFlexrayFrameTransmitEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::FlexraySymbolEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::FlexraySymbolTransmitEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::FlexrayCycleStartEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::FlexrayHostCommand& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::FlexrayControllerConfig& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::FlexrayTxBufferConfigUpdate& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::WireFlexrayTxBufferUpdate& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Flexray::FlexrayPocStatusEvent& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Lin::LinSendFrameRequest& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Lin::LinSendFrameHeaderRequest& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Lin::LinTransmission& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Lin::LinFrameResponseUpdate& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Lin::WireLinControllerConfig& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Lin::LinControllerStatusUpdate& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Lin::LinWakeupPulse& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::PubSub::WireDataMessageEvent& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Rpc::FunctionCall& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, Services::Rpc::FunctionCall&& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Rpc::FunctionCallResponse& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, Services::Rpc::FunctionCallResponse&& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Orchestration::NextSimTask& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Orchestration::ParticipantStatus& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Orchestration::SystemCommand& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Orchestration::WorkflowConfiguration& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, Services::Logging::LogMsg&& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Services::Logging::LogMsg& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Discovery::ParticipantDiscoveryEvent& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const Discovery::ServiceDiscoveryEvent& /*msg*/) override {} - - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const RequestReply::RequestReplyCall& /*msg*/) override {} - void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, const RequestReply::RequestReplyCallReturn& /*msg*/) override {} + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Can::WireCanFrameEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Can::CanFrameTransmitEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Can::CanControllerStatus& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Can::CanConfigureBaudrate& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Can::CanSetControllerMode& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Ethernet::WireEthernetFrameEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Ethernet::EthernetFrameTransmitEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Ethernet::EthernetStatus& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Ethernet::EthernetSetMode& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::WireFlexrayFrameEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::WireFlexrayFrameTransmitEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::FlexraySymbolEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::FlexraySymbolTransmitEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::FlexrayCycleStartEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::FlexrayHostCommand& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::FlexrayControllerConfig& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::FlexrayTxBufferConfigUpdate& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::WireFlexrayTxBufferUpdate& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Flexray::FlexrayPocStatusEvent& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Lin::LinSendFrameRequest& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Lin::LinSendFrameHeaderRequest& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Lin::LinTransmission& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Lin::LinFrameResponseUpdate& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Lin::WireLinControllerConfig& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Lin::LinControllerStatusUpdate& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Lin::LinWakeupPulse& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::PubSub::WireDataMessageEvent& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Rpc::FunctionCall& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + Services::Rpc::FunctionCall&& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Rpc::FunctionCallResponse& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + Services::Rpc::FunctionCallResponse&& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Orchestration::NextSimTask& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Orchestration::ParticipantStatus& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Orchestration::SystemCommand& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Orchestration::WorkflowConfiguration& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + Services::Logging::LogMsg&& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Services::Logging::LogMsg& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Discovery::ParticipantDiscoveryEvent& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const Discovery::ServiceDiscoveryEvent& /*msg*/) override + { + } + + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const RequestReply::RequestReplyCall& /*msg*/) override + { + } + void SendMsg(const IServiceEndpoint* /*from*/, const std::string& /*targetParticipantName*/, + const RequestReply::RequestReplyCallReturn& /*msg*/) override + { + } void OnAllMessagesDelivered(std::function /*callback*/) override {} @@ -360,21 +548,55 @@ class DummyParticipant : public IParticipantInternal callback(); } - auto GetParticipantName() const -> const std::string& override { return _name; } - auto GetRegistryUri() const -> const std::string& override { return _registryUri; } + auto GetParticipantName() const -> const std::string& override + { + return _name; + } + auto GetRegistryUri() const -> const std::string& override + { + return _registryUri; + } - virtual auto GetTimeProvider() -> Services::Orchestration::ITimeProvider* { return &mockTimeProvider; } + virtual auto GetTimeProvider() -> Services::Orchestration::ITimeProvider* + { + return &mockTimeProvider; + } void JoinSilKitSimulation() override {} - auto GetServiceDiscovery() -> Discovery::IServiceDiscovery* override { return &mockServiceDiscovery; } - auto GetRequestReplyService() -> RequestReply::IRequestReplyService* override { return &mockRequestReplyService; } - auto GetParticipantRepliesProcedure() -> RequestReply::IParticipantReplies* override { return &mockParticipantReplies; } + auto GetServiceDiscovery() -> Discovery::IServiceDiscovery* override + { + return &mockServiceDiscovery; + } + auto GetRequestReplyService() -> RequestReply::IRequestReplyService* override + { + return &mockRequestReplyService; + } + auto GetParticipantRepliesProcedure() -> RequestReply::IParticipantReplies* override + { + return &mockParticipantReplies; + } + + void AddAsyncSubscriptionsCompletionHandler(std::function handler) override + { + handler(); + }; + + void SetIsSystemControllerCreated(bool /*isCreated*/) override {}; + bool GetIsSystemControllerCreated() override + { + return false; + }; + + void SetIsNetworkSimulatorCreated(bool /*isCreated*/) override {}; + bool GetIsNetworkSimulatorCreated() override + { + return false; + }; - void SetAsyncSubscriptionsCompletionHandler(std::function handler) override { handler(); }; - - void SetIsSystemControllerCreated(bool /*isCreated*/) override{}; - bool GetIsSystemControllerCreated() override { return false; }; - size_t GetNumberOfConnectedParticipants() override { return 0; }; + size_t GetNumberOfConnectedParticipants() override + { + return 0; + }; size_t GetNumberOfRemoteReceivers(const IServiceEndpoint* /*service*/, const std::string& /*msgTypeName*/) override { return 0; @@ -387,13 +609,23 @@ class DummyParticipant : public IParticipantInternal } void NotifyShutdown() override {}; - void RegisterReplayController(ISimulator*, const SilKit::Core::ServiceDescriptor&, const SilKit::Config::SimulatedNetwork& ) override { } + void RegisterReplayController(SilKit::Tracing::IReplayDataController*, const std::string&, + const SilKit::Config::SimulatedNetwork&) override + { + } - bool ParticipantHasCapability(const std::string& /*participantName*/, const std::string& /*capability*/) const override + bool ParticipantHasCapability(const std::string& /*participantName*/, + const std::string& /*capability*/) const override { return true; } + std::string GetServiceDescriptorString( + SilKit::Experimental::NetworkSimulation::ControllerDescriptor /*controllerDescriptor*/) override + { + return ""; + } + const std::string _name = "MockParticipant"; const std::string _registryUri = "silkit://mock.participant.silkit:0"; testing::NiceMock logger; @@ -405,6 +637,7 @@ class DummyParticipant : public IParticipantInternal testing::NiceMock mockServiceDiscovery; MockRequestReplyService mockRequestReplyService; MockParticipantReplies mockParticipantReplies; + DummyNetworkSimulator mockNetworkSimulator; }; // ================================================================================ diff --git a/SilKit/source/core/mock/participant/MockTimeProvider.hpp b/SilKit/source/core/mock/participant/MockTimeProvider.hpp old mode 100755 new mode 100644 index 4dc0a8412..3586c6dbe --- a/SilKit/source/core/mock/participant/MockTimeProvider.hpp +++ b/SilKit/source/core/mock/participant/MockTimeProvider.hpp @@ -40,15 +40,15 @@ class MockTimeProvider : public Services::Orchestration::ITimeProvider { ON_CALL(*this, TimeProviderName()).WillByDefault(testing::ReturnRef(_name)); ON_CALL(*this, Now()).WillByDefault(testing::Return(now)); - } + } MOCK_METHOD(std::chrono::nanoseconds, Now, (), (override, const)); MOCK_METHOD(const std::string&, TimeProviderName, (), (override, const)); MOCK_METHOD(void, SetTime, (std::chrono::nanoseconds /*now*/, std::chrono::nanoseconds /*duration*/), (override)); MOCK_METHOD(void, ConfigureTimeProvider, (Services::Orchestration::TimeProviderKind timeProviderKind), (override)); - MOCK_METHOD(void, SetSynchronizeVirtualTime,(bool isSynchronizingVirtualTime), (override)); - MOCK_METHOD(bool, IsSynchronizingVirtualTime,(),(const, override)); + MOCK_METHOD(void, SetSynchronizeVirtualTime, (bool isSynchronizingVirtualTime), (override)); + MOCK_METHOD(bool, IsSynchronizingVirtualTime, (), (const, override)); Services::HandlerId AddNextSimStepHandler(NextSimStepHandler handler) override { diff --git a/SilKit/source/core/participant/CreateParticipantInternal.cpp b/SilKit/source/core/participant/CreateParticipantInternal.cpp index 7f3ac76bc..46ce309eb 100644 --- a/SilKit/source/core/participant/CreateParticipantInternal.cpp +++ b/SilKit/source/core/participant/CreateParticipantInternal.cpp @@ -27,8 +27,8 @@ namespace SilKit { namespace Core { auto CreateParticipantInternal(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri) - -> std::unique_ptr + const std::string& participantName, + const std::string& registryUri) -> std::unique_ptr { return CreateParticipantT(std::move(participantConfig), participantName, registryUri); } diff --git a/SilKit/source/core/participant/CreateParticipantInternal.hpp b/SilKit/source/core/participant/CreateParticipantInternal.hpp index b8841d29d..170855db4 100644 --- a/SilKit/source/core/participant/CreateParticipantInternal.hpp +++ b/SilKit/source/core/participant/CreateParticipantInternal.hpp @@ -28,8 +28,8 @@ namespace SilKit { namespace Core { auto CreateParticipantInternal(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri) - -> std::unique_ptr; + const std::string& participantName, + const std::string& registryUri) -> std::unique_ptr; } // namespace Core } // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/core/participant/CreateParticipantT.hpp b/SilKit/source/core/participant/CreateParticipantT.hpp index 81bc80945..ede0683ef 100644 --- a/SilKit/source/core/participant/CreateParticipantT.hpp +++ b/SilKit/source/core/participant/CreateParticipantT.hpp @@ -29,8 +29,8 @@ namespace Core { template auto CreateParticipantT(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri, Args&&... args) - -> std::unique_ptr>; + const std::string& participantName, const std::string& registryUri, + Args&&... args) -> std::unique_ptr>; // ================================================================================ // Inline Implementations @@ -38,8 +38,8 @@ auto CreateParticipantT(std::shared_ptr auto CreateParticipantT(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri, Args&&... args) - -> std::unique_ptr> + const std::string& participantName, const std::string& registryUri, + Args&&... args) -> std::unique_ptr> { auto&& result = ValidateAndSanitizeConfig(std::move(participantConfig), participantName, registryUri); auto&& participant = std::make_unique>(std::move(result.participantConfiguration), diff --git a/SilKit/source/core/participant/Participant.hpp b/SilKit/source/core/participant/Participant.hpp index c2fa1be4f..7b9602780 100644 --- a/SilKit/source/core/participant/Participant.hpp +++ b/SilKit/source/core/participant/Participant.hpp @@ -83,6 +83,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // utilities for CreateController #include "traits/SilKitServiceConfigTraits.hpp" +#include "NetworkSimulatorInternal.hpp" + using namespace std::chrono_literals; namespace SilKit { @@ -114,40 +116,39 @@ class Participant : public IParticipantInternal // Public interface methods // // IParticipant - auto CreateCanController(const std::string& canonicalName, const std::string& networkName) - -> Services::Can::ICanController* override; - auto CreateEthernetController(const std::string& canonicalName, const std::string& networkName) - -> Services::Ethernet::IEthernetController* override; - auto CreateFlexrayController(const std::string& canonicalName, const std::string& networkName) - -> Services::Flexray::IFlexrayController* override; - auto CreateLinController(const std::string& canonicalName, const std::string& networkName) - -> Services::Lin::ILinController* override; - - auto CreateDataPublisher(const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, size_t history = 0) - -> Services::PubSub::IDataPublisher* override; + auto CreateCanController(const std::string& canonicalName, + const std::string& networkName) -> Services::Can::ICanController* override; + auto CreateEthernetController(const std::string& canonicalName, + const std::string& networkName) -> Services::Ethernet::IEthernetController* override; + auto CreateFlexrayController(const std::string& canonicalName, + const std::string& networkName) -> Services::Flexray::IFlexrayController* override; + auto CreateLinController(const std::string& canonicalName, + const std::string& networkName) -> Services::Lin::ILinController* override; + + auto CreateDataPublisher(const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, + size_t history = 0) -> Services::PubSub::IDataPublisher* override; auto CreateDataSubscriber(const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, Services::PubSub::DataMessageHandler defaultDataHandler) -> Services::PubSub::IDataSubscriber* override; - auto CreateDataSubscriberInternal(const std::string& canonicalName, const std::string& linkName, - const std::string& mediaType, - const std::vector& publisherLabels, - Services::PubSub::DataMessageHandler callback, Services::PubSub::IDataSubscriber* parent) - -> Services::PubSub::DataSubscriberInternal* override; + auto CreateDataSubscriberInternal( + const std::string& canonicalName, const std::string& linkName, const std::string& mediaType, + const std::vector& publisherLabels, + Services::PubSub::DataMessageHandler callback, + Services::PubSub::IDataSubscriber* parent) -> Services::PubSub::DataSubscriberInternal* override; - auto CreateRpcClient(const std::string& canonicalName, const SilKit::Services::Rpc::RpcSpec& dataSpec, Services::Rpc::RpcCallResultHandler handler) - -> Services::Rpc::IRpcClient* override; + auto CreateRpcClient(const std::string& canonicalName, const SilKit::Services::Rpc::RpcSpec& dataSpec, + Services::Rpc::RpcCallResultHandler handler) -> Services::Rpc::IRpcClient* override; auto CreateRpcServer(const std::string& canonicalName, const SilKit::Services::Rpc::RpcSpec& dataSpec, - Services::Rpc::RpcCallHandler handler) - -> Services::Rpc::IRpcServer* override; + Services::Rpc::RpcCallHandler handler) -> Services::Rpc::IRpcServer* override; auto CreateRpcServerInternal(const std::string& functionName, const std::string& linkName, const std::string& mediaType, const std::vector& clientLabels, - Services::Rpc::RpcCallHandler handler, Services::Rpc::IRpcServer* parent) - -> Services::Rpc::RpcServerInternal* override; + Services::Rpc::RpcCallHandler handler, + Services::Rpc::IRpcServer* parent) -> Services::Rpc::RpcServerInternal* override; auto CreateSystemMonitor() -> Services::Orchestration::ISystemMonitor* override; auto GetSystemMonitor() -> Services::Orchestration::ISystemMonitor* override; @@ -162,8 +163,17 @@ class Participant : public IParticipantInternal auto GetLifecycleService() -> Services::Orchestration::ILifecycleService* override; auto CreateTimeSyncService(Services::Orchestration::LifecycleService* lifecycleService) -> Services::Orchestration::TimeSyncService* override; - auto GetParticipantName() const -> const std::string& override { return _participantConfig.participantName; } - auto GetRegistryUri() const -> const std::string& override { return _participantConfig.middleware.registryUri; } + + auto CreateNetworkSimulator() -> Experimental::NetworkSimulation::INetworkSimulator* override; + + auto GetParticipantName() const -> const std::string& override + { + return _participantConfig.participantName; + } + auto GetRegistryUri() const -> const std::string& override + { + return _participantConfig.middleware.registryUri; + } void SendMsg(const IServiceEndpoint* from, const Services::Can::WireCanFrameEvent& msg) override; void SendMsg(const IServiceEndpoint* from, const Services::Can::CanFrameTransmitEvent& msg) override; @@ -216,66 +226,110 @@ class Participant : public IParticipantInternal void SendMsg(const IServiceEndpoint*, const RequestReply::RequestReplyCallReturn& msg) override; // targeted messaging - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::WireCanFrameEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::CanFrameTransmitEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::CanControllerStatus& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::CanConfigureBaudrate& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Can::CanSetControllerMode& msg) override; - - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Ethernet::WireEthernetFrameEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Ethernet::EthernetFrameTransmitEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Ethernet::EthernetStatus& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Ethernet::EthernetSetMode& msg) override; - - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayFrameEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexraySymbolEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexraySymbolTransmitEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayCycleStartEvent& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayHostCommand& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayControllerConfig& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayTxBufferUpdate& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayPocStatusEvent& msg) override; - - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinSendFrameRequest& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinSendFrameHeaderRequest& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinTransmission& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinWakeupPulse& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::WireLinControllerConfig& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinControllerStatusUpdate& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinFrameResponseUpdate& msg) override; - - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const Services::Orchestration::NextSimTask& msg) override; - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const Services::Orchestration::ParticipantStatus& msg) override; - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const Services::Orchestration::SystemCommand& msg) override; - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const Services::Orchestration::WorkflowConfiguration& msg) override; - - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const Services::Logging::LogMsg& msg) override; - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, Services::Logging::LogMsg&& msg) override; - - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::PubSub::WireDataMessageEvent& msg) override; - - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Rpc::FunctionCall& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, Services::Rpc::FunctionCall&& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Rpc::FunctionCallResponse& msg) override; - void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, Services::Rpc::FunctionCallResponse&& msg) override; - - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const Discovery::ParticipantDiscoveryEvent& msg) override; - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const Discovery::ServiceDiscoveryEvent& msg) override; - - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const RequestReply::RequestReplyCall& msg) override; - void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, const RequestReply::RequestReplyCallReturn& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::WireCanFrameEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::CanFrameTransmitEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::CanControllerStatus& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::CanConfigureBaudrate& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Can::CanSetControllerMode& msg) override; + + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Ethernet::WireEthernetFrameEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Ethernet::EthernetFrameTransmitEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Ethernet::EthernetStatus& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Ethernet::EthernetSetMode& msg) override; + + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayFrameEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexraySymbolEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexraySymbolTransmitEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayCycleStartEvent& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayHostCommand& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayControllerConfig& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayTxBufferUpdate& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayPocStatusEvent& msg) override; + + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinSendFrameRequest& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinSendFrameHeaderRequest& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinTransmission& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinWakeupPulse& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::WireLinControllerConfig& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinControllerStatusUpdate& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinFrameResponseUpdate& msg) override; + + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const Services::Orchestration::NextSimTask& msg) override; + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const Services::Orchestration::ParticipantStatus& msg) override; + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const Services::Orchestration::SystemCommand& msg) override; + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const Services::Orchestration::WorkflowConfiguration& msg) override; + + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const Services::Logging::LogMsg& msg) override; + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + Services::Logging::LogMsg&& msg) override; + + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::PubSub::WireDataMessageEvent& msg) override; + + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Rpc::FunctionCall& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + Services::Rpc::FunctionCall&& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Rpc::FunctionCallResponse& msg) override; + void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + Services::Rpc::FunctionCallResponse&& msg) override; + + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const Discovery::ParticipantDiscoveryEvent& msg) override; + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const Discovery::ServiceDiscoveryEvent& msg) override; + + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const RequestReply::RequestReplyCall& msg) override; + void SendMsg(const IServiceEndpoint*, const std::string& targetParticipantName, + const RequestReply::RequestReplyCallReturn& msg) override; void OnAllMessagesDelivered(std::function callback) override; void FlushSendBuffers() override; void ExecuteDeferred(std::function callback) override; - void SetAsyncSubscriptionsCompletionHandler(std::function handler) override; + void AddAsyncSubscriptionsCompletionHandler(std::function handler) override; void SetIsSystemControllerCreated(bool isCreated) override; bool GetIsSystemControllerCreated() override; + void SetIsNetworkSimulatorCreated(bool isCreated) override; + bool GetIsNetworkSimulatorCreated() override; + size_t GetNumberOfConnectedParticipants() override; size_t GetNumberOfRemoteReceivers(const IServiceEndpoint* service, const std::string& msgTypeName) override; @@ -284,10 +338,15 @@ class Participant : public IParticipantInternal void NotifyShutdown() override; - void RegisterReplayController(ISimulator* simulator, const SilKit::Core::ServiceDescriptor& service, const SilKit::Config::SimulatedNetwork& simulatedNetwork) override; + void RegisterReplayController(SilKit::Tracing::IReplayDataController* replayController, + const std::string& controllerName, + const SilKit::Config::SimulatedNetwork& simulatedNetwork) override; bool ParticipantHasCapability(const std::string& /*participantName*/, const std::string& /*capability*/) const override; + std::string GetServiceDescriptorString( + SilKit::Experimental::NetworkSimulation::ControllerDescriptor controllerDescriptor) override; + public: // ---------------------------------------- // Public methods @@ -300,12 +359,15 @@ class Participant : public IParticipantInternal void JoinSilKitSimulation() override; // For Testing Purposes: - inline auto GetSilKitConnection() -> SilKitConnectionT& { return _connection; } + inline auto GetSilKitConnection() -> SilKitConnectionT& + { + return _connection; + } private: // ---------------------------------------- // private datatypes - template + template using ControllerMap = std::unordered_map>; private: @@ -314,8 +376,8 @@ class Participant : public IParticipantInternal //!< Search for the controller configuration by name and set configured values. Initialize with controller name if no config is found. template - auto GetConfigByControllerName(const std::vector& controllers, const std::string& canonicalName) - -> ConfigT; + auto GetConfigByControllerName(const std::vector& controllers, + const std::string& canonicalName) -> ConfigT; //!< Update the controller configuration for a given optional field. Prefers configured values over programmatically passed values. template @@ -332,31 +394,34 @@ class Participant : public IParticipantInternal void SetTimeProvider(Services::Orchestration::ITimeProvider*); - template + template void SendMsgImpl(const IServiceEndpoint* from, SilKitMessageT&& msg); - template + template void SendMsgImpl(const IServiceEndpoint* from, const std::string& targetParticipantName, SilKitMessageT&& msg); - template + template auto GetController(const std::string& serviceName) -> ControllerT*; //!< Internal controller creation, explicit network argument for ConfigT without network template - auto CreateController(const SilKitServiceTraitConfigType_t& config, - const std::string& network, const Core::SupplementalData& supplementalData, bool publishService, Arg&&... arg) - -> ControllerT*; + auto CreateController(const SilKitServiceTraitConfigType_t& config, const std::string& network, + const Core::SupplementalData& supplementalData, bool publishService, + Arg&&... arg) -> ControllerT*; //!< Internal controller creation, expects config.network template auto CreateController(const SilKitServiceTraitConfigType_t& config, - const Core::SupplementalData& supplementalData, bool publishService, Arg&&... arg) - -> ControllerT*; + const Core::SupplementalData& supplementalData, bool publishService, + Arg&&... arg) -> ControllerT*; + + void RegisterSimulator(ISimulator* busSim, std::string networkName, + Experimental::NetworkSimulation::SimulatedNetworkType networkType) override; - void RegisterSimulator(ISimulator* busSim, const std::vector& networks) override; + void AddTraceSinksToSource(ITraceMessageSource* controller, SilKit::Config::SimulatedNetwork config) override; - template - void AddTraceSinksToSource(ITraceMessageSource* controller, ConfigT config); + template + void AddTraceSinksToSourceInternal(ITraceMessageSource* controller, ConfigT config); private: // ---------------------------------------- @@ -372,44 +437,36 @@ class Participant : public IParticipantInternal std::unique_ptr _participantReplies; std::tuple< - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap, + ControllerMap, ControllerMap, + ControllerMap, ControllerMap, + ControllerMap, ControllerMap, + ControllerMap, ControllerMap, + ControllerMap, ControllerMap, + ControllerMap, ControllerMap, ControllerMap, ControllerMap, ControllerMap, - ControllerMap, - ControllerMap, - ControllerMap - > _controllers; + ControllerMap, ControllerMap, + ControllerMap> + _controllers; - std::atomic _localEndpointId{ 0 }; + std::atomic _localEndpointId{0}; - std::tuple< - Services::Can::IMsgForCanSimulator*, - Services::Ethernet::IMsgForEthSimulator*, - Services::Flexray::IMsgForFlexrayBusSimulator*, - Services::Lin::IMsgForLinSimulator* - > _simulators {nullptr, nullptr, nullptr, nullptr}; + std::unique_ptr _networkSimulatorInternal; + + std::tuple + _simulators{nullptr, nullptr, nullptr, nullptr}; SilKitConnectionT _connection; - // control variables to prevent multiple create accesses by public API + // control variables to prevent multiple create accesses by public API std::atomic _isSystemMonitorCreated{false}; std::atomic _isSystemControllerCreated{false}; std::atomic _isLoggerCreated{false}; std::atomic _isLifecycleServiceCreated{false}; + std::atomic _isNetworkSimulatorCreated{false}; }; } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/participant/Participant_impl.hpp b/SilKit/source/core/participant/Participant_impl.hpp old mode 100755 new mode 100644 index c48fb80e7..20017747e --- a/SilKit/source/core/participant/Participant_impl.hpp +++ b/SilKit/source/core/participant/Participant_impl.hpp @@ -33,6 +33,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "RpcClient.hpp" #include "RpcServer.hpp" #include "RpcServerInternal.hpp" +#include "NetworkSimulatorDatatypesInternal.hpp" +#include "silkit/experimental/netsim/string_utils.hpp" #include "LifecycleService.hpp" #include "SystemController.hpp" @@ -46,6 +48,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "RequestReplyService.hpp" #include "ParticipantConfiguration.hpp" #include "YamlParser.hpp" +#include "NetworkSimulatorInternal.hpp" #include "tuple_tools/bind.hpp" #include "tuple_tools/for_each.hpp" @@ -62,6 +65,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ILogger.hpp" + namespace SilKit { namespace Core { @@ -73,12 +77,16 @@ namespace tt = Util::tuple_tools; // Anonymous namespace for Helper Traits and Functions namespace { -template -struct IsControllerMap : std::false_type {}; -template -struct IsControllerMap>, U> : std::is_base_of {}; +template +struct IsControllerMap : std::false_type +{ +}; +template +struct IsControllerMap>, U> : std::is_base_of +{ +}; -} // namespace anonymous +} // namespace template Participant::Participant(Config::ParticipantConfiguration participantConfig, ProtocolVersion version) @@ -93,7 +101,6 @@ Participant::Participant(Config::ParticipantConfiguration par Logging::Info(_logger.get(), "Creating participant '{}' at '{}', SIL Kit version: {}", GetParticipantName(), _participantConfig.middleware.registryUri, Version::StringImpl()); - } @@ -108,7 +115,7 @@ template void Participant::OnSilKitSimulationJoined() { SetupRemoteLogging(); - + // NB: Create the systemController to abort the simulation already in the startup phase (void)GetSystemController(); @@ -145,7 +152,8 @@ void Participant::SetupRemoteLogging() if (_participantConfig.logging.logFromRemotes) { Core::SupplementalData supplementalData; - supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeLoggerReceiver; + supplementalData[SilKit::Core::Discovery::controllerType] = + SilKit::Core::Discovery::controllerTypeLoggerReceiver; Config::InternalController config; config.name = "LogMsgReceiver"; @@ -154,38 +162,39 @@ void Participant::SetupRemoteLogging() } auto sinkIter = std::find_if(_participantConfig.logging.sinks.begin(), _participantConfig.logging.sinks.end(), - [](const Config::Sink& sink) { return sink.type == Config::Sink::Type::Remote; }); + [](const Config::Sink& sink) { return sink.type == Config::Sink::Type::Remote; }); if (sinkIter != _participantConfig.logging.sinks.end()) { Core::SupplementalData supplementalData; - supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeLoggerSender; + supplementalData[SilKit::Core::Discovery::controllerType] = + SilKit::Core::Discovery::controllerTypeLoggerSender; Config::InternalController config; config.name = "LogMsgSender"; config.network = "default"; - auto&& logMsgSender = CreateController( - config, std::move(supplementalData), true); + auto&& logMsgSender = + CreateController(config, std::move(supplementalData), true); logger->RegisterRemoteLogging([logMsgSender](Services::Logging::LogMsg logMsg) { - logMsgSender->SendLogMsg(std::move(logMsg)); - }); } } else { - Logging::Warn(GetLogger(), "Failed to setup remote logging. Participant {} will not send and receive remote logs.", GetParticipantName()); + Logging::Warn(GetLogger(), + "Failed to setup remote logging. Participant {} will not send and receive remote logs.", + GetParticipantName()); } } -template +template inline void Participant::SetTimeProvider(Orchestration::ITimeProvider* newClock) { // Register the time provider with all already instantiated controllers auto setTimeProvider = [newClock](auto& controllers) { - for (auto& controller: controllers) + for (auto& controller : controllers) { auto* ctl = dynamic_cast(controller.second.get()); if (ctl) @@ -200,12 +209,11 @@ inline void Participant::SetTimeProvider(Orchestration::ITime template template auto Participant::GetConfigByControllerName(const std::vector& controllers, - const std::string& canonicalName) -> ConfigT + const std::string& canonicalName) -> ConfigT { ConfigT controllerConfig; - auto it = std::find_if(controllers.begin(), controllers.end(), [canonicalName](auto&& controllerConfig) { - return controllerConfig.name == canonicalName; - }); + auto it = std::find_if(controllers.begin(), controllers.end(), + [canonicalName](auto&& controllerConfig) { return controllerConfig.name == canonicalName; }); if (it != controllers.end()) { controllerConfig = *it; @@ -221,8 +229,8 @@ auto Participant::GetConfigByControllerName(const std::vector template template void Participant::UpdateOptionalConfigValue(const std::string& controllerName, - SilKit::Util::Optional& configuredValue, - const ValueT& passedValue) + SilKit::Util::Optional& configuredValue, + const ValueT& passedValue) { if (!configuredValue.has_value()) { @@ -237,17 +245,18 @@ void Participant::UpdateOptionalConfigValue(const std::string } template -auto Participant::CreateCanController(const std::string& canonicalName, const std::string& networkName) -> Can::ICanController* +auto Participant::CreateCanController(const std::string& canonicalName, + const std::string& networkName) -> Can::ICanController* { - SilKit::Config::CanController controllerConfig = GetConfigByControllerName(_participantConfig.canControllers, canonicalName); + SilKit::Config::CanController controllerConfig = + GetConfigByControllerName(_participantConfig.canControllers, canonicalName); UpdateOptionalConfigValue(canonicalName, controllerConfig.network, networkName); Core::SupplementalData supplementalData; supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeCan; - auto controller = CreateController( - controllerConfig, std::move(supplementalData), true, controllerConfig, - &_timeProvider); + auto controller = CreateController(controllerConfig, std::move(supplementalData), true, + controllerConfig, &_timeProvider); controller->RegisterServiceDiscovery(); @@ -264,15 +273,15 @@ auto Participant::CreateCanController(const std::string& cano auto* traceSource = dynamic_cast(controller); if (traceSource) { - AddTraceSinksToSource(traceSource, controllerConfig); + AddTraceSinksToSourceInternal(traceSource, controllerConfig); } return controller; } template -auto Participant::CreateEthernetController(const std::string& canonicalName, const std::string& networkName) - -> Ethernet::IEthernetController* +auto Participant::CreateEthernetController( + const std::string& canonicalName, const std::string& networkName) -> Ethernet::IEthernetController* { SilKit::Config::EthernetController controllerConfig = GetConfigByControllerName(_participantConfig.ethernetControllers, canonicalName); @@ -281,9 +290,8 @@ auto Participant::CreateEthernetController(const std::string& Core::SupplementalData supplementalData; supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeEthernet; - auto *controller = CreateController( - controllerConfig, std::move(supplementalData), true, controllerConfig, - &_timeProvider); + auto* controller = CreateController(controllerConfig, std::move(supplementalData), true, + controllerConfig, &_timeProvider); controller->RegisterServiceDiscovery(); @@ -300,25 +308,25 @@ auto Participant::CreateEthernetController(const std::string& auto* traceSource = dynamic_cast(controller); if (traceSource) { - AddTraceSinksToSource(traceSource, controllerConfig); + AddTraceSinksToSourceInternal(traceSource, controllerConfig); } return controller; } template -auto Participant::CreateFlexrayController(const std::string& canonicalName, const std::string& networkName) - -> Services::Flexray::IFlexrayController* +auto Participant::CreateFlexrayController( + const std::string& canonicalName, const std::string& networkName) -> Services::Flexray::IFlexrayController* { - SilKit::Config::FlexrayController controllerConfig = GetConfigByControllerName(_participantConfig.flexrayControllers, canonicalName); + SilKit::Config::FlexrayController controllerConfig = + GetConfigByControllerName(_participantConfig.flexrayControllers, canonicalName); UpdateOptionalConfigValue(canonicalName, controllerConfig.network, networkName); Core::SupplementalData supplementalData; supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeFlexray; - auto controller = CreateController( - controllerConfig, std::move(supplementalData), true, controllerConfig, - &_timeProvider); + auto controller = CreateController(controllerConfig, std::move(supplementalData), true, + controllerConfig, &_timeProvider); controller->RegisterServiceDiscovery(); @@ -329,25 +337,25 @@ auto Participant::CreateFlexrayController(const std::string& auto* traceSource = dynamic_cast(controller); if (traceSource) { - AddTraceSinksToSource(traceSource, controllerConfig); + AddTraceSinksToSourceInternal(traceSource, controllerConfig); } return controller; } template -auto Participant::CreateLinController(const std::string& canonicalName, const std::string& networkName) - -> Lin::ILinController* +auto Participant::CreateLinController(const std::string& canonicalName, + const std::string& networkName) -> Lin::ILinController* { - SilKit::Config::LinController controllerConfig = GetConfigByControllerName(_participantConfig.linControllers, canonicalName); + SilKit::Config::LinController controllerConfig = + GetConfigByControllerName(_participantConfig.linControllers, canonicalName); UpdateOptionalConfigValue(canonicalName, controllerConfig.network, networkName); Core::SupplementalData supplementalData; supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeLin; - auto controller = CreateController( - controllerConfig, std::move(supplementalData), true, controllerConfig, - &_timeProvider); + auto controller = CreateController(controllerConfig, std::move(supplementalData), true, + controllerConfig, &_timeProvider); controller->RegisterServiceDiscovery(); @@ -365,19 +373,18 @@ auto Participant::CreateLinController(const std::string& cano auto* traceSource = dynamic_cast(controller); if (traceSource) { - AddTraceSinksToSource(traceSource, controllerConfig); + AddTraceSinksToSourceInternal(traceSource, controllerConfig); } return controller; } template -auto Participant::CreateDataSubscriberInternal(const std::string& topic, const std::string& linkName, - const std::string& mediaType, - const std::vector& publisherLabels, - Services::PubSub::DataMessageHandler defaultHandler, - Services::PubSub::IDataSubscriber* parent) - -> Services::PubSub::DataSubscriberInternal* +auto Participant::CreateDataSubscriberInternal( + const std::string& topic, const std::string& linkName, const std::string& mediaType, + const std::vector& publisherLabels, + Services::PubSub::DataMessageHandler defaultHandler, + Services::PubSub::IDataSubscriber* parent) -> Services::PubSub::DataSubscriberInternal* { Core::SupplementalData supplementalData; supplementalData[SilKit::Core::Discovery::controllerType] = @@ -395,8 +402,8 @@ auto Participant::CreateDataSubscriberInternal(const std::str std::string network = linkName; auto controller = CreateController( - controllerConfig, network, std::move(supplementalData), true, &_timeProvider, - topic, mediaType, publisherLabels, defaultHandler, parent); + controllerConfig, network, std::move(supplementalData), true, &_timeProvider, topic, mediaType, publisherLabels, + defaultHandler, parent); //Restore original DataSubscriber config for replay auto&& parentConfig = parentDataSubscriber->GetConfig(); @@ -432,8 +439,12 @@ static inline auto FormatLabelsForLogging(const std::vector& labe switch (label.kind) { - case MatchingLabel::Kind::Optional: os << "Optional"; break; - case MatchingLabel::Kind::Mandatory: os << "Mandatory"; break; + case MatchingLabel::Kind::Optional: + os << "Optional"; + break; + case MatchingLabel::Kind::Mandatory: + os << "Mandatory"; + break; default: os << "MatchingLabel::Kind(" << static_cast>(label.kind) << ")"; break; @@ -448,7 +459,7 @@ static inline auto FormatLabelsForLogging(const std::vector& labe template auto Participant::CreateDataPublisher(const std::string& canonicalName, const SilKit::Services::PubSub::PubSubSpec& dataSpec, - size_t history) -> Services::PubSub::IDataPublisher* + size_t history) -> Services::PubSub::IDataPublisher* { if (history > 1) { @@ -458,13 +469,13 @@ auto Participant::CreateDataPublisher(const std::string& cano std::string network = to_string(Util::Uuid::GenerateRandom()); // Merge config and parameters, sort labels - SilKit::Config::DataPublisher controllerConfig = GetConfigByControllerName(_participantConfig.dataPublishers, canonicalName); + SilKit::Config::DataPublisher controllerConfig = + GetConfigByControllerName(_participantConfig.dataPublishers, canonicalName); UpdateOptionalConfigValue(canonicalName, controllerConfig.topic, dataSpec.Topic()); SilKit::Services::PubSub::PubSubSpec configuredDataNodeSpec{controllerConfig.topic.value(), dataSpec.MediaType()}; auto labels = dataSpec.Labels(); - std::sort(labels.begin(), labels.end(), [](const MatchingLabel& v1, const MatchingLabel& v2) { - return v1.key < v2.key; - }); + std::sort(labels.begin(), labels.end(), + [](const MatchingLabel& v1, const MatchingLabel& v2) { return v1.key < v2.key; }); for (auto label : labels) { configuredDataNodeSpec.AddLabel(label); @@ -479,13 +490,7 @@ auto Participant::CreateDataPublisher(const std::string& cano supplementalData[SilKit::Core::Discovery::supplKeyDataPublisherPubLabels] = labelStr; auto controller = CreateController( - controllerConfig, - network, - std::move(supplementalData), - true, - &_timeProvider, - configuredDataNodeSpec, - network, + controllerConfig, network, std::move(supplementalData), true, &_timeProvider, configuredDataNodeSpec, network, controllerConfig); _connection.SetHistoryLengthForLink(history, controller); @@ -503,7 +508,7 @@ auto Participant::CreateDataPublisher(const std::string& cano auto* traceSource = dynamic_cast(controller); if (traceSource) { - AddTraceSinksToSource(traceSource, controllerConfig); + AddTraceSinksToSourceInternal(traceSource, controllerConfig); } if (_replayScheduler) @@ -526,14 +531,14 @@ auto Participant::CreateDataSubscriber( const auto network = "default"; // Merge config and parameters, sort labels - SilKit::Config::DataSubscriber controllerConfig = GetConfigByControllerName(_participantConfig.dataSubscribers, canonicalName); + SilKit::Config::DataSubscriber controllerConfig = + GetConfigByControllerName(_participantConfig.dataSubscribers, canonicalName); UpdateOptionalConfigValue(canonicalName, controllerConfig.topic, dataSpec.Topic()); - + SilKit::Services::PubSub::PubSubSpec configuredDataNodeSpec{controllerConfig.topic.value(), dataSpec.MediaType()}; auto labels = dataSpec.Labels(); - std::sort(labels.begin(), labels.end(), [](const MatchingLabel& v1, const MatchingLabel& v2) { - return v1.key < v2.key; - }); + std::sort(labels.begin(), labels.end(), + [](const MatchingLabel& v1, const MatchingLabel& v2) { return v1.key < v2.key; }); for (auto label : labels) { configuredDataNodeSpec.AddLabel(label); @@ -565,20 +570,20 @@ auto Participant::CreateDataSubscriber( auto* traceSource = dynamic_cast(controller); if (traceSource) { - AddTraceSinksToSource(traceSource, controllerConfig); + AddTraceSinksToSourceInternal(traceSource, controllerConfig); } return controller; } template -auto Participant::CreateRpcServerInternal(const std::string& functionName, const std::string& clientUUID, - const std::string& mediaType, - const std::vector& clientLabels, - Services::Rpc::RpcCallHandler handler, - Services::Rpc::IRpcServer* parent) -> Services::Rpc::RpcServerInternal* +auto Participant::CreateRpcServerInternal( + const std::string& functionName, const std::string& clientUUID, const std::string& mediaType, + const std::vector& clientLabels, Services::Rpc::RpcCallHandler handler, + Services::Rpc::IRpcServer* parent) -> Services::Rpc::RpcServerInternal* { - Logging::Trace(GetLogger(), "Creating internal server for functionName={}, clientUUID={}", functionName, clientUUID); + Logging::Trace(GetLogger(), "Creating internal server for functionName={}, clientUUID={}", functionName, + clientUUID); SilKit::Config::RpcServer controllerConfig; // Use a unique name to avoid collisions of several RpcSevers on same functionName on one participant @@ -587,7 +592,8 @@ auto Participant::CreateRpcServerInternal(const std::string& // RpcServerInternal gets discovered by RpcClient which is then ready to detach calls SilKit::Core::SupplementalData supplementalData; - supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeRpcServerInternal; + supplementalData[SilKit::Core::Discovery::controllerType] = + SilKit::Core::Discovery::controllerTypeRpcServerInternal; supplementalData[SilKit::Core::Discovery::supplKeyRpcServerInternalClientUUID] = clientUUID; auto parentRpcServer = dynamic_cast(parent); if (parentRpcServer) @@ -595,20 +601,21 @@ auto Participant::CreateRpcServerInternal(const std::string& supplementalData[SilKit::Core::Discovery::supplKeyRpcServerInternalParentServiceID] = std::to_string(parentRpcServer->GetServiceDescriptor().GetServiceId()); } - return CreateController( - controllerConfig, network, std::move(supplementalData), true, &_timeProvider, - functionName, mediaType, clientLabels, clientUUID, handler, parent); + return CreateController(controllerConfig, network, std::move(supplementalData), + true, &_timeProvider, functionName, mediaType, + clientLabels, clientUUID, handler, parent); } template -auto Participant::CreateRpcClient(const std::string& canonicalName, - const SilKit::Services::Rpc::RpcSpec& dataSpec, - Services::Rpc::RpcCallResultHandler handler) -> Services::Rpc::IRpcClient* +auto Participant::CreateRpcClient( + const std::string& canonicalName, const SilKit::Services::Rpc::RpcSpec& dataSpec, + Services::Rpc::RpcCallResultHandler handler) -> Services::Rpc::IRpcClient* { // RpcClient communicates on a unique network auto network = to_string(Util::Uuid::GenerateRandom()); - SilKit::Config::RpcClient controllerConfig = GetConfigByControllerName(_participantConfig.rpcClients, canonicalName); + SilKit::Config::RpcClient controllerConfig = + GetConfigByControllerName(_participantConfig.rpcClients, canonicalName); UpdateOptionalConfigValue(canonicalName, controllerConfig.functionName, dataSpec.FunctionName()); // RpcClient gets discovered by RpcServer which creates RpcServerInternal on a matching connection @@ -627,9 +634,9 @@ auto Participant::CreateRpcClient(const std::string& canonica configuredDataSpec.AddLabel(label); } - auto controller = CreateController( - controllerConfig, network, std::move(supplementalData), true, &_timeProvider, - configuredDataSpec, network, handler); + auto controller = + CreateController(controllerConfig, network, std::move(supplementalData), true, + &_timeProvider, configuredDataSpec, network, handler); // RpcClient discovers RpcServerInternal and is ready to dispatch calls controller->RegisterServiceDiscovery(); @@ -648,15 +655,16 @@ auto Participant::CreateRpcClient(const std::string& canonica } template -auto Participant::CreateRpcServer(const std::string& canonicalName, - const SilKit::Services::Rpc::RpcSpec& dataSpec, - Services::Rpc::RpcCallHandler handler) -> Services::Rpc::IRpcServer* +auto Participant::CreateRpcServer( + const std::string& canonicalName, const SilKit::Services::Rpc::RpcSpec& dataSpec, + Services::Rpc::RpcCallHandler handler) -> Services::Rpc::IRpcServer* { // RpcServer has no registered messages (discovers RpcClients and creates RpcServerInternal), // so the network name is irrelevant. auto network = "default"; - SilKit::Config::RpcServer controllerConfig = GetConfigByControllerName(_participantConfig.rpcServers, canonicalName); + SilKit::Config::RpcServer controllerConfig = + GetConfigByControllerName(_participantConfig.rpcServers, canonicalName); UpdateOptionalConfigValue(canonicalName, controllerConfig.functionName, dataSpec.FunctionName()); Core::SupplementalData supplementalData; @@ -668,16 +676,14 @@ auto Participant::CreateRpcServer(const std::string& canonica auto labelStr = SilKit::Config::Serialize>(labels); supplementalData[SilKit::Core::Discovery::supplKeyRpcServerLabels] = labelStr; - SilKit::Services::Rpc::RpcSpec configuredDataSpec{controllerConfig.functionName.value(), - dataSpec.MediaType()}; + SilKit::Services::Rpc::RpcSpec configuredDataSpec{controllerConfig.functionName.value(), dataSpec.MediaType()}; for (auto label : dataSpec.Labels()) { configuredDataSpec.AddLabel(label); } - auto controller = CreateController( - controllerConfig, network, supplementalData, true, &_timeProvider, - configuredDataSpec, handler); + auto controller = CreateController(controllerConfig, network, supplementalData, true, + &_timeProvider, configuredDataSpec, handler); // RpcServer discovers RpcClient and creates RpcServerInternal on a matching connection controller->RegisterServiceDiscovery(); @@ -696,7 +702,8 @@ auto Participant::CreateRpcServer(const std::string& canonica } template -auto Participant::CreateTimeSyncService(Orchestration::LifecycleService* lifecycleService) -> Services::Orchestration::TimeSyncService* +auto Participant::CreateTimeSyncService(Orchestration::LifecycleService* lifecycleService) + -> Services::Orchestration::TimeSyncService* { auto* timeSyncService = GetController(SilKit::Core::Discovery::controllerTypeTimeSyncService); @@ -707,13 +714,15 @@ auto Participant::CreateTimeSyncService(Orchestration::Lifecy } Core::SupplementalData timeSyncSupplementalData; - timeSyncSupplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeTimeSyncService; + timeSyncSupplementalData[SilKit::Core::Discovery::controllerType] = + SilKit::Core::Discovery::controllerTypeTimeSyncService; Config::InternalController config; config.name = Discovery::controllerTypeTimeSyncService; config.network = "default"; timeSyncService = CreateController( - config, std::move(timeSyncSupplementalData), false, &_timeProvider, _participantConfig.healthCheck, lifecycleService); + config, std::move(timeSyncSupplementalData), false, &_timeProvider, _participantConfig.healthCheck, + lifecycleService); return timeSyncService; } @@ -727,17 +736,19 @@ auto Participant::GetLifecycleService() -> Services::Orchestr if (!lifecycleService) { Core::SupplementalData lifecycleSupplementalData; - lifecycleSupplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeLifecycleService; + lifecycleSupplementalData[SilKit::Core::Discovery::controllerType] = + SilKit::Core::Discovery::controllerTypeLifecycleService; Config::InternalController config; config.name = Discovery::controllerTypeLifecycleService; config.network = "default"; - lifecycleService = CreateController( - config, std::move(lifecycleSupplementalData), false); + lifecycleService = + CreateController(config, std::move(lifecycleSupplementalData), false); } return lifecycleService; } + static inline auto FormatLifecycleConfigurationForLogging( const Services::Orchestration::LifecycleConfiguration& lifecycleConfiguration) -> std::string { @@ -748,9 +759,15 @@ static inline auto FormatLifecycleConfigurationForLogging( os << "LifecycleConfiguration{operationMode="; switch (lifecycleConfiguration.operationMode) { - case OperationMode::Invalid: os << "Invalid"; break; - case OperationMode::Coordinated: os << "Coordinated"; break; - case OperationMode::Autonomous: os << "Autonomous"; break; + case OperationMode::Invalid: + os << "Invalid"; + break; + case OperationMode::Coordinated: + os << "Coordinated"; + break; + case OperationMode::Autonomous: + os << "Autonomous"; + break; default: os << "OperationMode(" << static_cast>(lifecycleConfiguration.operationMode) << ")"; @@ -789,17 +806,18 @@ auto Participant::CreateLifecycleService( template auto Participant::GetSystemMonitor() -> Services::Orchestration::ISystemMonitor* { - auto* controller = GetController(SilKit::Core::Discovery::controllerTypeSystemMonitor); + auto* controller = + GetController(SilKit::Core::Discovery::controllerTypeSystemMonitor); if (!controller) { Core::SupplementalData supplementalData; - supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeSystemMonitor; + supplementalData[SilKit::Core::Discovery::controllerType] = + SilKit::Core::Discovery::controllerTypeSystemMonitor; Config::InternalController config; config.name = Discovery::controllerTypeSystemMonitor; config.network = "default"; - controller = CreateController( - config, std::move(supplementalData), true); + controller = CreateController(config, std::move(supplementalData), true); _connection.RegisterMessageReceiver([controller](IVAsioPeer* peer, const ParticipantAnnouncement&) { controller->OnParticipantConnected( @@ -828,22 +846,22 @@ auto Participant::CreateSystemMonitor() -> Services::Orchestr template auto Participant::GetServiceDiscovery() -> Discovery::IServiceDiscovery* { - auto* controller = - GetController(SilKit::Core::Discovery::controllerTypeServiceDiscovery); + auto* controller = GetController( + SilKit::Core::Discovery::controllerTypeServiceDiscovery); if (!controller) { Core::SupplementalData supplementalData; - supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeServiceDiscovery; + supplementalData[SilKit::Core::Discovery::controllerType] = + SilKit::Core::Discovery::controllerTypeServiceDiscovery; Config::InternalController config; config.name = Discovery::controllerTypeServiceDiscovery; config.network = "default"; - controller = CreateController( - config, std::move(supplementalData), true, GetParticipantName()); + controller = CreateController(config, std::move(supplementalData), + true, GetParticipantName()); - _connection.RegisterPeerShutdownCallback([controller](IVAsioPeer* peer) { - controller->OnParticpantRemoval(peer->GetInfo().participantName); - }); + _connection.RegisterPeerShutdownCallback( + [controller](IVAsioPeer* peer) { controller->OnParticpantRemoval(peer->GetInfo().participantName); }); } return controller; } @@ -862,17 +880,17 @@ auto Participant::GetRequestReplyService() -> RequestReply::I _participantReplies = std::make_unique(this, controller); - RequestReply::ProcedureMap procedures{{RequestReply::FunctionType::ParticipantReplies, _participantReplies.get()}}; + RequestReply::ProcedureMap procedures{ + {RequestReply::FunctionType::ParticipantReplies, _participantReplies.get()}}; Config::InternalController config; config.name = "RequestReplyService"; config.network = "default"; - controller = CreateController( - config, std::move(supplementalData), true, GetParticipantName(), procedures); + controller = CreateController(config, std::move(supplementalData), true, + GetParticipantName(), procedures); - _connection.RegisterPeerShutdownCallback([controller](IVAsioPeer* peer) { - controller->OnParticpantRemoval(peer->GetInfo().participantName); - }); + _connection.RegisterPeerShutdownCallback( + [controller](IVAsioPeer* peer) { controller->OnParticpantRemoval(peer->GetInfo().participantName); }); } return controller; } @@ -895,25 +913,52 @@ void Participant::SetIsSystemControllerCreated(bool isCreated _isSystemControllerCreated = isCreated; } +template +bool Participant::GetIsNetworkSimulatorCreated() +{ + return _isNetworkSimulatorCreated; +} + +template +void Participant::SetIsNetworkSimulatorCreated(bool isCreated) +{ + _isNetworkSimulatorCreated = isCreated; +} + + template auto Participant::GetSystemController() -> Experimental::Services::Orchestration::ISystemController* { - auto* controller = GetController(SilKit::Core::Discovery::controllerTypeSystemController); + auto* controller = + GetController(SilKit::Core::Discovery::controllerTypeSystemController); if (!controller) { Core::SupplementalData supplementalData; - supplementalData[SilKit::Core::Discovery::controllerType] = SilKit::Core::Discovery::controllerTypeSystemController; + supplementalData[SilKit::Core::Discovery::controllerType] = + SilKit::Core::Discovery::controllerTypeSystemController; Config::InternalController config; config.name = SilKit::Core::Discovery::controllerTypeSystemController; config.network = "default"; - return CreateController( - config, std::move(supplementalData), true); + return CreateController(config, std::move(supplementalData), true); } return controller; } + +template +auto Participant::CreateNetworkSimulator() -> Experimental::NetworkSimulation::INetworkSimulator* +{ + if (_networkSimulatorInternal != nullptr) + { + throw SilKitError("You may not create the network simulator more than once."); + } + + _networkSimulatorInternal = std::make_unique(this); + return _networkSimulatorInternal.get(); +} + template auto Participant::GetLogger() -> Services::Logging::ILogger* { @@ -957,7 +1002,8 @@ void Participant::SendMsg(const IServiceEndpoint* from, const } template -void Participant::SendMsg(const IServiceEndpoint* from, const Ethernet::EthernetFrameTransmitEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Ethernet::EthernetFrameTransmitEvent& msg) { SendMsgImpl(from, msg); } @@ -975,73 +1021,85 @@ void Participant::SendMsg(const IServiceEndpoint* from, const } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::WireFlexrayFrameEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::WireFlexrayFrameEvent& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::FlexraySymbolEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::FlexraySymbolEvent& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::FlexraySymbolTransmitEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::FlexraySymbolTransmitEvent& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::FlexrayCycleStartEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::FlexrayCycleStartEvent& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::FlexrayHostCommand& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::FlexrayHostCommand& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::FlexrayControllerConfig& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::FlexrayControllerConfig& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::WireFlexrayTxBufferUpdate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::WireFlexrayTxBufferUpdate& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Flexray::FlexrayPocStatusEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Flexray::FlexrayPocStatusEvent& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Lin::LinSendFrameRequest& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Lin::LinSendFrameRequest& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Lin::LinSendFrameHeaderRequest& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Lin::LinSendFrameHeaderRequest& msg) { SendMsgImpl(from, msg); } @@ -1059,25 +1117,29 @@ void Participant::SendMsg(const IServiceEndpoint* from, const } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Lin::WireLinControllerConfig& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Lin::WireLinControllerConfig& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Lin::LinControllerStatusUpdate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Lin::LinControllerStatusUpdate& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Lin::LinFrameResponseUpdate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Lin::LinFrameResponseUpdate& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::PubSub::WireDataMessageEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::PubSub::WireDataMessageEvent& msg) { SendMsgImpl(from, msg); } @@ -1095,7 +1157,8 @@ void Participant::SendMsg(const IServiceEndpoint* from, Servi } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Rpc::FunctionCallResponse& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Rpc::FunctionCallResponse& msg) { SendMsgImpl(from, msg); } @@ -1107,25 +1170,29 @@ void Participant::SendMsg(const IServiceEndpoint* from, Servi } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Orchestration::NextSimTask& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Orchestration::NextSimTask& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Orchestration::ParticipantStatus& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Orchestration::ParticipantStatus& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Orchestration::SystemCommand& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Orchestration::SystemCommand& msg) { SendMsgImpl(from, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const Services::Orchestration::WorkflowConfiguration& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Services::Orchestration::WorkflowConfiguration& msg) { SendMsgImpl(from, msg); } @@ -1144,7 +1211,8 @@ void Participant::SendMsg(const IServiceEndpoint* from, Servi } template -void Participant::SendMsg(const IServiceEndpoint* from, const Discovery::ParticipantDiscoveryEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const Discovery::ParticipantDiscoveryEvent& msg) { SendMsgImpl(from, std::move(msg)); } @@ -1162,7 +1230,8 @@ void Participant::SendMsg(const IServiceEndpoint* from, const } template -void Participant::SendMsg(const IServiceEndpoint* from, const RequestReply::RequestReplyCallReturn& msg) +void Participant::SendMsg(const IServiceEndpoint* from, + const RequestReply::RequestReplyCallReturn& msg) { SendMsgImpl(from, std::move(msg)); } @@ -1177,260 +1246,296 @@ void Participant::SendMsgImpl(const IServiceEndpoint* from, S // Targeted messaging template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Can::WireCanFrameEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Can::WireCanFrameEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Can::CanFrameTransmitEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Can::CanFrameTransmitEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Can::CanControllerStatus& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Can::CanControllerStatus& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Can::CanConfigureBaudrate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Can::CanConfigureBaudrate& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Can::CanSetControllerMode& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Can::CanSetControllerMode& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Ethernet::WireEthernetFrameEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Ethernet::WireEthernetFrameEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Ethernet::EthernetFrameTransmitEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Ethernet::EthernetFrameTransmitEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Ethernet::EthernetStatus& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Ethernet::EthernetStatus& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Ethernet::EthernetSetMode& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Ethernet::EthernetSetMode& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayFrameEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayFrameEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayFrameTransmitEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexraySymbolEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexraySymbolEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexraySymbolTransmitEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexraySymbolTransmitEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayCycleStartEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayCycleStartEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayHostCommand& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayHostCommand& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayControllerConfig& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayControllerConfig& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayTxBufferConfigUpdate& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::WireFlexrayTxBufferUpdate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::WireFlexrayTxBufferUpdate& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Flexray::FlexrayPocStatusEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Flexray::FlexrayPocStatusEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinSendFrameRequest& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinSendFrameRequest& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinSendFrameHeaderRequest& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinSendFrameHeaderRequest& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinTransmission& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinTransmission& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinWakeupPulse& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinWakeupPulse& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::WireLinControllerConfig& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::WireLinControllerConfig& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinControllerStatusUpdate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinControllerStatusUpdate& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Lin::LinFrameResponseUpdate& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Lin::LinFrameResponseUpdate& msg) { SendMsgImpl(from, targetParticipantName, msg); } template void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, - const Services::PubSub::WireDataMessageEvent& msg) + const Services::PubSub::WireDataMessageEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, - const Services::Rpc::FunctionCall& msg) + const Services::Rpc::FunctionCall& msg) { SendMsgImpl(from, targetParticipantName, msg); } template void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, - Services::Rpc::FunctionCall&& msg) + Services::Rpc::FunctionCall&& msg) { SendMsgImpl(from, targetParticipantName, std::move(msg)); } template void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, - const Services::Rpc::FunctionCallResponse& msg) + const Services::Rpc::FunctionCallResponse& msg) { SendMsgImpl(from, targetParticipantName, msg); } template void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, - Services::Rpc::FunctionCallResponse&& msg) + Services::Rpc::FunctionCallResponse&& msg) { SendMsgImpl(from, targetParticipantName, std::move(msg)); } template void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, - const Services::Orchestration::NextSimTask& msg) + const Services::Orchestration::NextSimTask& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Orchestration::ParticipantStatus& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Orchestration::ParticipantStatus& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Orchestration::SystemCommand& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Orchestration::SystemCommand& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Orchestration::WorkflowConfiguration& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Orchestration::WorkflowConfiguration& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Services::Logging::LogMsg& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Services::Logging::LogMsg& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, Services::Logging::LogMsg&& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + Services::Logging::LogMsg&& msg) { SendMsgImpl(from, targetParticipantName, std::move(msg)); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Discovery::ParticipantDiscoveryEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Discovery::ParticipantDiscoveryEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const Discovery::ServiceDiscoveryEvent& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const Discovery::ServiceDiscoveryEvent& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const RequestReply::RequestReplyCall& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const RequestReply::RequestReplyCall& msg) { SendMsgImpl(from, targetParticipantName, msg); } template -void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, const RequestReply::RequestReplyCallReturn& msg) +void Participant::SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, + const RequestReply::RequestReplyCallReturn& msg) { SendMsgImpl(from, targetParticipantName, msg); } template template -void Participant::SendMsgImpl(const IServiceEndpoint* from, const std::string& targetParticipantName, SilKitMessageT&& msg) +void Participant::SendMsgImpl(const IServiceEndpoint* from, const std::string& targetParticipantName, + SilKitMessageT&& msg) { TraceTx(GetLogger(), from, msg); _connection.SendMsg(from, targetParticipantName, std::forward(msg)); @@ -1456,22 +1561,20 @@ auto Participant::GetController(const std::string& serviceNam template template auto Participant::CreateController(const SilKitServiceTraitConfigType_t& config, - const SilKit::Core::SupplementalData& supplementalData, - const bool publishService, - Arg&&... arg) -> ControllerT* + const SilKit::Core::SupplementalData& supplementalData, + const bool publishService, Arg&&... arg) -> ControllerT* { SILKIT_ASSERT(config.network.has_value()); - return CreateController(config, *config.network, supplementalData, - publishService, std::forward(arg)...); + return CreateController(config, *config.network, supplementalData, publishService, + std::forward(arg)...); } template template auto Participant::CreateController(const SilKitServiceTraitConfigType_t& config, - const std::string& network, - const SilKit::Core::SupplementalData& supplementalData, - const bool publishService, - Arg&&... arg) -> ControllerT* + const std::string& network, + const SilKit::Core::SupplementalData& supplementalData, + const bool publishService, Arg&&... arg) -> ControllerT* { const auto serviceType = SilKitServiceTraitServiceType::GetServiceType(); if (config.name == "") @@ -1514,21 +1617,25 @@ auto Participant::CreateController(const SilKitServiceTraitCo return controllerPtr; } +template +void Participant::AddTraceSinksToSource(ITraceMessageSource* traceSource, + SilKit::Config::SimulatedNetwork config) +{ + AddTraceSinksToSourceInternal(traceSource, config); +} + template template -void Participant::AddTraceSinksToSource(ITraceMessageSource* traceSource, ConfigT config) +void Participant::AddTraceSinksToSourceInternal(ITraceMessageSource* traceSource, ConfigT config) { if (config.useTraceSinks.empty()) { Logging::Debug(GetLogger(), "Tracer on {}/{} not enabled, skipping", GetParticipantName(), config.name); return; } - auto findSinkByName = [this](const auto& name) - { - return std::find_if(_traceSinks.begin(), _traceSinks.end(), - [&name](const auto& sinkPtr) { - return sinkPtr->Name() == name; - }); + auto findSinkByName = [this](const auto& name) { + return std::find_if(_traceSinks.begin(), _traceSinks.end(), + [&name](const auto& sinkPtr) { return sinkPtr->Name() == name; }); }; for (const auto& sinkName : config.useTraceSinks) @@ -1536,8 +1643,8 @@ void Participant::AddTraceSinksToSource(ITraceMessageSource* auto sinkIter = findSinkByName(sinkName); if (sinkIter == _traceSinks.end()) { - Logging::Warn(GetLogger(), "Tracing: the service '{}' refers to non-existing trace sink '{}'", - config.name, sinkName); + Logging::Warn(GetLogger(), "Tracing: the service '{}' refers to non-existing trace sink '{}'", config.name, + sinkName); continue; } traceSource->AddSink((*sinkIter).get(), config.GetNetworkType()); @@ -1545,44 +1652,34 @@ void Participant::AddTraceSinksToSource(ITraceMessageSource* } template -void Participant::RegisterSimulator(ISimulator* busSim, const std::vector& networks) +void Participant::RegisterSimulator( + ISimulator* busSim, std::string networkName, Experimental::NetworkSimulation::SimulatedNetworkType networkType) { - auto& serviceEndpoint = dynamic_cast(*busSim); - auto oldDescriptor = serviceEndpoint.GetServiceDescriptor(); - // We temporarily overwrite the simulator's serviceEndpoint (not used internally) only for RegisterSilKitService - for (auto&& network: networks) - { - auto id = ServiceDescriptor{}; - id.SetNetworkName(network.name); - id.SetServiceName(network.name); - id.SetNetworkType(network.type); - id.SetParticipantNameAndComputeId(GetParticipantName()); - - serviceEndpoint.SetServiceDescriptor(id); - // Tell the middleware we are interested in this named network of the given type - switch (network.type) - { - case Config::NetworkType::CAN: - _connection.RegisterSilKitService(dynamic_cast(busSim)); break; - case Config::NetworkType::FlexRay: - _connection.RegisterSilKitService(dynamic_cast(busSim)); break; - case Config::NetworkType::LIN: - _connection.RegisterSilKitService(dynamic_cast(busSim)); break; - case Config::NetworkType::Ethernet: - _connection.RegisterSilKitService(dynamic_cast(busSim)); break; - default: - throw SilKitError{ "RegisterSimulator: simulator does not support given network type: " + to_string(network.type) }; - } - } - serviceEndpoint.SetServiceDescriptor(oldDescriptor); //restore + auto serviceDescriptor = ServiceDescriptor{}; + serviceDescriptor.SetNetworkName(networkName); + serviceDescriptor.SetServiceName(networkName); + serviceDescriptor.SetNetworkType(ConvertNetworkTypeToConfig(networkType)); + serviceDescriptor.SetParticipantNameAndComputeId(GetParticipantName()); + busSim->SetServiceDescriptor(serviceDescriptor); - auto traceSource = dynamic_cast(busSim); - if (traceSource) + // Tell the middleware we are interested in this named network of the given type + switch (networkType) { - for (auto&& network: networks) - { - AddTraceSinksToSource(traceSource, network); - } + case Experimental::NetworkSimulation::SimulatedNetworkType::CAN: + _connection.RegisterSilKitService(dynamic_cast(busSim)); + break; + case Experimental::NetworkSimulation::SimulatedNetworkType::FlexRay: + _connection.RegisterSilKitService(dynamic_cast(busSim)); + break; + case Experimental::NetworkSimulation::SimulatedNetworkType::LIN: + _connection.RegisterSilKitService(dynamic_cast(busSim)); + break; + case Experimental::NetworkSimulation::SimulatedNetworkType::Ethernet: + _connection.RegisterSilKitService(dynamic_cast(busSim)); + break; + default: + throw SilKitError{"RegisterSimulator: simulator does not support given network type: " + + to_string(networkType)}; } } @@ -1605,16 +1702,16 @@ void Participant::ExecuteDeferred(std::function callb } template -void Participant::SetAsyncSubscriptionsCompletionHandler(std::function handler) +void Participant::AddAsyncSubscriptionsCompletionHandler(std::function handler) { - _connection.SetAsyncSubscriptionsCompletionHandler(std::move(handler)); + _connection.AddAsyncSubscriptionsCompletionHandler(std::move(handler)); } template template void Participant::LogMismatchBetweenConfigAndPassedValue(const std::string& canonicalName, - const ValueT& passedValue, - const ValueT& configuredValue) + const ValueT& passedValue, + const ValueT& configuredValue) { std::stringstream ss; ss << "Mismatch between a configured and programmatically passed value. The configured value will be used." @@ -1653,23 +1750,18 @@ void Participant::NotifyShutdown() } template -void Participant::RegisterReplayController(ISimulator* simulator, const SilKit::Core::ServiceDescriptor& serviceDescriptor, const SilKit::Config::SimulatedNetwork& simulatedNetwork) +void Participant::RegisterReplayController(SilKit::Tracing::IReplayDataController* replayController, + const std::string& controllerName, + const SilKit::Config::SimulatedNetwork& simulatedNetwork) { - if (! _replayScheduler) + if (!_replayScheduler) { return; } - if(simulatedNetwork.replay.direction != SilKit::Config::Replay::Direction::Undefined) + if (simulatedNetwork.replay.direction != SilKit::Config::Replay::Direction::Undefined) { - auto&& replayController = dynamic_cast(simulator); - _replayScheduler->ConfigureController( - serviceDescriptor.GetServiceName(), - replayController, - simulatedNetwork.replay, - serviceDescriptor.GetNetworkName(), - serviceDescriptor.GetNetworkType() - ); - simulator->SetReplayActive(serviceDescriptor.GetNetworkType(), true); + _replayScheduler->ConfigureController(controllerName, replayController, simulatedNetwork.replay, + simulatedNetwork.name, simulatedNetwork.type); } } @@ -1680,6 +1772,18 @@ bool Participant::ParticipantHasCapability(const std::string& return _connection.ParticipantHasCapability(participantName, capability); } +template +std::string Participant::GetServiceDescriptorString( + SilKit::Experimental::NetworkSimulation::ControllerDescriptor controllerDescriptor) +{ + if (!_networkSimulatorInternal) + { + Logging::Warn(GetLogger(), "GetServiceDescriptorString was queried, but no network simulator exists."); + return ""; + } + return _networkSimulatorInternal->GetServiceDescriptorString(controllerDescriptor); +} + } // namespace Core } // namespace SilKit diff --git a/SilKit/source/core/participant/Test_Participant.cpp b/SilKit/source/core/participant/Test_Participant.cpp index 507c4493d..a9d2df31c 100644 --- a/SilKit/source/core/participant/Test_Participant.cpp +++ b/SilKit/source/core/participant/Test_Participant.cpp @@ -38,9 +38,7 @@ using namespace SilKit::Config; class Test_Participant : public testing::Test { protected: - Test_Participant() - { - } + Test_Participant() {} }; TEST_F(Test_Participant, throw_on_empty_participant_name) @@ -63,8 +61,7 @@ TEST_F(Test_Participant, use_configured_name_on_participant_name_mismatch) mockConfig->participantName = configuredParticipantName; - auto participant = - CreateNullConnectionParticipantImpl(mockConfig, "TestParticipant"); + auto participant = CreateNullConnectionParticipantImpl(mockConfig, "TestParticipant"); auto comParticipantName = participant->GetParticipantName(); EXPECT_EQ(participant->GetParticipantName(), configuredParticipantName); } diff --git a/SilKit/source/core/participant/ValidateAndSanitizeConfig.cpp b/SilKit/source/core/participant/ValidateAndSanitizeConfig.cpp index 11bb4ef5a..4e89fb591 100644 --- a/SilKit/source/core/participant/ValidateAndSanitizeConfig.cpp +++ b/SilKit/source/core/participant/ValidateAndSanitizeConfig.cpp @@ -28,8 +28,8 @@ namespace SilKit { namespace Core { auto ValidateAndSanitizeConfig(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri) - -> ValidateAndSanitizeConfigResult + const std::string& participantName, + const std::string& registryUri) -> ValidateAndSanitizeConfigResult { ValidateAndSanitizeConfigResult result; diff --git a/SilKit/source/core/participant/ValidateAndSanitizeConfig.hpp b/SilKit/source/core/participant/ValidateAndSanitizeConfig.hpp index 8eae2ed65..c311bf690 100644 --- a/SilKit/source/core/participant/ValidateAndSanitizeConfig.hpp +++ b/SilKit/source/core/participant/ValidateAndSanitizeConfig.hpp @@ -41,8 +41,8 @@ struct ValidateAndSanitizeConfigResult }; auto ValidateAndSanitizeConfig(std::shared_ptr participantConfig, - const std::string& participantName, const std::string& registryUri) - -> ValidateAndSanitizeConfigResult; + const std::string& participantName, + const std::string& registryUri) -> ValidateAndSanitizeConfigResult; } // namespace Core } // namespace SilKit diff --git a/SilKit/source/core/requests/IRequestReplyProcedure.hpp b/SilKit/source/core/requests/IRequestReplyProcedure.hpp index 490ad44e3..bc70ccce5 100644 --- a/SilKit/source/core/requests/IRequestReplyProcedure.hpp +++ b/SilKit/source/core/requests/IRequestReplyProcedure.hpp @@ -36,12 +36,12 @@ class IRequestReplyService; class IRequestReplyProcedure { public: - virtual ~IRequestReplyProcedure() = default; - virtual void ReceiveCall(IRequestReplyService* requestReplyService, Util::Uuid callUuid, std::vector callData) = 0; - virtual void ReceiveCallReturn(std::string fromParticipant, Util::Uuid callUuid, std::vector callReturnData, - CallReturnStatus callReturnStatus) = 0; + virtual void ReceiveCall(IRequestReplyService* requestReplyService, Util::Uuid callUuid, + std::vector callData) = 0; + virtual void ReceiveCallReturn(std::string fromParticipant, Util::Uuid callUuid, + std::vector callReturnData, CallReturnStatus callReturnStatus) = 0; virtual void SetRequestReplyServiceEndpoint(IServiceEndpoint* requestReplyServiceEndpoint) = 0; }; diff --git a/SilKit/source/core/requests/IRequestReplyService.hpp b/SilKit/source/core/requests/IRequestReplyService.hpp index 22ac2b387..165518be9 100644 --- a/SilKit/source/core/requests/IRequestReplyService.hpp +++ b/SilKit/source/core/requests/IRequestReplyService.hpp @@ -36,7 +36,6 @@ class IParticipantReplies; class IRequestReplyService { public: - virtual ~IRequestReplyService() = default; virtual Util::Uuid Call(FunctionType functionType, std::vector callData) = 0; diff --git a/SilKit/source/core/requests/RequestReplyDatatypes.hpp b/SilKit/source/core/requests/RequestReplyDatatypes.hpp index 7af791d92..02897e121 100644 --- a/SilKit/source/core/requests/RequestReplyDatatypes.hpp +++ b/SilKit/source/core/requests/RequestReplyDatatypes.hpp @@ -85,8 +85,10 @@ inline std::string to_string(FunctionType value) { switch (value) { - case FunctionType::ParticipantReplies: return "ParticipantReplies"; - case FunctionType::Invalid: return "Invalid"; + case FunctionType::ParticipantReplies: + return "ParticipantReplies"; + case FunctionType::Invalid: + return "Invalid"; }; throw SilKit::TypeConversionError{}; } @@ -95,18 +97,21 @@ inline std::string to_string(CallReturnStatus value) { switch (value) { - case CallReturnStatus::Success: return "Success"; - case CallReturnStatus::UnknownFunctionType: return "UnknownFunctionType"; - case CallReturnStatus::ProcedureError: return "ProcedureError"; - case CallReturnStatus::RecipientDisconnected: return "RecipientDisconnected"; + case CallReturnStatus::Success: + return "Success"; + case CallReturnStatus::UnknownFunctionType: + return "UnknownFunctionType"; + case CallReturnStatus::ProcedureError: + return "ProcedureError"; + case CallReturnStatus::RecipientDisconnected: + return "RecipientDisconnected"; }; throw SilKit::TypeConversionError{}; } inline std::ostream& operator<<(std::ostream& out, const RequestReplyCall& msg) { - out << "RequestReplyCall{functionType=" << to_string(msg.functionType) - << ", callUuid=" << msg.callUuid + out << "RequestReplyCall{functionType=" << to_string(msg.functionType) << ", callUuid=" << msg.callUuid << ", data=" << Util::AsHexString(msg.callData).WithSeparator(" ").WithMaxLength(16) << ", size=" << msg.callData.size() << "}"; diff --git a/SilKit/source/core/requests/RequestReplySerdes.cpp b/SilKit/source/core/requests/RequestReplySerdes.cpp index ff64a9ae7..5f2cd0d5b 100644 --- a/SilKit/source/core/requests/RequestReplySerdes.cpp +++ b/SilKit/source/core/requests/RequestReplySerdes.cpp @@ -27,43 +27,25 @@ namespace RequestReply { inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const RequestReplyCall& msg) { - buffer - << msg.callUuid - << msg.functionType - << msg.callData - ; + buffer << msg.callUuid << msg.functionType << msg.callData; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, RequestReplyCall& out) { - buffer - >> out.callUuid - >> out.functionType - >> out.callData - ; + buffer >> out.callUuid >> out.functionType >> out.callData; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const RequestReplyCallReturn& msg) { - buffer - << msg.callUuid - << msg.functionType - << msg.callReturnData - << msg.callReturnStatus - ; + buffer << msg.callUuid << msg.functionType << msg.callReturnData << msg.callReturnStatus; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, RequestReplyCallReturn& out) { - buffer - >> out.callUuid - >> out.functionType - >> out.callReturnData - >> out.callReturnStatus - ; + buffer >> out.callUuid >> out.functionType >> out.callReturnData >> out.callReturnStatus; return buffer; } diff --git a/SilKit/source/core/requests/RequestReplySerdes.hpp b/SilKit/source/core/requests/RequestReplySerdes.hpp index 82a27ac9f..4e0f599c3 100644 --- a/SilKit/source/core/requests/RequestReplySerdes.hpp +++ b/SilKit/source/core/requests/RequestReplySerdes.hpp @@ -34,6 +34,6 @@ void Serialize(SilKit::Core::MessageBuffer& buffer, const RequestReplyCallReturn void Deserialize(MessageBuffer& buffer, RequestReplyCall& out); void Deserialize(MessageBuffer& buffer, RequestReplyCallReturn& out); -} // namespace RequestReply +} // namespace RequestReply } // namespace Core } // namespace SilKit diff --git a/SilKit/source/core/requests/RequestReplyService.cpp b/SilKit/source/core/requests/RequestReplyService.cpp index 4c9aafcf7..ce62463ad 100644 --- a/SilKit/source/core/requests/RequestReplyService.cpp +++ b/SilKit/source/core/requests/RequestReplyService.cpp @@ -28,7 +28,8 @@ namespace SilKit { namespace Core { namespace RequestReply { -RequestReplyService::RequestReplyService(IParticipantInternal* participant, const std::string& participantName, ProcedureMap prodecures) +RequestReplyService::RequestReplyService(IParticipantInternal* participant, const std::string& participantName, + ProcedureMap prodecures) : _participant{participant} , _participantName{participantName} , _participantDisconnectCallReturns{} @@ -60,8 +61,7 @@ Util::Uuid RequestReplyService::Call(FunctionType functionType, std::vectorGetParticipantNamesOfRemoteReceivers(this, "REQUESTREPLYCALL"); + auto receivingParticipants = _participant->GetParticipantNamesOfRemoteReceivers(this, "REQUESTREPLYCALL"); // Prepare RequestReplyCallReturn message for disconnects. There, we only have the name // of the disconnected participant, so we directly map name and reply diff --git a/SilKit/source/core/requests/RequestReplyService.hpp b/SilKit/source/core/requests/RequestReplyService.hpp index c9d211ee4..ffc1b6abe 100644 --- a/SilKit/source/core/requests/RequestReplyService.hpp +++ b/SilKit/source/core/requests/RequestReplyService.hpp @@ -51,37 +51,36 @@ class RequestReplyService , public IServiceEndpoint , public IRequestReplyService { -public: - +public: RequestReplyService(IParticipantInternal* participant, const std::string& participantName, ProcedureMap procedures); virtual ~RequestReplyService() noexcept; - + // Disconnect handler void OnParticpantRemoval(const std::string& participantName); // IRequestReplyService Util::Uuid Call(FunctionType functionType, std::vector callData) override; - void SubmitCallReturn(Util::Uuid callUuid, FunctionType functionType, std::vector callReturnData, CallReturnStatus callReturnStatus) override; + void SubmitCallReturn(Util::Uuid callUuid, FunctionType functionType, std::vector callReturnData, + CallReturnStatus callReturnStatus) override; // IServiceEndpoint void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; // IReceiver void ReceiveMsg(const IServiceEndpoint* from, const RequestReplyCall& msg) override; void ReceiveMsg(const IServiceEndpoint* from, const RequestReplyCallReturn& msg) override; private: - void RemovePartcipantFromDisconnectLookup(Util::Uuid callUuid, const std::string& participantName); void ForwardCallToProcedure(const RequestReplyCall& msg); void ForwardCallReturnToProcedure(std::string fromParticipant, const RequestReplyCallReturn& msg); - + private: IParticipantInternal* _participant{nullptr}; std::string _participantName; ServiceDescriptor _serviceDescriptor; - + mutable std::recursive_mutex _requestReplyMx; std::atomic _shuttingDown{false}; @@ -95,4 +94,3 @@ class RequestReplyService } // namespace RequestReply } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/requests/Test_RequestReplyService.cpp b/SilKit/source/core/requests/Test_RequestReplyService.cpp index 26965eba9..2a38338a5 100644 --- a/SilKit/source/core/requests/Test_RequestReplyService.cpp +++ b/SilKit/source/core/requests/Test_RequestReplyService.cpp @@ -47,8 +47,7 @@ using namespace SilKit::Util; using ::SilKit::Core::Tests::DummyParticipant; -auto ARequestReplyCallWith(FunctionType functionType, std::vector callData) - -> Matcher +auto ARequestReplyCallWith(FunctionType functionType, std::vector callData) -> Matcher { return AllOf(Field(&RequestReplyCall::callData, callData), Field(&RequestReplyCall::functionType, functionType)); } @@ -57,10 +56,12 @@ class MockParticipant : public DummyParticipant { public: MOCK_METHOD(void, SendMsg, (const IServiceEndpoint*, const RequestReplyCall&), (override)); - MOCK_METHOD(void, SendMsg, (const IServiceEndpoint*, const std::string& targetParticipantName, const RequestReplyCallReturn&), (override)); + MOCK_METHOD(void, SendMsg, + (const IServiceEndpoint*, const std::string& targetParticipantName, const RequestReplyCallReturn&), + (override)); std::vector GetParticipantNamesOfRemoteReceivers(const IServiceEndpoint* /*service*/, - const std::string& /*msgTypeName*/) override + const std::string& /*msgTypeName*/) override { return {"P1", "P2"}; } @@ -69,16 +70,22 @@ class MockParticipant : public DummyParticipant { return 2; } - }; -class MockParticipantReplies : public IRequestReplyProcedure, public IParticipantReplies +class MockParticipantReplies + : public IRequestReplyProcedure + , public IParticipantReplies { public: // IRequestReplyProcedure - MOCK_METHOD(void, ReceiveCall, (IRequestReplyService * requestReplyService, Util::Uuid callUuid, std::vector callData), (override)); - MOCK_METHOD(void, ReceiveCallReturn, (std::string fromParticipant, Util::Uuid callUuid, std::vector callReturnData, CallReturnStatus callReturnStatus), (override)); - MOCK_METHOD(void, SetRequestReplyServiceEndpoint, (IServiceEndpoint* requestReplyServiceEndpoint), (override)); + MOCK_METHOD(void, ReceiveCall, + (IRequestReplyService * requestReplyService, Util::Uuid callUuid, std::vector callData), + (override)); + MOCK_METHOD(void, ReceiveCallReturn, + (std::string fromParticipant, Util::Uuid callUuid, std::vector callReturnData, + CallReturnStatus callReturnStatus), + (override)); + MOCK_METHOD(void, SetRequestReplyServiceEndpoint, (IServiceEndpoint * requestReplyServiceEndpoint), (override)); // IParticipantReplies MOCK_METHOD(void, CallAfterAllParticipantsReplied, (std::function completionFunction), (override)); }; @@ -87,13 +94,10 @@ class MockParticipantReplies : public IRequestReplyProcedure, public IParticipan class Test_RequestReplyService : public testing::Test { protected: - Test_RequestReplyService() - { - } + Test_RequestReplyService() {} MockParticipant _participant; MockParticipantReplies _participantReplies; - }; // RCP flow 1/4: Client: Call() sends out RequestReplyCall @@ -110,7 +114,8 @@ TEST_F(Test_RequestReplyService, test_call) // Test that SendMsg fires on Call() // Matcher needed here to exclude UUID which is returned by Call() itself, thus unknown in EXPECT_CALL. - EXPECT_CALL(_participant, SendMsg(&reqReplService, ARequestReplyCallWith(reqReplCall.functionType, reqReplCall.callData))); + EXPECT_CALL(_participant, + SendMsg(&reqReplService, ARequestReplyCallWith(reqReplCall.functionType, reqReplCall.callData))); reqReplCall.callUuid = reqReplService.Call(reqReplCall.functionType, reqReplCall.callData); // Test that a call with FunctionType::Invalid throws @@ -134,7 +139,7 @@ TEST_F(Test_RequestReplyService, test_functiontype_route_call_to_participantrepl EXPECT_CALL(_participantReplies, ReceiveCall(&reqReplService, reqReplCall.callUuid, reqReplCall.callData)); // Initiate receive - MockServiceEndpoint from{"p1", "n1","c1", 2}; + MockServiceEndpoint from{"p1", "n1", "c1", 2}; reqReplService.ReceiveMsg(&from, reqReplCall); // Invalid function type should throw @@ -142,7 +147,7 @@ TEST_F(Test_RequestReplyService, test_functiontype_route_call_to_participantrepl EXPECT_THROW(reqReplService.ReceiveMsg(&from, reqReplCall), SilKitError); } -// RCP flow 3/4: Server: Reveice a RequestReplyCall; SubmitCallReturn() sends out RequestReplyCallReturn +// RCP flow 3/4: Server: Reveice a RequestReplyCall; SubmitCallReturn() sends out RequestReplyCallReturn TEST_F(Test_RequestReplyService, test_submitcallreturn) { EXPECT_CALL(_participantReplies, SetRequestReplyServiceEndpoint(_)); @@ -162,7 +167,7 @@ TEST_F(Test_RequestReplyService, test_submitcallreturn) reqReplCallReturn.callReturnStatus = CallReturnStatus::Success; // Receive a call, test reception - MockServiceEndpoint from{"p1", "n1","c1", 2}; + MockServiceEndpoint from{"p1", "n1", "c1", 2}; EXPECT_CALL(_participantReplies, ReceiveCall(&reqReplService, reqReplCall.callUuid, reqReplCall.callData)); reqReplService.ReceiveMsg(&from, reqReplCall); @@ -170,10 +175,13 @@ TEST_F(Test_RequestReplyService, test_submitcallreturn) EXPECT_THROW(reqReplService.ReceiveMsg(&from, reqReplCall), SilKitError); // Test that SubmitCallReturn with FunctionType::Invalid throws - EXPECT_THROW(reqReplService.SubmitCallReturn({}, FunctionType::Invalid, {}, CallReturnStatus::Success), SilKitError); + EXPECT_THROW(reqReplService.SubmitCallReturn({}, FunctionType::Invalid, {}, CallReturnStatus::Success), + SilKitError); // Test that SubmitCallReturn with unknown UUID throws - EXPECT_THROW(reqReplService.SubmitCallReturn({1234, 1234}, FunctionType::ParticipantReplies, {}, CallReturnStatus::Success), SilKitError); + EXPECT_THROW( + reqReplService.SubmitCallReturn({1234, 1234}, FunctionType::ParticipantReplies, {}, CallReturnStatus::Success), + SilKitError); // Test that SendMsg fires on SubmitCallReturn() EXPECT_CALL(_participant, @@ -197,11 +205,12 @@ TEST_F(Test_RequestReplyService, test_functiontype_route_callreturn_to_participa reqReplCallReturn.callReturnStatus = CallReturnStatus::Success; // Test that FunctionType::ParticipantReplies is routed to ParticipantReplies - EXPECT_CALL(_participantReplies, ReceiveCallReturn("p1", reqReplCallReturn.callUuid, reqReplCallReturn.callReturnData, - reqReplCallReturn.callReturnStatus)); + EXPECT_CALL(_participantReplies, + ReceiveCallReturn("p1", reqReplCallReturn.callUuid, reqReplCallReturn.callReturnData, + reqReplCallReturn.callReturnStatus)); // Initiate receive - MockServiceEndpoint from{"p1", "n1","c1", 2}; + MockServiceEndpoint from{"p1", "n1", "c1", 2}; reqReplService.ReceiveMsg(&from, reqReplCallReturn); } @@ -230,13 +239,13 @@ TEST_F(Test_RequestReplyService, test_disconnect_during_call) // Removing "P1" will trigger the CallReturn via disconnect EXPECT_CALL(_participantReplies, ReceiveCallReturn("P1", reqReplCallReturn.callUuid, reqReplCallReturn.callReturnData, - CallReturnStatus::RecipientDisconnected)); + CallReturnStatus::RecipientDisconnected)); reqReplService.OnParticpantRemoval("P1"); // Removing "P2" will trigger the CallReturn via disconnect EXPECT_CALL(_participantReplies, - ReceiveCallReturn("P2" , reqReplCallReturn.callUuid, reqReplCallReturn.callReturnData, - CallReturnStatus::RecipientDisconnected)); + ReceiveCallReturn("P2", reqReplCallReturn.callUuid, reqReplCallReturn.callReturnData, + CallReturnStatus::RecipientDisconnected)); reqReplService.OnParticpantRemoval("P2"); } @@ -258,13 +267,12 @@ TEST_F(Test_RequestReplyService, test_unknown_function_type) reqReplCallReturn.callReturnStatus = CallReturnStatus::UnknownFunctionType; // Initiate receive - MockServiceEndpoint from{"p1", "n1","c1", 2}; + MockServiceEndpoint from{"p1", "n1", "c1", 2}; // The unknown function type cannot be routed to a procedure, the CallReturn is directly // submitted with CallReturnStatus::UnknownFunctionType and empty data EXPECT_CALL(_participant, SendMsg(&reqReplService, from.GetServiceDescriptor().GetParticipantName(), reqReplCallReturn)); reqReplService.ReceiveMsg(&from, reqReplCall); - } -} // anonymous namespace for test +} // namespace diff --git a/SilKit/source/core/requests/procs/IParticipantReplies.hpp b/SilKit/source/core/requests/procs/IParticipantReplies.hpp index 5db63a05e..9bba68702 100644 --- a/SilKit/source/core/requests/procs/IParticipantReplies.hpp +++ b/SilKit/source/core/requests/procs/IParticipantReplies.hpp @@ -32,10 +32,9 @@ namespace RequestReply { class IParticipantReplies { public: - virtual ~IParticipantReplies() = default; - - //! Send a RequestReplyCall to all participants. They will immediately respond with a RequestReplyCallReturn. + + //! Send a RequestReplyCall to all participants. They will immediately respond with a RequestReplyCallReturn. //! If all replies arrived, trigger the completionFunction. virtual void CallAfterAllParticipantsReplied(std::function completionFunction) = 0; }; diff --git a/SilKit/source/core/requests/procs/ParticipantReplies.cpp b/SilKit/source/core/requests/procs/ParticipantReplies.cpp index eb9266891..d077a2e4b 100644 --- a/SilKit/source/core/requests/procs/ParticipantReplies.cpp +++ b/SilKit/source/core/requests/procs/ParticipantReplies.cpp @@ -44,10 +44,11 @@ void ParticipantReplies::CallAfterAllParticipantsReplied(std::function c { // Execute deferred to prevent additional participants to join between GetNumberOfRemoteReceivers and actual SendMsg in GetRequestReplyService()->Call() _participant->ExecuteDeferred([this, completionFunction = std::move(completionFunction)]() mutable { - if (_barrierActive) { - Services::Logging::Debug(_participant->GetLogger(), "Only one barrier can be active at a time, ignoring."); + Services::Logging::Debug(_participant->GetLogger(), + "Still waiting for replies from participants on a previous call, action when new " + "call is replied will not be executed. This might lead to unexpected behavior."); return; } @@ -84,7 +85,9 @@ void ParticipantReplies::ReceiveCall(IRequestReplyService* requestReplyService, requestReplyService->SubmitCallReturn(callUuid, _functionType, {}, CallReturnStatus::Success); } -void ParticipantReplies::ReceiveCallReturn(std::string fromParticipant, Util::Uuid callUuid, std::vector /*callReturnData*/, CallReturnStatus /*callReturnStatus*/) +void ParticipantReplies::ReceiveCallReturn(std::string fromParticipant, Util::Uuid callUuid, + std::vector /*callReturnData*/, + CallReturnStatus /*callReturnStatus*/) { // All values of callReturnStatus are ok to complete the request. // If we know the callUuid, collect call returns and call the completion function @@ -106,4 +109,3 @@ void ParticipantReplies::ReceiveCallReturn(std::string fromParticipant, Util::Uu } // namespace RequestReply } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/requests/procs/ParticipantReplies.hpp b/SilKit/source/core/requests/procs/ParticipantReplies.hpp index 39ed17e8e..1488bbcd3 100644 --- a/SilKit/source/core/requests/procs/ParticipantReplies.hpp +++ b/SilKit/source/core/requests/procs/ParticipantReplies.hpp @@ -42,7 +42,6 @@ class ParticipantReplies , public IRequestReplyProcedure { public: - ParticipantReplies(IParticipantInternal* participant, IServiceEndpoint* requestReplyServiceEndpoint); // IParticipantReplies @@ -53,7 +52,8 @@ class ParticipantReplies void ReceiveCall(IRequestReplyService* requestReplyService, Util::Uuid callUuid, std::vector callData) override; - void ReceiveCallReturn(std::string fromParticipant, Util::Uuid callUuid, std::vector callReturnData, CallReturnStatus callReturnStatus) override; + void ReceiveCallReturn(std::string fromParticipant, Util::Uuid callUuid, std::vector callReturnData, + CallReturnStatus callReturnStatus) override; void SetRequestReplyServiceEndpoint(IServiceEndpoint* requestReplyService) override; @@ -70,8 +70,6 @@ class ParticipantReplies }; - } // namespace RequestReply } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/service/IServiceDiscovery.hpp b/SilKit/source/core/service/IServiceDiscovery.hpp index 8b8d1f741..f95260bba 100644 --- a/SilKit/source/core/service/IServiceDiscovery.hpp +++ b/SilKit/source/core/service/IServiceDiscovery.hpp @@ -36,7 +36,6 @@ using ServiceDiscoveryHandler = class IServiceDiscovery { public: - virtual ~IServiceDiscovery() = default; //!< Publish a locally created new ServiceDescriptor to all other participants virtual void NotifyServiceCreated(const ServiceDescriptor& serviceDescriptor) = 0; @@ -44,8 +43,8 @@ class IServiceDiscovery virtual void NotifyServiceRemoved(const ServiceDescriptor& serviceDescriptor) = 0; //!< Register a handler for asynchronous service creation notifications virtual void RegisterServiceDiscoveryHandler(ServiceDiscoveryHandler handler) = 0; - //!< Register a handler for service creation notifications for a specific controllerTypeName, - //!< associated supplDataKey and given supplDataValue + //!< Register a handler for service creation notifications for a specific controllerTypeName, + //!< associated supplDataKey and given supplDataValue virtual void RegisterSpecificServiceDiscoveryHandler( ServiceDiscoveryHandler handler, const std::string& controllerType, const std::string& topic, const std::vector& labels) = 0; @@ -53,9 +52,8 @@ class IServiceDiscovery virtual std::vector GetServices() const = 0; //!< React on a participant shutdown virtual void OnParticpantRemoval(const std::string& participantName) = 0; - }; -} // namespace Orchestration +} // namespace Discovery } // namespace Core } // namespace SilKit diff --git a/SilKit/source/core/service/MockServiceEndpoint.hpp b/SilKit/source/core/service/MockServiceEndpoint.hpp index 026f90c5a..4d792ad2f 100644 --- a/SilKit/source/core/service/MockServiceEndpoint.hpp +++ b/SilKit/source/core/service/MockServiceEndpoint.hpp @@ -18,7 +18,7 @@ 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. */ -#pragma once +#pragma once #include #include #include @@ -37,14 +37,15 @@ using namespace testing; class MockServiceEndpoint : public SilKit::Core::IServiceEndpoint { public: - MockServiceEndpoint(std::string participantName, std::string networkName, - std::string serviceName, EndpointId serviceId = 0) + MockServiceEndpoint(std::string participantName, std::string networkName, std::string serviceName, + EndpointId serviceId = 0) : _serviceDescriptor{participantName, networkName, serviceName, serviceId} { ON_CALL(*this, GetServiceDescriptor()).WillByDefault(ReturnRef(_serviceDescriptor)); } - MOCK_METHOD(void,SetServiceDescriptor, (const ServiceDescriptor& ), (override)); - MOCK_METHOD(const ServiceDescriptor&, GetServiceDescriptor, (),(const,override)); + MOCK_METHOD(void, SetServiceDescriptor, (const ServiceDescriptor&), (override)); + MOCK_METHOD(const ServiceDescriptor&, GetServiceDescriptor, (), (const, override)); + public: ServiceDescriptor _serviceDescriptor; }; diff --git a/SilKit/source/core/service/ServiceDatatypes.hpp b/SilKit/source/core/service/ServiceDatatypes.hpp index ebc5918dd..840d99f34 100644 --- a/SilKit/source/core/service/ServiceDatatypes.hpp +++ b/SilKit/source/core/service/ServiceDatatypes.hpp @@ -39,7 +39,7 @@ struct ServiceDiscoveryEvent ServiceCreated, ServiceRemoved, }; - Type type{ Type::Invalid }; + Type type{Type::Invalid}; ServiceDescriptor serviceDescriptor; }; @@ -55,15 +55,11 @@ struct ParticipantDiscoveryEvent //requires history >= 1 //////////////////////////////////////////////////////////////////////////////// inline bool operator==(const ServiceDiscoveryEvent& lhs, const ServiceDiscoveryEvent& rhs) { - return lhs.type == rhs.type - && lhs.serviceDescriptor == rhs.serviceDescriptor - ; + return lhs.type == rhs.type && lhs.serviceDescriptor == rhs.serviceDescriptor; } inline bool operator==(const ParticipantDiscoveryEvent& lhs, const ParticipantDiscoveryEvent& rhs) { - return lhs.participantName == rhs.participantName - && lhs.services == rhs.services - ; + return lhs.participantName == rhs.participantName && lhs.services == rhs.services; } inline bool operator!=(const ParticipantDiscoveryEvent& lhs, const ParticipantDiscoveryEvent& rhs) { @@ -77,9 +73,15 @@ inline std::ostream& operator<<(std::ostream& out, const ServiceDiscoveryEvent:: { switch (t) { - case ServiceDiscoveryEvent::Type::Invalid: out << "Invalid"; break; - case ServiceDiscoveryEvent::Type::ServiceCreated: out << "ServiceCreated"; break; - case ServiceDiscoveryEvent::Type::ServiceRemoved: out << "ServiceRemoved"; break; + case ServiceDiscoveryEvent::Type::Invalid: + out << "Invalid"; + break; + case ServiceDiscoveryEvent::Type::ServiceCreated: + out << "ServiceCreated"; + break; + case ServiceDiscoveryEvent::Type::ServiceRemoved: + out << "ServiceRemoved"; + break; default: out << "Unknown ServiceDiscoveryEvent::Type{" << static_cast>(t); @@ -94,14 +96,10 @@ inline std::ostream& operator<<(std::ostream& out, const ServiceDiscoveryEvent& inline std::ostream& operator<<(std::ostream& out, const ParticipantDiscoveryEvent& serviceAnnouncement) { - out << "ParticipantDiscoveryEvent{\"" << serviceAnnouncement.participantName - << "\", services=[" - ; + out << "ParticipantDiscoveryEvent{\"" << serviceAnnouncement.participantName << "\", services=["; for (auto&& service : serviceAnnouncement.services) { - out << service - << ", " - ; + out << service << ", "; } out << "] }"; return out; diff --git a/SilKit/source/core/service/ServiceDiscovery.cpp b/SilKit/source/core/service/ServiceDiscovery.cpp index d298c18af..6f1145a11 100644 --- a/SilKit/source/core/service/ServiceDiscovery.cpp +++ b/SilKit/source/core/service/ServiceDiscovery.cpp @@ -214,7 +214,8 @@ void ServiceDiscovery::OnServiceRemoval(const ServiceDescriptor& serviceDescript CallHandlers(ServiceDiscoveryEvent::Type::ServiceRemoved, serviceDescriptor); } -void ServiceDiscovery::CallHandlers(ServiceDiscoveryEvent::Type eventType, const ServiceDescriptor& serviceDescriptor) const +void ServiceDiscovery::CallHandlers(ServiceDiscoveryEvent::Type eventType, + const ServiceDescriptor& serviceDescriptor) const { // CallHandlers must be used with a lock on _discoveryMx for (auto&& handler : _handlers) diff --git a/SilKit/source/core/service/ServiceDiscovery.hpp b/SilKit/source/core/service/ServiceDiscovery.hpp index 8fc298e5d..8fc97b977 100644 --- a/SilKit/source/core/service/ServiceDiscovery.hpp +++ b/SilKit/source/core/service/ServiceDiscovery.hpp @@ -46,11 +46,10 @@ class ServiceDiscovery , public IServiceEndpoint , public Discovery::IServiceDiscovery { -public: - +public: ServiceDiscovery(IParticipantInternal* participant, const std::string& participantName); virtual ~ServiceDiscovery() noexcept; - + public: //IServiceDiscovery //!< Called on creating a service locally; Publish new service to ourselves and all other participants void NotifyServiceCreated(const ServiceDescriptor& serviceDescriptor) override; @@ -66,21 +65,19 @@ class ServiceDiscovery //!< Get all currently known services, including from ourselves std::vector GetServices() const override; - //!< React on a leaving participant, called via RegisterPeerShutdownCallback + //!< React on a leaving participant, called via RegisterPeerShutdownCallback void OnParticpantRemoval(const std::string& participantName) override; public: // Interfaces - // IServiceEndpoint void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; // IReceiver void ReceiveMsg(const IServiceEndpoint* from, const ParticipantDiscoveryEvent& msg) override; void ReceiveMsg(const IServiceEndpoint* from, const ServiceDiscoveryEvent& msg) override; private: // Methods - //!< React on a new participant void OnParticpantAddition(const ParticipantDiscoveryEvent& msg); @@ -88,7 +85,7 @@ class ServiceDiscovery void OnServiceRemoval(const ServiceDescriptor&); void OnServiceAddition(const ServiceDescriptor&); - //!< When a serciveDiscovery of another participant is discovered, we announce all services from ourselves + //!< When a serciveDiscovery of another participant is discovered, we announce all services from ourselves void AnnounceLocalParticipantTo(const std::string& otherParticipant); //!< Inform about service changes @@ -101,7 +98,7 @@ class ServiceDiscovery std::vector _handlers; //!< a cache for computing additions/removals per participant using ServiceMap = std::unordered_map; - std::unordered_map _servicesByParticipant; + std::unordered_map _servicesByParticipant; SpecificDiscoveryStore _specificDiscoveryStore; mutable std::recursive_mutex _discoveryMx; std::atomic _shuttingDown{false}; @@ -110,4 +107,3 @@ class ServiceDiscovery } // namespace Discovery } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/service/ServiceSerdes.cpp b/SilKit/source/core/service/ServiceSerdes.cpp index f0dd88346..cb04f412e 100644 --- a/SilKit/source/core/service/ServiceSerdes.cpp +++ b/SilKit/source/core/service/ServiceSerdes.cpp @@ -28,75 +28,48 @@ namespace Core { // ServiceDescriptor encoding is here, because it pulls in O_SilKit_Config inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, - const SilKit::Core::ServiceDescriptor& msg) + const SilKit::Core::ServiceDescriptor& msg) { - buffer - << msg._participantName - << msg._serviceType - << msg._networkName - << msg._networkType - << msg._serviceName - << msg._serviceId - << msg._supplementalData - << msg._participantId - ; + buffer << msg._participantName << msg._serviceType << msg._networkName << msg._networkType << msg._serviceName + << msg._serviceId << msg._supplementalData << msg._participantId; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, - SilKit::Core::ServiceDescriptor& updatedMsg) + SilKit::Core::ServiceDescriptor& updatedMsg) { - buffer - >> updatedMsg._participantName - >> updatedMsg._serviceType - >> updatedMsg._networkName - >> updatedMsg._networkType - >> updatedMsg._serviceName - >> updatedMsg._serviceId - >> updatedMsg._supplementalData - >> updatedMsg._participantId - ; + buffer >> updatedMsg._participantName >> updatedMsg._serviceType >> updatedMsg._networkName + >> updatedMsg._networkType >> updatedMsg._serviceName >> updatedMsg._serviceId >> updatedMsg._supplementalData + >> updatedMsg._participantId; return buffer; } namespace Discovery { // ParticipantDiscoveryEvent inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, - const ParticipantDiscoveryEvent& msg) + const ParticipantDiscoveryEvent& msg) { - buffer << msg.participantName - << msg.version - << msg.services - ; + buffer << msg.participantName << msg.version << msg.services; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, - ParticipantDiscoveryEvent& updatedMsg) + ParticipantDiscoveryEvent& updatedMsg) { - buffer >> updatedMsg.participantName - >> updatedMsg.version - >> updatedMsg.services - ; + buffer >> updatedMsg.participantName >> updatedMsg.version >> updatedMsg.services; return buffer; } // ServiceDiscoveryEvent -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, - const ServiceDiscoveryEvent& msg) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const ServiceDiscoveryEvent& msg) { - buffer << msg.type - << msg.serviceDescriptor - ; + buffer << msg.type << msg.serviceDescriptor; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, - ServiceDiscoveryEvent& updatedMsg) +inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, ServiceDiscoveryEvent& updatedMsg) { - buffer >> updatedMsg.type - >> updatedMsg.serviceDescriptor - ; + buffer >> updatedMsg.type >> updatedMsg.serviceDescriptor; return buffer; } diff --git a/SilKit/source/core/service/ServiceSerdes.hpp b/SilKit/source/core/service/ServiceSerdes.hpp index 8feb972e0..221d78ed1 100644 --- a/SilKit/source/core/service/ServiceSerdes.hpp +++ b/SilKit/source/core/service/ServiceSerdes.hpp @@ -35,6 +35,6 @@ void Serialize(SilKit::Core::MessageBuffer& buffer, const ServiceDiscoveryEvent& void Deserialize(MessageBuffer& buffer, ParticipantDiscoveryEvent& out); void Deserialize(MessageBuffer& buffer, ServiceDiscoveryEvent& out); -} // namespace Discovery +} // namespace Discovery } // namespace Core } // namespace SilKit diff --git a/SilKit/source/core/service/SpecificDiscoveryStore.cpp b/SilKit/source/core/service/SpecificDiscoveryStore.cpp index 96e8f2dd9..1d9fe5048 100644 --- a/SilKit/source/core/service/SpecificDiscoveryStore.cpp +++ b/SilKit/source/core/service/SpecificDiscoveryStore.cpp @@ -22,19 +22,19 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "SpecificDiscoveryStore.hpp" #include "YamlParser.hpp" namespace { -inline auto MakeFilter(const std::string& type, const std::string& topicOrFunction) - -> SilKit::Core::Discovery::FilterType +inline auto MakeFilter(const std::string& type, + const std::string& topicOrFunction) -> SilKit::Core::Discovery::FilterType { - return std::make_tuple(type, topicOrFunction); + return std::make_tuple(type, topicOrFunction); } } // end namespace namespace SilKit { namespace Core { namespace Discovery { -// Service changes get announced here. +// Service changes get announced here. void SpecificDiscoveryStore::ServiceChange(ServiceDiscoveryEvent::Type changeType, - const ServiceDescriptor& serviceDescriptor) + const ServiceDescriptor& serviceDescriptor) { std::string supplControllerTypeName; if (serviceDescriptor.GetSupplementalDataItem(Core::Discovery::controllerType, supplControllerTypeName)) @@ -58,7 +58,7 @@ void SpecificDiscoveryStore::ServiceChange(ServiceDiscoveryEvent::Type changeTyp // Add labels std::string labelsStr; - if(serviceDescriptor.GetSupplementalDataItem(supplKeyRpcClientLabels, labelsStr)) + if (serviceDescriptor.GetSupplementalDataItem(supplKeyRpcClientLabels, labelsStr)) { labels = SilKit::Config::Deserialize(labelsStr); } @@ -70,7 +70,7 @@ void SpecificDiscoveryStore::ServiceChange(ServiceDiscoveryEvent::Type changeTyp // Add labels std::string labelsStr; - if(serviceDescriptor.GetSupplementalDataItem(supplKeyDataPublisherPubLabels, labelsStr)) + if (serviceDescriptor.GetSupplementalDataItem(supplKeyDataPublisherPubLabels, labelsStr)) { labels = SilKit::Config::Deserialize(labelsStr); } @@ -90,9 +90,9 @@ void SpecificDiscoveryStore::ServiceChange(ServiceDiscoveryEvent::Type changeTyp } // A new subscriber shows up -> notify of all earlier services -void SpecificDiscoveryStore::CallHandlerOnHandlerRegistration(const ServiceDiscoveryHandler& handler, - const std::string& controllerType_, const std::string& key, - const std::vector& labels) +void SpecificDiscoveryStore::CallHandlerOnHandlerRegistration( + const ServiceDiscoveryHandler& handler, const std::string& controllerType_, const std::string& key, + const std::vector& labels) { // pre filter key and mediaType auto& entry = _lookup[MakeFilter(controllerType_, key)]; @@ -131,13 +131,14 @@ void SpecificDiscoveryStore::CallHandlerOnHandlerRegistration(const ServiceDisco // A new publisher shows up -> notify all subscriber handlers void SpecificDiscoveryStore::CallHandlersOnServiceChange(ServiceDiscoveryEvent::Type eventType, - const std::string& supplControllerTypeName, const std::string& key, + const std::string& supplControllerTypeName, + const std::string& key, const std::vector& labels, const ServiceDescriptor& serviceDescriptor) { // pre filter key and mediaType auto& entry = _lookup[MakeFilter(supplControllerTypeName, key)]; - + const SilKit::Services::MatchingLabel* greedyLabel = GetLabelWithMinimalHandlerSet(entry, labels); if (greedyLabel == nullptr) @@ -183,10 +184,11 @@ void SpecificDiscoveryStore::CallHandlersOnServiceChange(ServiceDiscoveryEvent:: } void SpecificDiscoveryStore::UpdateLookupOnServiceChange(ServiceDiscoveryEvent::Type eventType, - const std::string& supplControllerTypeName, const std::string& key, + const std::string& supplControllerTypeName, + const std::string& key, const std::vector& labels, const ServiceDescriptor& serviceDescriptor) -{ +{ if (eventType == ServiceDiscoveryEvent::Type::ServiceCreated) { InsertLookupNode(supplControllerTypeName, key, labels, serviceDescriptor); @@ -197,8 +199,8 @@ void SpecificDiscoveryStore::UpdateLookupOnServiceChange(ServiceDiscoveryEvent:: } } -auto SpecificDiscoveryStore::GetLabelWithMinimalHandlerSet( - DiscoveryKeyNode& keyNode, const std::vector& labels) +auto SpecificDiscoveryStore::GetLabelWithMinimalHandlerSet(DiscoveryKeyNode& keyNode, + const std::vector& labels) -> const SilKit::Services::MatchingLabel* { const SilKit::Services::MatchingLabel* outGreedyLabel = nullptr; @@ -237,8 +239,8 @@ auto SpecificDiscoveryStore::GetLabelWithMinimalHandlerSet( return outGreedyLabel; } -auto SpecificDiscoveryStore::GetLabelWithMinimalNodeSet(DiscoveryKeyNode& keyNode, - const std::vector& labels) +auto SpecificDiscoveryStore::GetLabelWithMinimalNodeSet(DiscoveryKeyNode& keyNode, + const std::vector& labels) -> const SilKit::Services::MatchingLabel* { const SilKit::Services::MatchingLabel* outGreedyLabel = nullptr; @@ -279,7 +281,7 @@ auto SpecificDiscoveryStore::GetLabelWithMinimalNodeSet(DiscoveryKeyNode& keyNod void SpecificDiscoveryStore::UpdateDiscoveryClusters(const std::string& controllerType_, const std::string& key, const std::vector& labels, - std::function updater) + std::function updater) { auto& entry = _lookup[MakeFilter(controllerType_, key)]; updater(entry.allCluster); @@ -315,13 +317,11 @@ void SpecificDiscoveryStore::UpdateDiscoveryClusters(const std::string& controll } // insert for every label - for (auto&& keyval: entry.notLabelMap) + for (auto&& keyval : entry.notLabelMap) { const auto& labelKey = keyval.first; auto foundLabel = - std::find_if(labels.begin(), labels.end(), [&labelKey](const auto& ml) { - return ml.key == labelKey; - }); + std::find_if(labels.begin(), labels.end(), [&labelKey](const auto& ml) { return ml.key == labelKey; }); if (foundLabel != labels.end()) { auto& labelEntry = entry.labelMap[MakeFilter(labelKey, foundLabel->value)]; @@ -336,34 +336,32 @@ void SpecificDiscoveryStore::UpdateDiscoveryClusters(const std::string& controll } } -void SpecificDiscoveryStore::InsertLookupNode(const std::string& controllerType_, const std::string& key, - const std::vector& labels, - const ServiceDescriptor& serviceDescriptor) +void SpecificDiscoveryStore::InsertLookupNode(const std::string& controllerType_, const std::string& key, + const std::vector& labels, + const ServiceDescriptor& serviceDescriptor) { - UpdateDiscoveryClusters(controllerType_, key, labels, [&serviceDescriptor](auto& cluster) { - cluster.nodes.push_back(serviceDescriptor); - }); + UpdateDiscoveryClusters(controllerType_, key, labels, + [&serviceDescriptor](auto& cluster) { cluster.nodes.push_back(serviceDescriptor); }); } void SpecificDiscoveryStore::RemoveLookupNode(const std::string& controllerType_, const std::string& key, const ServiceDescriptor& serviceDescriptor) { - auto& entry = _lookup[MakeFilter(controllerType_, key)]; entry.allCluster.nodes.erase( std::remove(entry.allCluster.nodes.begin(), entry.allCluster.nodes.end(), serviceDescriptor), - entry.allCluster.nodes.end()); + entry.allCluster.nodes.end()); entry.noLabelCluster.nodes.erase( std::remove(entry.noLabelCluster.nodes.begin(), entry.noLabelCluster.nodes.end(), serviceDescriptor), entry.noLabelCluster.nodes.end()); - for (auto&& keyval: entry.notLabelMap) + for (auto&& keyval : entry.notLabelMap) { auto& cluster = keyval.second; cluster.nodes.erase(std::remove(cluster.nodes.begin(), cluster.nodes.end(), serviceDescriptor), cluster.nodes.end()); } - for (auto&& keyval: entry.labelMap) + for (auto&& keyval : entry.labelMap) { auto& cluster = keyval.second; cluster.nodes.erase(std::remove(cluster.nodes.begin(), cluster.nodes.end(), serviceDescriptor), @@ -373,16 +371,15 @@ void SpecificDiscoveryStore::RemoveLookupNode(const std::string& controllerType_ void SpecificDiscoveryStore::InsertLookupHandler(const std::string& controllerType_, const std::string& key, const std::vector& labels, - ServiceDiscoveryHandler handler) + ServiceDiscoveryHandler handler) { auto handlerPtr = std::make_shared(std::move(handler)); - UpdateDiscoveryClusters(controllerType_, key, labels, [handlerPtr](auto& cluster) { - cluster.handlers.push_back(handlerPtr); - }); + UpdateDiscoveryClusters(controllerType_, key, labels, + [handlerPtr](auto& cluster) { cluster.handlers.push_back(handlerPtr); }); } void SpecificDiscoveryStore::RegisterSpecificServiceDiscoveryHandler( - ServiceDiscoveryHandler handler, const std::string& controllerType_, const std::string& key, + ServiceDiscoveryHandler handler, const std::string& controllerType_, const std::string& key, const std::vector& labels) { CallHandlerOnHandlerRegistration(handler, controllerType_, key, labels); @@ -392,4 +389,3 @@ void SpecificDiscoveryStore::RegisterSpecificServiceDiscoveryHandler( } // namespace Discovery } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/service/SpecificDiscoveryStore.hpp b/SilKit/source/core/service/SpecificDiscoveryStore.hpp old mode 100755 new mode 100644 index fe3cc2524..eb5fcf2e6 --- a/SilKit/source/core/service/SpecificDiscoveryStore.hpp +++ b/SilKit/source/core/service/SpecificDiscoveryStore.hpp @@ -43,10 +43,8 @@ struct FilterTypeHash { std::size_t operator()(const FilterType& ft) const { - return static_cast( - SilKit::Util::Hash::HashCombine(std::hash()(std::get<0>(ft)), - (std::hash()(std::get<1>(ft)))) - ); + return static_cast(SilKit::Util::Hash::HashCombine(std::hash()(std::get<0>(ft)), + (std::hash()(std::get<1>(ft))))); } }; @@ -77,8 +75,7 @@ class DiscoveryKeyNode //! Store to prevent quadratic lookup of services class SpecificDiscoveryStore { -public: - +public: /*! \brief Service addition/removal is called on service discovery events * * Note: Implementation is not thread safe, all public API interactions must be secured with a common mutex @@ -94,16 +91,16 @@ class SpecificDiscoveryStore * * Note: handler might be called for service discovery events that only if a subset of the parameter constraints * Implementation is not thread safe, all public API interactions must be secured with a common mutex - */ + */ void RegisterSpecificServiceDiscoveryHandler(ServiceDiscoveryHandler handler, const std::string& controllerType, const std::string& key, const std::vector& labels); private: //methods - //!< Trigger relevant handler calls when a service has changed void CallHandlersOnServiceChange(ServiceDiscoveryEvent::Type eventType, const std::string& controllerType, - const std::string& topic, const std::vector& labels, + const std::string& topic, + const std::vector& labels, const ServiceDescriptor& serviceDescriptor); //!< Trigger handler for past events that happened before registration @@ -120,7 +117,7 @@ class SpecificDiscoveryStore //!< Update all DiscoveryClusters within the internal lookup structure void UpdateDiscoveryClusters(const std::string& controllerType, const std::string& key, const std::vector& labels, - std::function); + std::function); //!< Looks for the label that returns a minimal handler set auto GetLabelWithMinimalHandlerSet(DiscoveryKeyNode& keyNode, @@ -133,21 +130,20 @@ class SpecificDiscoveryStore -> const SilKit::Services::MatchingLabel*; //!< Insert a new lookup node from internal lookup structure - void InsertLookupNode(const std::string& controllerType, const std::string& key, - const std::vector& labels, - const ServiceDescriptor& serviceDescriptor); - + void InsertLookupNode(const std::string& controllerType, const std::string& key, + const std::vector& labels, + const ServiceDescriptor& serviceDescriptor); + //!< Remove a new lookup node from internal lookup structure void RemoveLookupNode(const std::string& controllerType, const std::string& key, const ServiceDescriptor& serviceDescriptor); //!< Insert a new lookup handler - void InsertLookupHandler(const std::string& controllerType, const std::string& key, - const std::vector& labels, + void InsertLookupHandler(const std::string& controllerType, const std::string& key, + const std::vector& labels, ServiceDiscoveryHandler handler); private: //member - //!< SpecificDiscoveryStore is only available to a a sub set of controllers const std::unordered_set _allowedControllers = { controllerTypeDataPublisher, controllerTypeRpcServerInternal, controllerTypeRpcClient}; @@ -160,4 +156,3 @@ class SpecificDiscoveryStore } // namespace Discovery } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/service/Test_ServiceDiscovery.cpp b/SilKit/source/core/service/Test_ServiceDiscovery.cpp index 5ef43729d..31476df14 100644 --- a/SilKit/source/core/service/Test_ServiceDiscovery.cpp +++ b/SilKit/source/core/service/Test_ServiceDiscovery.cpp @@ -57,15 +57,12 @@ class MockParticipant : public DummyParticipant class Callbacks { public: - MOCK_METHOD(void, ServiceDiscoveryHandler, - (ServiceDiscoveryEvent::Type, const ServiceDescriptor&)); + MOCK_METHOD(void, ServiceDiscoveryHandler, (ServiceDiscoveryEvent::Type, const ServiceDescriptor&)); }; class Test_ServiceDiscovery : public testing::Test { protected: - Test_ServiceDiscovery() - { - } + Test_ServiceDiscovery() {} protected: @@ -89,7 +86,7 @@ TEST_F(Test_ServiceDiscovery, portable_hash_function) testStrings.push_back(to_string(Uuid::GenerateRandom())); } std::set hashes; - for (const auto& s: testStrings) + for (const auto& s : testStrings) { hashes.insert(SilKit::Util::Hash::Hash(s)); } @@ -102,19 +99,17 @@ TEST_F(Test_ServiceDiscovery, service_creation_notification) senderDescriptor.SetParticipantNameAndComputeId("ParticipantA"); senderDescriptor.SetNetworkName("Link1"); senderDescriptor.SetServiceName("ServiceDiscovery"); - ServiceDiscovery disco{ &participant, "ParticipantA" }; + ServiceDiscovery disco{&participant, "ParticipantA"}; disco.SetServiceDescriptor(senderDescriptor); ServiceDescriptor descr; descr = senderDescriptor; - disco.RegisterServiceDiscoveryHandler( - [&descr](auto /*eventType*/, auto&& newServiceDescr) { - ASSERT_EQ(descr.GetSupplementalData(), newServiceDescr.GetSupplementalData()); - }); - disco.RegisterServiceDiscoveryHandler([this](auto type, auto&& serviceDescr) { - callbacks.ServiceDiscoveryHandler(type, serviceDescr); + disco.RegisterServiceDiscoveryHandler([&descr](auto /*eventType*/, auto&& newServiceDescr) { + ASSERT_EQ(descr.GetSupplementalData(), newServiceDescr.GetSupplementalData()); }); + disco.RegisterServiceDiscoveryHandler( + [this](auto type, auto&& serviceDescr) { callbacks.ServiceDiscoveryHandler(type, serviceDescr); }); // reference data for validation ServiceDiscoveryEvent event; @@ -123,30 +118,27 @@ TEST_F(Test_ServiceDiscovery, service_creation_notification) // NotifyServiceCreated should publish a message EXPECT_CALL(participant, SendMsg(&disco, event)).Times(1); // NotifyServiceCreated should also trigger ourself - EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, - descr)).Times(1); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, descr)).Times(1); // trigger notification on the same participant disco.NotifyServiceCreated(descr); // trigger notifications on reception path from different participant - MockServiceEndpoint otherParticipant{ "P1", "N1", "C1", 2 }; + MockServiceEndpoint otherParticipant{"P1", "N1", "C1", 2}; descr.SetParticipantNameAndComputeId("ParticipantOther"); event.serviceDescriptor = descr; - EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, - descr)).Times(1); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, descr)).Times(1); // when sending a different service descriptor, we expect a notification once disco.ReceiveMsg(&otherParticipant, event); - disco.ReceiveMsg(&otherParticipant, event);//should not trigger callback, is cached + disco.ReceiveMsg(&otherParticipant, event); //should not trigger callback, is cached } TEST_F(Test_ServiceDiscovery, multiple_service_creation_notification) { - MockServiceEndpoint otherParticipant{ "P1", "N1", "C1", 2 }; - ServiceDiscovery disco{ &participant, "ParticipantA" }; + MockServiceEndpoint otherParticipant{"P1", "N1", "C1", 2}; + ServiceDiscovery disco{&participant, "ParticipantA"}; - disco.RegisterServiceDiscoveryHandler([this](auto type, auto&& descr) { - callbacks.ServiceDiscoveryHandler(type, descr); - }); + disco.RegisterServiceDiscoveryHandler( + [this](auto type, auto&& descr) { callbacks.ServiceDiscoveryHandler(type, descr); }); ServiceDescriptor senderDescriptor; senderDescriptor.SetParticipantNameAndComputeId("ParticipantA"); @@ -165,13 +157,10 @@ TEST_F(Test_ServiceDiscovery, multiple_service_creation_notification) // Expect that each serviceDescriptor is only handled by a single notification handler // e.g., no duplicate notifications - EXPECT_CALL(callbacks, - ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, descr) - ).Times(1); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, descr)).Times(1); disco.ReceiveMsg(&otherParticipant, event); - disco.ReceiveMsg(&otherParticipant, event);//duplicate should not trigger a notification - + disco.ReceiveMsg(&otherParticipant, event); //duplicate should not trigger a notification }; for (auto i = 0; i < 10; i++) @@ -182,12 +171,11 @@ TEST_F(Test_ServiceDiscovery, multiple_service_creation_notification) TEST_F(Test_ServiceDiscovery, service_removal) { - MockServiceEndpoint otherParticipant{ "P1", "N1", "C1", 2 }; - ServiceDiscovery disco{ &participant, "ParticipantA" }; + MockServiceEndpoint otherParticipant{"P1", "N1", "C1", 2}; + ServiceDiscovery disco{&participant, "ParticipantA"}; - disco.RegisterServiceDiscoveryHandler([this](auto type, auto&& descr) { - callbacks.ServiceDiscoveryHandler(type, descr); - }); + disco.RegisterServiceDiscoveryHandler( + [this](auto type, auto&& descr) { callbacks.ServiceDiscoveryHandler(type, descr); }); ServiceDescriptor senderDescriptor; senderDescriptor.SetParticipantNameAndComputeId("ParticipantA"); @@ -203,36 +191,27 @@ TEST_F(Test_ServiceDiscovery, service_removal) event.serviceDescriptor = descr; // Test addition - EXPECT_CALL(callbacks, - ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, descr) - ).Times(1); - EXPECT_CALL(callbacks, - ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceRemoved, descr) - ).Times(0); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, descr)).Times(1); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceRemoved, descr)).Times(0); disco.ReceiveMsg(&otherParticipant, event); // add a modified one event.serviceDescriptor.SetServiceName("Modified"); auto modifiedDescr = event.serviceDescriptor; - EXPECT_CALL(callbacks, - ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, modifiedDescr) - ).Times(1); - EXPECT_CALL(callbacks, - ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceRemoved, modifiedDescr) - ).Times(0); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, modifiedDescr)) + .Times(1); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceRemoved, modifiedDescr)) + .Times(0); disco.ReceiveMsg(&otherParticipant, event); // Test removal event.type = ServiceDiscoveryEvent::Type::ServiceRemoved; - EXPECT_CALL(callbacks, - ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceRemoved, modifiedDescr) - ).Times(1); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceRemoved, modifiedDescr)) + .Times(1); disco.ReceiveMsg(&otherParticipant, event); // Nothing to remove, no triggers event.type = ServiceDiscoveryEvent::Type::ServiceRemoved; - EXPECT_CALL(callbacks, - ServiceDiscoveryHandler(_, _) - ).Times(0); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(_, _)).Times(0); disco.ReceiveMsg(&otherParticipant, event); } -} // anonymous namespace for test +} // namespace diff --git a/SilKit/source/core/service/Test_ServiceSerdes.cpp b/SilKit/source/core/service/Test_ServiceSerdes.cpp index 7838d4b24..7af4be48c 100644 --- a/SilKit/source/core/service/Test_ServiceSerdes.cpp +++ b/SilKit/source/core/service/Test_ServiceSerdes.cpp @@ -29,7 +29,8 @@ TEST(Test_ServiceSerdes, Mw_Service) SilKit::Core::Discovery::ParticipantDiscoveryEvent in{}; in.participantName = "Input"; - for (auto i = 0; i < 10; i++) { + for (auto i = 0; i < 10; i++) + { SilKit::Core::SupplementalData supplementalData; supplementalData["hello"] = "world"; @@ -45,7 +46,7 @@ TEST(Test_ServiceSerdes, Mw_Service) } SilKit::Core::Discovery::ParticipantDiscoveryEvent out{}; - + Serialize(buffer, in); Deserialize(buffer, out); @@ -57,4 +58,3 @@ TEST(Test_ServiceSerdes, Mw_Service) std::string dummy; EXPECT_EQ(out.services.at(9).GetSupplementalDataItem("Second", dummy), true); } - diff --git a/SilKit/source/core/service/Test_SpecificDiscoveryStore.cpp b/SilKit/source/core/service/Test_SpecificDiscoveryStore.cpp index 4839feec2..727e7a521 100644 --- a/SilKit/source/core/service/Test_SpecificDiscoveryStore.cpp +++ b/SilKit/source/core/service/Test_SpecificDiscoveryStore.cpp @@ -51,22 +51,21 @@ using ::SilKit::Core::Tests::DummyParticipant; class TestWrapperSpecificDiscoveryStore : public SpecificDiscoveryStore { public: - std::unordered_map& GetLookup() { return _lookup; }; - + std::unordered_map& GetLookup() + { + return _lookup; + }; }; class Callbacks { public: - MOCK_METHOD(void, ServiceDiscoveryHandler, - (ServiceDiscoveryEvent::Type, const ServiceDescriptor&)); + MOCK_METHOD(void, ServiceDiscoveryHandler, (ServiceDiscoveryEvent::Type, const ServiceDescriptor&)); }; class Test_SpecificDiscoveryStore : public testing::Test { protected: - Test_SpecificDiscoveryStore() - { - } + Test_SpecificDiscoveryStore() {} protected: @@ -98,10 +97,10 @@ TEST_F(Test_SpecificDiscoveryStore, no_reaction_on_irrelevant_services) testDescriptor.SetNetworkName("Link1"); testDescriptor.SetServiceName("ServiceDiscovery"); - + TestWrapperSpecificDiscoveryStore testStore; - for (std::string& ctrlType: controllerTypes) + for (std::string& ctrlType : controllerTypes) { testDescriptor.SetSupplementalDataItem(Core::Discovery::controllerType, ctrlType); testStore.ServiceChange(ServiceDiscoveryEvent::Type::ServiceCreated, testDescriptor); @@ -139,10 +138,10 @@ TEST_F(Test_SpecificDiscoveryStore, lookup_entries_pubsub) ASSERT_EQ(entry.allCluster.nodes[0], noLabelTestDescriptor); testStore.ServiceChange(ServiceDiscoveryEvent::Type::ServiceCreated, labelTestDescriptor); - + //refresh lookup and entry entry = lookup[std::make_tuple(controllerTypeDataPublisher, "Topic1")]; - + ASSERT_EQ(entry.noLabelCluster.nodes.size(), 1); ASSERT_EQ(entry.noLabelCluster.nodes[0], noLabelTestDescriptor); auto& labelMapEntry = entry.labelMap[std::make_tuple("kA", "vA")]; @@ -274,10 +273,10 @@ TEST_F(Test_SpecificDiscoveryStore, lookup_handler_then_service_discovery) testStore.RegisterSpecificServiceDiscoveryHandler( [this](ServiceDiscoveryEvent::Type discoveryType, const ServiceDescriptor& sd) { - callbacks.ServiceDiscoveryHandler(discoveryType, sd); - }, - controllerTypeDataPublisher, "Topic1", {}); - EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, noLabelTestDescriptor)).Times(1); + callbacks.ServiceDiscoveryHandler(discoveryType, sd); + }, controllerTypeDataPublisher, "Topic1", {}); + EXPECT_CALL(callbacks, ServiceDiscoveryHandler(ServiceDiscoveryEvent::Type::ServiceCreated, noLabelTestDescriptor)) + .Times(1); testStore.ServiceChange(ServiceDiscoveryEvent::Type::ServiceCreated, noLabelTestDescriptor); } @@ -304,9 +303,8 @@ TEST_F(Test_SpecificDiscoveryStore, lookup_service_discovery_then_handler_no_lab .Times(1); testStore.RegisterSpecificServiceDiscoveryHandler( [this](ServiceDiscoveryEvent::Type discoveryType, const ServiceDescriptor& sd) { - callbacks.ServiceDiscoveryHandler(discoveryType, sd); - }, - controllerTypeDataPublisher, "Topic1", {}); + callbacks.ServiceDiscoveryHandler(discoveryType, sd); + }, controllerTypeDataPublisher, "Topic1", {}); } TEST_F(Test_SpecificDiscoveryStore, lookup_service_discovery_then_handler_labels) @@ -333,9 +331,8 @@ TEST_F(Test_SpecificDiscoveryStore, lookup_service_discovery_then_handler_labels testStore.RegisterSpecificServiceDiscoveryHandler( [this](ServiceDiscoveryEvent::Type discoveryType, const ServiceDescriptor& sd) { - callbacks.ServiceDiscoveryHandler(discoveryType, sd); - }, - controllerTypeDataPublisher, "Topic1", {label}); + callbacks.ServiceDiscoveryHandler(discoveryType, sd); + }, controllerTypeDataPublisher, "Topic1", {label}); } TEST_F(Test_SpecificDiscoveryStore, lookup_service_discovery_then_handler_issues) @@ -356,7 +353,8 @@ TEST_F(Test_SpecificDiscoveryStore, lookup_service_discovery_then_handler_issues ServiceDescriptor labelTestDescriptor{baseDescriptor}; labelTestDescriptor.SetSupplementalDataItem(supplKeyDataPublisherPubLabels, - " - key: kA\n value: vA\n kind: 2\n - key: kB\n value: vB\n kind: 2\n - key: kC\n value: vC\n kind: 2 "); + " - key: kA\n value: vA\n kind: 2\n - key: kB\n value: vB\n " + "kind: 2\n - key: kC\n value: vC\n kind: 2 "); labelTestDescriptor.SetServiceId(2); testStore.ServiceChange(ServiceDiscoveryEvent::Type::ServiceCreated, labelTestDescriptor); @@ -375,37 +373,35 @@ TEST_F(Test_SpecificDiscoveryStore, lookup_service_discovery_then_handler_issues testStore.RegisterSpecificServiceDiscoveryHandler( [this, optionalSubscriberLabels](ServiceDiscoveryEvent::Type discoveryType, const ServiceDescriptor& sd) { - std::vector labels; - std::string labelsStr; - if (sd.GetSupplementalDataItem(supplKeyDataPublisherPubLabels, labelsStr)) - { - labels = SilKit::Config::Deserialize(labelsStr); - } - if (MatchLabels(labels, optionalSubscriberLabels)) - { - callbacks.ServiceDiscoveryHandler(discoveryType, sd); - } - }, - controllerTypeDataPublisher, "Topic1", optionalSubscriberLabels); - - std::vector optionalSubscriberLabels2 { - {"kA", "vA", SilKit::Services::MatchingLabel::Kind::Optional}, - {"kB", "vB", SilKit::Services::MatchingLabel::Kind::Optional}, - {"kC", "vC", SilKit::Services::MatchingLabel::Kind::Optional}}; + std::vector labels; + std::string labelsStr; + if (sd.GetSupplementalDataItem(supplKeyDataPublisherPubLabels, labelsStr)) + { + labels = SilKit::Config::Deserialize(labelsStr); + } + if (MatchLabels(labels, optionalSubscriberLabels)) + { + callbacks.ServiceDiscoveryHandler(discoveryType, sd); + } + }, controllerTypeDataPublisher, "Topic1", optionalSubscriberLabels); + + std::vector optionalSubscriberLabels2{ + {"kA", "vA", SilKit::Services::MatchingLabel::Kind::Optional}, + {"kB", "vB", SilKit::Services::MatchingLabel::Kind::Optional}, + {"kC", "vC", SilKit::Services::MatchingLabel::Kind::Optional}}; testStore.RegisterSpecificServiceDiscoveryHandler( [this, optionalSubscriberLabels2](ServiceDiscoveryEvent::Type discoveryType, const ServiceDescriptor& sd) { - std::vector labels; - std::string labelsStr; - if (sd.GetSupplementalDataItem(supplKeyDataPublisherPubLabels, labelsStr)) - { - labels = SilKit::Config::Deserialize(labelsStr); - } - if (MatchLabels(labels, optionalSubscriberLabels2)) - { - callbacks.ServiceDiscoveryHandler(discoveryType, sd); - } - }, - controllerTypeDataPublisher, "Topic1", optionalSubscriberLabels2); + std::vector labels; + std::string labelsStr; + if (sd.GetSupplementalDataItem(supplKeyDataPublisherPubLabels, labelsStr)) + { + labels = SilKit::Config::Deserialize(labelsStr); + } + if (MatchLabels(labels, optionalSubscriberLabels2)) + { + callbacks.ServiceDiscoveryHandler(discoveryType, sd); + } + }, controllerTypeDataPublisher, "Topic1", optionalSubscriberLabels2); } -} // anonymous namespace for test +} // namespace diff --git a/SilKit/source/core/vasio/ConnectKnownParticipants.cpp b/SilKit/source/core/vasio/ConnectKnownParticipants.cpp index a2225bd1e..1dafa9ec7 100644 --- a/SilKit/source/core/vasio/ConnectKnownParticipants.cpp +++ b/SilKit/source/core/vasio/ConnectKnownParticipants.cpp @@ -34,9 +34,9 @@ #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_VAsioConnection -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif diff --git a/SilKit/source/core/vasio/ConnectPeer.cpp b/SilKit/source/core/vasio/ConnectPeer.cpp index b39c812ae..e609b7701 100644 --- a/SilKit/source/core/vasio/ConnectPeer.cpp +++ b/SilKit/source/core/vasio/ConnectPeer.cpp @@ -17,9 +17,9 @@ #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_ConnectPeer -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif @@ -62,9 +62,7 @@ void ConnectPeer::AsyncConnect(size_t numberOfAttempts, std::chrono::millisecond _remainingAttempts = std::max(numberOfAttempts, 1); _timeout = timeout; - _ioContext->Dispatch([this] { - TryNextUri(); - }); + _ioContext->Dispatch([this] { TryNextUri(); }); } @@ -187,9 +185,7 @@ void ConnectPeer::TryNextUri() _remainingAttempts -= 1; _uriIndex = 0; - _ioContext->Dispatch([this] { - TryNextUri(); - }); + _ioContext->Dispatch([this] { TryNextUri(); }); return; } @@ -241,9 +237,7 @@ void ConnectPeer::TryNextUri() if (_connector == nullptr) { - _ioContext->Dispatch([this] { - TryNextUri(); - }); + _ioContext->Dispatch([this] { TryNextUri(); }); } } diff --git a/SilKit/source/core/vasio/RemoteConnectionManager.cpp b/SilKit/source/core/vasio/RemoteConnectionManager.cpp index 2b0435c93..46ec3cd6a 100644 --- a/SilKit/source/core/vasio/RemoteConnectionManager.cpp +++ b/SilKit/source/core/vasio/RemoteConnectionManager.cpp @@ -29,9 +29,9 @@ #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_VAsioConnection -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif @@ -79,10 +79,8 @@ void RemoteConnectionManager::Remove(const IConnectPeer &connectPeer) { std::lock_guard lock{_mutex}; - _connectPeers.erase( - std::remove_if(_connectPeers.begin(), _connectPeers.end(), [needle = &connectPeer](const auto &hay) { - return needle == hay.get(); - })); + _connectPeers.erase(std::remove_if(_connectPeers.begin(), _connectPeers.end(), + [needle = &connectPeer](const auto &hay) { return needle == hay.get(); })); } diff --git a/SilKit/source/core/vasio/SerializedMessage.cpp b/SilKit/source/core/vasio/SerializedMessage.cpp index c9a74ee8c..df209468d 100644 --- a/SilKit/source/core/vasio/SerializedMessage.cpp +++ b/SilKit/source/core/vasio/SerializedMessage.cpp @@ -58,7 +58,7 @@ auto SerializedMessage::GetRemoteIndex() const -> EndpointId if (!IsMwOrSim(_messageKind)) { throw SilKitError("SerializedMessage::GetEndpointAddress called on wrong message kind: " - + std::to_string((int)_messageKind)); + + std::to_string((int)_messageKind)); } return _remoteIndex; } @@ -68,7 +68,7 @@ auto SerializedMessage::GetEndpointAddress() const -> EndpointAddress if (!IsMwOrSim(_messageKind)) { throw SilKitError("SerializedMessage::GetEndpointAddress called on wrong message kind: " - + std::to_string((int)_messageKind)); + + std::to_string((int)_messageKind)); } return _endpointAddress; } @@ -118,7 +118,7 @@ void SerializedMessage::ReadNetworkHeaders() // ParticipantAnnouncement and KnownParticipants start with the RegistryMessageHeader // ParticipantAnnouncementReply does _NOT_ start with the RegistryMessageHeader - switch(_registryKind) + switch (_registryKind) { case RegistryMessageKind::ParticipantAnnouncement: case RegistryMessageKind::KnownParticipants: diff --git a/SilKit/source/core/vasio/SerializedMessage.hpp b/SilKit/source/core/vasio/SerializedMessage.hpp index 5f38feda6..c8989f34e 100644 --- a/SilKit/source/core/vasio/SerializedMessage.hpp +++ b/SilKit/source/core/vasio/SerializedMessage.hpp @@ -42,13 +42,13 @@ namespace SilKit { namespace Core { // Helper to allow calling Deserialize(MessageBuffer&, T&) inside of template method SerializedMessage::Deserialize -template +template auto AdlDeserialize(Args&&... args) -> decltype(auto) { - return Deserialize(std::forward(args)...); + return Deserialize(std::forward(args)...); } -template +template struct SerializedSize { size_t _size{}; @@ -68,54 +68,54 @@ struct SerializedSize class SerializedMessage { public: //defaulted CTors - SerializedMessage(SerializedMessage&&) = default; - SerializedMessage& operator=(SerializedMessage&&) = default; - SerializedMessage(const SerializedMessage&) = default; - SerializedMessage& operator=(const SerializedMessage&) = default; + SerializedMessage(SerializedMessage&&) = default; + SerializedMessage& operator=(SerializedMessage&&) = default; + SerializedMessage(const SerializedMessage&) = default; + SerializedMessage& operator=(const SerializedMessage&) = default; public: // Sending a SerializedMessage: from T to binary blob - template + template explicit SerializedMessage(const MessageT& message); - // Sim messages have additional parameters: - template - explicit SerializedMessage(const MessageT& message , EndpointAddress endpointAddress, EndpointId remoteIndex); - template - explicit SerializedMessage(ProtocolVersion version, const MessageT& message); + // Sim messages have additional parameters: + template + explicit SerializedMessage(const MessageT& message, EndpointAddress endpointAddress, EndpointId remoteIndex); + template + explicit SerializedMessage(ProtocolVersion version, const MessageT& message); - auto ReleaseStorage() -> std::vector; + auto ReleaseStorage() -> std::vector; public: // Receiving a SerializedMessage: from binary blob to SilKitMessage - explicit SerializedMessage(std::vector&& blob); - - template - auto Deserialize() -> ApiMessageT; - template - auto Deserialize() const -> ApiMessageT; - - auto GetMessageKind() const -> VAsioMsgKind; - auto GetRegistryKind() const -> RegistryMessageKind; - auto GetRemoteIndex() const -> EndpointId; - auto GetEndpointAddress() const -> EndpointAddress; - void SetProtocolVersion(ProtocolVersion version); + explicit SerializedMessage(std::vector&& blob); + + template + auto Deserialize() -> ApiMessageT; + template + auto Deserialize() const -> ApiMessageT; + + auto GetMessageKind() const -> VAsioMsgKind; + auto GetRegistryKind() const -> RegistryMessageKind; + auto GetRemoteIndex() const -> EndpointId; + auto GetEndpointAddress() const -> EndpointAddress; + void SetProtocolVersion(ProtocolVersion version); auto GetProxyMessageHeader() const -> ProxyMessageHeader; - auto GetRegistryMessageHeader() const -> RegistryMsgHeader; + auto GetRegistryMessageHeader() const -> RegistryMsgHeader; private: - void WriteNetworkHeaders(); - void ReadNetworkHeaders(); - // network headers, some members are optional depending on messageKind - uint32_t _messageSize{0}; - VAsioMsgKind _messageKind{VAsioMsgKind::Invalid}; - RegistryMessageKind _registryKind{RegistryMessageKind::Invalid}; - // For simMsg - EndpointAddress _endpointAddress{}; - EndpointId _remoteIndex{0}; - // For registry messages - RegistryMsgHeader _registryMessageHeader; + void WriteNetworkHeaders(); + void ReadNetworkHeaders(); + // network headers, some members are optional depending on messageKind + uint32_t _messageSize{0}; + VAsioMsgKind _messageKind{VAsioMsgKind::Invalid}; + RegistryMessageKind _registryKind{RegistryMessageKind::Invalid}; + // For simMsg + EndpointAddress _endpointAddress{}; + EndpointId _remoteIndex{0}; + // For registry messages + RegistryMsgHeader _registryMessageHeader; // For proxy messages ProxyMessageHeader _proxyMessageHeader; - MessageBuffer _buffer; + MessageBuffer _buffer; }; ////////////////////////////////////////////////////////////////////// diff --git a/SilKit/source/core/vasio/SerializedMessageTraits.hpp b/SilKit/source/core/vasio/SerializedMessageTraits.hpp index b0e8c3cba..c9f348e3c 100644 --- a/SilKit/source/core/vasio/SerializedMessageTraits.hpp +++ b/SilKit/source/core/vasio/SerializedMessageTraits.hpp @@ -29,38 +29,74 @@ namespace Core { // The VAsioMsgKind tags are encoded in serialized (network) messages. // default is SilKitMwMsg -template -inline constexpr auto messageKind() -> VAsioMsgKind { return VAsioMsgKind::SilKitMwMsg; } +template +inline constexpr auto messageKind() -> VAsioMsgKind +{ + return VAsioMsgKind::SilKitMwMsg; +} // Registry messages -template<> -inline constexpr auto messageKind() -> VAsioMsgKind { return VAsioMsgKind::SilKitRegistryMessage; } -template<> -inline constexpr auto messageKind() -> VAsioMsgKind { return VAsioMsgKind::SilKitRegistryMessage; } -template<> -inline constexpr auto messageKind() -> VAsioMsgKind { return VAsioMsgKind::SilKitRegistryMessage; } -template<> -inline constexpr auto messageKind() -> VAsioMsgKind { return VAsioMsgKind::SilKitRegistryMessage; } +template <> +inline constexpr auto messageKind() -> VAsioMsgKind +{ + return VAsioMsgKind::SilKitRegistryMessage; +} +template <> +inline constexpr auto messageKind() -> VAsioMsgKind +{ + return VAsioMsgKind::SilKitRegistryMessage; +} +template <> +inline constexpr auto messageKind() -> VAsioMsgKind +{ + return VAsioMsgKind::SilKitRegistryMessage; +} +template <> +inline constexpr auto messageKind() -> VAsioMsgKind +{ + return VAsioMsgKind::SilKitRegistryMessage; +} // Service subscription -template<> -inline constexpr auto messageKind() -> VAsioMsgKind { return VAsioMsgKind::SubscriptionAcknowledge; } -template<> -inline constexpr auto messageKind() -> VAsioMsgKind { return VAsioMsgKind::SubscriptionAnnouncement; } +template <> +inline constexpr auto messageKind() -> VAsioMsgKind +{ + return VAsioMsgKind::SubscriptionAcknowledge; +} +template <> +inline constexpr auto messageKind() -> VAsioMsgKind +{ + return VAsioMsgKind::SubscriptionAnnouncement; +} // Proxy messages -template<> -inline constexpr auto messageKind() -> VAsioMsgKind { return VAsioMsgKind::SilKitProxyMessage; } +template <> +inline constexpr auto messageKind() -> VAsioMsgKind +{ + return VAsioMsgKind::SilKitProxyMessage; +} -template -inline constexpr auto registryMessageKind() -> RegistryMessageKind { return RegistryMessageKind::Invalid; } -template<> -inline constexpr auto registryMessageKind() -> RegistryMessageKind { return RegistryMessageKind::ParticipantAnnouncement; } -template<> -inline constexpr auto registryMessageKind() -> RegistryMessageKind { return RegistryMessageKind::ParticipantAnnouncementReply; } -template<> -inline constexpr auto registryMessageKind() -> RegistryMessageKind { return RegistryMessageKind::KnownParticipants; } -template<> +template +inline constexpr auto registryMessageKind() -> RegistryMessageKind +{ + return RegistryMessageKind::Invalid; +} +template <> +inline constexpr auto registryMessageKind() -> RegistryMessageKind +{ + return RegistryMessageKind::ParticipantAnnouncement; +} +template <> +inline constexpr auto registryMessageKind() -> RegistryMessageKind +{ + return RegistryMessageKind::ParticipantAnnouncementReply; +} +template <> +inline constexpr auto registryMessageKind() -> RegistryMessageKind +{ + return RegistryMessageKind::KnownParticipants; +} +template <> inline constexpr auto registryMessageKind() -> RegistryMessageKind { return RegistryMessageKind::RemoteParticipantConnectRequest; @@ -74,9 +110,7 @@ inline constexpr bool IsMwOrSim(VAsioMsgKind kind); ////////////////////////////////////////////////////////////////////// inline constexpr bool IsMwOrSim(VAsioMsgKind kind) { - return kind == VAsioMsgKind::SilKitMwMsg - || kind == VAsioMsgKind::SilKitSimMsg - ; + return kind == VAsioMsgKind::SilKitMwMsg || kind == VAsioMsgKind::SilKitSimMsg; } } // namespace Core diff --git a/SilKit/source/core/vasio/SilKitLink.hpp b/SilKit/source/core/vasio/SilKitLink.hpp old mode 100755 new mode 100644 index 38c59162d..06ed81d6b --- a/SilKit/source/core/vasio/SilKitLink.hpp +++ b/SilKit/source/core/vasio/SilKitLink.hpp @@ -42,14 +42,24 @@ class SilKitLink public: // ---------------------------------------- // Constructors and Destructor - SilKitLink(std::string name, Services::Logging::ILogger* logger, Services::Orchestration::ITimeProvider* timeProvider); + SilKitLink(std::string name, Services::Logging::ILogger* logger, + Services::Orchestration::ITimeProvider* timeProvider); public: // ---------------------------------------- // Public methods - static constexpr auto MsgTypeName() -> const char* { return SilKitMsgTraits::TypeName(); } - static constexpr auto MessageSerdesName() -> const char* { return SilKitMsgTraits::SerdesName(); } - inline auto Name() const -> const std::string& { return _name; } + static constexpr auto MsgTypeName() -> const char* + { + return SilKitMsgTraits::TypeName(); + } + static constexpr auto MessageSerdesName() -> const char* + { + return SilKitMsgTraits::SerdesName(); + } + inline auto Name() const -> const std::string& + { + return _name; + } void AddLocalReceiver(ReceiverT* receiver); void AddRemoteReceiver(IVAsioPeer* peer, EndpointId remoteIdx); @@ -62,12 +72,14 @@ class SilKitLink void SetHistoryLength(size_t history); - void DispatchSilKitMessageToTarget(const IServiceEndpoint* from, const std::string& targetParticipantName, const MsgT& msg); + void DispatchSilKitMessageToTarget(const IServiceEndpoint* from, const std::string& targetParticipantName, + const MsgT& msg); private: // ---------------------------------------- // private methods void DispatchSilKitMessage(ReceiverT* to, const IServiceEndpoint* from, const MsgT& msg); + void DistributeToSelf(const IServiceEndpoint* from, const MsgT& msg); private: // ---------------------------------------- @@ -84,7 +96,8 @@ class SilKitLink // Inline Implementations // ================================================================================ template -SilKitLink::SilKitLink(std::string name, Services::Logging::ILogger* logger, Services::Orchestration::ITimeProvider* timeProvider) +SilKitLink::SilKitLink(std::string name, Services::Logging::ILogger* logger, + Services::Orchestration::ITimeProvider* timeProvider) : _name{std::move(name)} , _logger{logger} , _timeProvider{timeProvider} @@ -94,7 +107,8 @@ SilKitLink::SilKitLink(std::string name, Services::Logging::ILogger* logge template void SilKitLink::AddLocalReceiver(ReceiverT* receiver) { - if (std::find(_localReceivers.begin(), _localReceivers.end(), receiver) != _localReceivers.end()) return; + if (std::find(_localReceivers.begin(), _localReceivers.end(), receiver) != _localReceivers.end()) + return; _localReceivers.push_back(receiver); } @@ -134,7 +148,8 @@ void SetTimestamp(MsgT& msg, std::chrono::nanoseconds value, std::enable_if_t -void SetTimestamp(MsgT& /*msg*/, std::chrono::nanoseconds /*value*/, std::enable_if_t::value, bool> = false) +void SetTimestamp(MsgT& /*msg*/, std::chrono::nanoseconds /*value*/, + std::enable_if_t::value, bool> = false) { } @@ -161,6 +176,12 @@ void SilKitLink::DistributeLocalSilKitMessage(const IServiceEndpoint* from // Otherwise, messages that may be produced during the internal dispatch will be dispatched to remote receivers first. // As a result, the messages may be delivered in the wrong order (possibly even reversed) DispatchSilKitMessage(&_vasioTransmitter, from, msg); + DistributeToSelf(from, msg); +} + +template +void SilKitLink::DistributeToSelf(const IServiceEndpoint* from, const MsgT& msg) +{ for (auto&& receiver : _localReceivers) { auto* receiverId = dynamic_cast(receiver); @@ -173,7 +194,8 @@ void SilKitLink::DistributeLocalSilKitMessage(const IServiceEndpoint* from // C++ 17 -> if constexpr if (!SilKitMsgTraits::IsSelfDeliveryEnforced()) { - if (receiverId->GetServiceDescriptor() == from->GetServiceDescriptor()) continue; + if (receiverId->GetServiceDescriptor() == from->GetServiceDescriptor()) + continue; } // Trace reception of self delivery Services::TraceRx(_logger, receiverId, msg, from->GetServiceDescriptor()); @@ -192,7 +214,8 @@ void SilKitLink::DispatchSilKitMessage(ReceiverT* to, const IServiceEndpoi } catch (const std::exception& e) { - Services::Logging::Warn(_logger, "Callback for {}[\"{}\"] threw an exception: {}", MsgTypeName(), Name(), e.what()); + Services::Logging::Warn(_logger, "Callback for {}[\"{}\"] threw an exception: {}", MsgTypeName(), Name(), + e.what()); } catch (...) { @@ -201,9 +224,17 @@ void SilKitLink::DispatchSilKitMessage(ReceiverT* to, const IServiceEndpoi } template -void SilKitLink::DispatchSilKitMessageToTarget(const IServiceEndpoint* from, const std::string& targetParticipantName, const MsgT& msg) +void SilKitLink::DispatchSilKitMessageToTarget(const IServiceEndpoint* from, + const std::string& targetParticipantName, const MsgT& msg) { - _vasioTransmitter.SendMessageToTarget(from, targetParticipantName, msg); + if (from->GetServiceDescriptor().GetParticipantName() == targetParticipantName) + { + DistributeToSelf(from, msg); + } + else + { + _vasioTransmitter.SendMessageToTarget(from, targetParticipantName, msg); + } } template diff --git a/SilKit/source/core/vasio/Test_ConnectKnownParticipants.cpp b/SilKit/source/core/vasio/Test_ConnectKnownParticipants.cpp index 811d13dbb..74a3404ff 100644 --- a/SilKit/source/core/vasio/Test_ConnectKnownParticipants.cpp +++ b/SilKit/source/core/vasio/Test_ConnectKnownParticipants.cpp @@ -134,9 +134,8 @@ TEST_F(Test_ConnectKnownParticipants, empty_known_participants_calls_success_han TEST_F(Test_ConnectKnownParticipants, successful_connection_initiates_waiting_for_replies) { - auto MakeSucceedingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { - return MakeConnectPeerThatSucceeds(peerInfo); - }}; + auto MakeSucceedingConnectPeer{ + [this](const VAsioPeerInfo& peerInfo) { return MakeConnectPeerThatSucceeds(peerInfo); }}; VAsioPeerInfo peerInfo; peerInfo.participantName = "A"; @@ -157,9 +156,9 @@ TEST_F(Test_ConnectKnownParticipants, successful_connection_initiates_waiting_fo EXPECT_CALL(connectionMethods, MakeVAsioPeer(WithRemoteEndpoint(peerInfo.acceptorUris.front()))) .InSequence(s1) .WillOnce([](std::unique_ptr) { - auto vAsioPeer{std::make_unique>()}; - return vAsioPeer; - }); + auto vAsioPeer{std::make_unique>()}; + return vAsioPeer; + }); EXPECT_CALL(connectionMethods, HandleConnectedPeer).InSequence(s1); EXPECT_CALL(connectionMethods, AddPeer).InSequence(s1); @@ -182,9 +181,7 @@ TEST_F(Test_ConnectKnownParticipants, successful_connection_initiates_waiting_fo TEST_F(Test_ConnectKnownParticipants, direct_connect_fallback_to_remote_connect_fallback_to_proxy_triggers_failure) { - auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { - return MakeConnectPeerThatFails(peerInfo); - }}; + auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { return MakeConnectPeerThatFails(peerInfo); }}; VAsioPeerInfo peerInfo; peerInfo.participantName = "A"; @@ -227,9 +224,7 @@ TEST_F(Test_ConnectKnownParticipants, direct_connect_fallback_to_remote_connect_ TEST_F(Test_ConnectKnownParticipants, remote_connect_timer_expiry_fallback_to_proxy) { - auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { - return MakeConnectPeerThatFails(peerInfo); - }}; + auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { return MakeConnectPeerThatFails(peerInfo); }}; VAsioPeerInfo peerInfo; peerInfo.participantName = "A"; @@ -284,9 +279,7 @@ TEST_F(Test_ConnectKnownParticipants, remote_connect_waits_for_replies_after_con // connection is actually attempted. The first message over the remote connection triggers the // REMOTE_PARTICIPANT_ANNOUNCEMENT notification. - auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { - return MakeConnectPeerThatFails(peerInfo); - }}; + auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { return MakeConnectPeerThatFails(peerInfo); }}; VAsioPeerInfo peerInfo; peerInfo.participantName = "A"; @@ -340,9 +333,7 @@ TEST_F(Test_ConnectKnownParticipants, remote_connect_waits_for_replies_after_ann // It is possible that the REMOTE_PARTICIPANT_ANNOUNCEMENT is received before the REMOTE_PARTICIPANT_IS_CONNECTING. // This might happen if connection establishment is really fast, and the registry is really slow for some reason. - auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { - return MakeConnectPeerThatFails(peerInfo); - }}; + auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { return MakeConnectPeerThatFails(peerInfo); }}; VAsioPeerInfo peerInfo; peerInfo.participantName = "A"; @@ -396,9 +387,7 @@ TEST_F(Test_ConnectKnownParticipants, remote_connect_fallback_to_proxy_after_fai // It is possible that the REMOTE_PARTICIPANT_ANNOUNCEMENT is received before the REMOTE_PARTICIPANT_IS_CONNECTING. // This might happen if connection establishment is really fast, and the registry is really slow for some reason. - auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { - return MakeConnectPeerThatFails(peerInfo); - }}; + auto MakeFailingConnectPeer{[this](const VAsioPeerInfo& peerInfo) { return MakeConnectPeerThatFails(peerInfo); }}; VAsioPeerInfo peerInfo; peerInfo.participantName = "A"; diff --git a/SilKit/source/core/vasio/Test_ConnectPeer.cpp b/SilKit/source/core/vasio/Test_ConnectPeer.cpp index bd478752c..64b03b3d1 100644 --- a/SilKit/source/core/vasio/Test_ConnectPeer.cpp +++ b/SilKit/source/core/vasio/Test_ConnectPeer.cpp @@ -86,9 +86,7 @@ TEST_F(Test_ConnectPeer, tcp_hosts_are_resolved_and_tried_in_order_with_specifie static constexpr bool DOMAIN_SOCKETS_ENABLED{true}; static constexpr auto TIMEOUT{4321ms}; - auto MakeConnector{[this] { - return MakeConnectorThatFails(TIMEOUT); - }}; + auto MakeConnector{[this] { return MakeConnectorThatFails(TIMEOUT); }}; // Arrange @@ -126,9 +124,7 @@ TEST_F(Test_ConnectPeer, local_is_tried_before_tcp_but_order_is_stable) static constexpr bool DOMAIN_SOCKETS_ENABLED{true}; static constexpr auto TIMEOUT{4321ms}; - auto MakeConnector{[this] { - return MakeConnectorThatFails(TIMEOUT); - }}; + auto MakeConnector{[this] { return MakeConnectorThatFails(TIMEOUT); }}; // Arrange @@ -175,9 +171,7 @@ TEST_F(Test_ConnectPeer, retry_count_is_honored) static constexpr size_t RETRY_COUNT{3}; static constexpr auto TIMEOUT{4321ms}; - auto MakeConnector{[this] { - return MakeConnectorThatFails(TIMEOUT); - }}; + auto MakeConnector{[this] { return MakeConnectorThatFails(TIMEOUT); }}; // Arrange @@ -216,9 +210,7 @@ TEST_F(Test_ConnectPeer, each_retry_tries_each_uri) static constexpr size_t RETRY_COUNT{2}; static constexpr auto TIMEOUT{4321ms}; - auto MakeConnector{[this] { - return MakeConnectorThatFails(TIMEOUT); - }}; + auto MakeConnector{[this] { return MakeConnectorThatFails(TIMEOUT); }}; // Arrange @@ -255,9 +247,7 @@ TEST_F(Test_ConnectPeer, disabling_local_domain_ignores_local_uris) static constexpr bool DOMAIN_SOCKETS_ENABLED{false}; static constexpr auto TIMEOUT{4321ms}; - auto MakeConnector{[this] { - return MakeConnectorThatFails(TIMEOUT); - }}; + auto MakeConnector{[this] { return MakeConnectorThatFails(TIMEOUT); }}; // Arrange @@ -293,15 +283,11 @@ TEST_F(Test_ConnectPeer, successful_connection_skips_remainder) static constexpr bool DOMAIN_SOCKETS_ENABLED{true}; static constexpr auto TIMEOUT{4321ms}; - auto MakeFailingConnector{[this] { - return MakeConnectorThatFails(TIMEOUT); - }}; + auto MakeFailingConnector{[this] { return MakeConnectorThatFails(TIMEOUT); }}; auto MakeSucceedingConnector{[this] { auto connector{MakeConnectorThatSucceeds(TIMEOUT)}; - EXPECT_CALL(*connector, MakeRawByteStream).WillOnce([] { - return std::make_unique(); - }); + EXPECT_CALL(*connector, MakeRawByteStream).WillOnce([] { return std::make_unique(); }); return connector; }}; diff --git a/SilKit/source/core/vasio/Test_ParticipantVersion.cpp b/SilKit/source/core/vasio/Test_ParticipantVersion.cpp index 80f9bbb93..ca94b11e6 100644 --- a/SilKit/source/core/vasio/Test_ParticipantVersion.cpp +++ b/SilKit/source/core/vasio/Test_ParticipantVersion.cpp @@ -42,8 +42,8 @@ namespace { using namespace SilKit::Core; -auto MakeParticipant(std::string participantName, std::string registryUri, ProtocolVersion version) - -> std::shared_ptr +auto MakeParticipant(std::string participantName, std::string registryUri, + ProtocolVersion version) -> std::shared_ptr { auto cfg = SilKit::Config::ParticipantConfiguration{}; cfg.participantName = std::move(participantName); diff --git a/SilKit/source/core/vasio/Test_SerializedMessage.cpp b/SilKit/source/core/vasio/Test_SerializedMessage.cpp index f14153c12..b3b05e00e 100644 --- a/SilKit/source/core/vasio/Test_SerializedMessage.cpp +++ b/SilKit/source/core/vasio/Test_SerializedMessage.cpp @@ -86,9 +86,7 @@ TEST(Test_SerializedMessage, packed_handshake_message) ASSERT_EQ(ptr->participantNameSize, announcement.peerInfo.participantName.size()); - auto to_string = [](const auto& data, auto size) { - return std::string{(const char*)data.data(), size}; - }; + auto to_string = [](const auto& data, auto size) { return std::string{(const char*)data.data(), size}; }; ASSERT_EQ(to_string(ptr->participantName, ptr->participantNameSize), announcement.peerInfo.participantName); diff --git a/SilKit/source/core/vasio/Test_VAsioConnection.cpp b/SilKit/source/core/vasio/Test_VAsioConnection.cpp old mode 100755 new mode 100644 index ee05da0f4..94e380527 --- a/SilKit/source/core/vasio/Test_VAsioConnection.cpp +++ b/SilKit/source/core/vasio/Test_VAsioConnection.cpp @@ -86,8 +86,10 @@ struct MockSilKitMessageReceiver ON_CALL(*this, GetServiceDescriptor()).WillByDefault(ReturnRef(_serviceDescriptor)); } // IMessageReceiver - MOCK_METHOD(void, ReceiveMsg, (const SilKit::Core::IServiceEndpoint*, const Tests::Version1::TestMessage&), (override)); - MOCK_METHOD(void, ReceiveMsg, (const SilKit::Core::IServiceEndpoint*, const Tests::Version2::TestMessage&), (override)); + MOCK_METHOD(void, ReceiveMsg, (const SilKit::Core::IServiceEndpoint*, const Tests::Version1::TestMessage&), + (override)); + MOCK_METHOD(void, ReceiveMsg, (const SilKit::Core::IServiceEndpoint*, const Tests::Version2::TestMessage&), + (override)); MOCK_METHOD(void, ReceiveMsg, (const SilKit::Core::IServiceEndpoint*, const Tests::TestFrameEvent&), (override)); // IServiceEndpoint @@ -96,8 +98,7 @@ struct MockSilKitMessageReceiver }; -struct MockVAsioPeer - : public IVAsioPeer +struct MockVAsioPeer : public IVAsioPeer { VAsioPeerInfo _peerInfo; ServiceDescriptor _serviceDescriptor; @@ -146,7 +147,7 @@ struct MockVAsioPeer // Matchers ////////////////////////////////////////////////////////////////////// MATCHER_P(AnnouncementReplyMatcher, validator, - "Deserialize the MessageBuffer from the SerializedMessage and check the announcement's reply") + "Deserialize the MessageBuffer from the SerializedMessage and check the announcement's reply") { SerializedMessage message = arg; auto reply = message.Deserialize(); @@ -154,13 +155,11 @@ MATCHER_P(AnnouncementReplyMatcher, validator, } MATCHER_P(SubscriptionAcknowledgeMatcher, subscriber, - "Deserialize the MessageBuffer from the SerializedMessage and check the subscriptions's ack") + "Deserialize the MessageBuffer from the SerializedMessage and check the subscriptions's ack") { SerializedMessage message = arg; auto reply = message.Deserialize(); - return reply.status == SubscriptionAcknowledge::Status::Success - && reply.subscriber == subscriber - ; + return reply.status == SubscriptionAcknowledge::Status::Success && reply.subscriber == subscriber; } } // namespace @@ -188,7 +187,7 @@ class Test_VAsioConnection : public testing::Test //we are a friend class // - allow selected access to private member - template + template void RegisterSilKitMsgReceiver(SilKit::Core::IMessageReceiver* receiver) { _connection.RegisterSilKitMsgReceiver(receiver); @@ -210,8 +209,7 @@ TEST_F(Test_VAsioConnection, unsupported_version_connect) SerializedMessage message(announcement); - auto validator = [](const ParticipantAnnouncementReply& reply) - { + auto validator = [](const ParticipantAnnouncementReply& reply) { return reply.status == ParticipantAnnouncementReply::Status::Failed; }; EXPECT_CALL(_from, SendSilKitMsg(AnnouncementReplyMatcher(validator))).Times(1); @@ -229,9 +227,7 @@ TEST_F(Test_VAsioConnection, unsupported_version_reply_from_registry_should_thro _from._peerInfo.participantId = REGISTRY_PARTICIPANT_ID; SerializedMessage message(reply); - EXPECT_THROW( - _connection.OnSocketData(&_from, std::move(message)), - SilKit::ProtocolError); + EXPECT_THROW(_connection.OnSocketData(&_from, std::move(message)), SilKit::ProtocolError); } TEST_F(Test_VAsioConnection, supported_version_reply_from_registry_must_not_throw) @@ -242,9 +238,7 @@ TEST_F(Test_VAsioConnection, supported_version_reply_from_registry_must_not_thro _from._peerInfo.participantId = REGISTRY_PARTICIPANT_ID; SerializedMessage message(reply); - EXPECT_NO_THROW( - _connection.OnSocketData(&_from, std::move(message)) - ); + EXPECT_NO_THROW(_connection.OnSocketData(&_from, std::move(message))); } TEST_F(Test_VAsioConnection, current_version_connect) @@ -254,8 +248,7 @@ TEST_F(Test_VAsioConnection, current_version_connect) SerializedMessage message(announcement); - auto validator = [](const ParticipantAnnouncementReply& reply) - { + auto validator = [](const ParticipantAnnouncementReply& reply) { return reply.status == ParticipantAnnouncementReply::Status::Success; }; EXPECT_CALL(_from, SendSilKitMsg(AnnouncementReplyMatcher(validator))).Times(1); @@ -271,10 +264,10 @@ TEST_F(Test_VAsioConnection, current_version_connect) // the different version used for transmission, this is a work in progress. TEST_F(Test_VAsioConnection, DISABLED_versioned_send_testmessage) { - // We send a 'version1', but expect to receive a 'version2' + // We send a 'version1', but expect to receive a 'version2' Tests::Version1::TestMessage message; message.integer = 1234; - message.str ="1234"; + message.str = "1234"; // Setup subscriptions for transmisison using MessageTrait = SilKit::Core::SilKitMsgTraits; @@ -293,11 +286,10 @@ TEST_F(Test_VAsioConnection, DISABLED_versioned_send_testmessage) // Create a receiver with index 0 and a different TestMessage _version_ MockSilKitMessageReceiver mockReceiver; - RegisterSilKitMsgReceiver(&mockReceiver); + RegisterSilKitMsgReceiver(&mockReceiver); // the actual message - auto buffer = SerializedMessage(message, _from.GetServiceDescriptor().to_endpointAddress(), - subscriber.receiverIdx); + auto buffer = SerializedMessage(message, _from.GetServiceDescriptor().to_endpointAddress(), subscriber.receiverIdx); _connection.OnSocketData(&_from, std::move(buffer)); } diff --git a/SilKit/source/core/vasio/TransformAcceptorUris.cpp b/SilKit/source/core/vasio/TransformAcceptorUris.cpp index 1b2bc22f2..274ace3ce 100644 --- a/SilKit/source/core/vasio/TransformAcceptorUris.cpp +++ b/SilKit/source/core/vasio/TransformAcceptorUris.cpp @@ -124,7 +124,8 @@ auto TransformAcceptorUris(SilKit::Services::Logging::ILogger* logger, IVAsioPee if (dst.Type() != Uri::UriType::Local && dst.Type() != Uri::UriType::Tcp) { - throw SilKitError{"SIL Kit Registry: TransformAcceptorUris: Local address of audience peer has invalid UriType"}; + throw SilKitError{ + "SIL Kit Registry: TransformAcceptorUris: Local address of audience peer has invalid UriType"}; } // URI transformation diff --git a/SilKit/source/core/vasio/VAsioCapabilities.hpp b/SilKit/source/core/vasio/VAsioCapabilities.hpp index e8d320e21..a04f6f4f0 100644 --- a/SilKit/source/core/vasio/VAsioCapabilities.hpp +++ b/SilKit/source/core/vasio/VAsioCapabilities.hpp @@ -30,19 +30,20 @@ namespace Core { // Protocol Capability literals struct CapabilityLiteral { - std::string _value; - explicit CapabilityLiteral(const char* capabilityString) - : _value{ capabilityString } - {} - - operator const char* () const - { - return _value.c_str(); - } - operator const std::string& () const - { - return _value; - } + std::string _value; + explicit CapabilityLiteral(const char* capabilityString) + : _value{capabilityString} + { + } + + operator const char*() const + { + return _value.c_str(); + } + operator const std::string&() const + { + return _value; + } }; diff --git a/SilKit/source/core/vasio/VAsioConnection.cpp b/SilKit/source/core/vasio/VAsioConnection.cpp old mode 100755 new mode 100644 index a19f48838..1f7a05a1d --- a/SilKit/source/core/vasio/VAsioConnection.cpp +++ b/SilKit/source/core/vasio/VAsioConnection.cpp @@ -49,9 +49,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_VAsioConnection -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif @@ -100,26 +100,19 @@ auto makeLocalEndpoint(const std::string& participantName, const SilKit::Core::P asio::local::stream_protocol::endpoint result; // Ensure the participantName is in a useful encoding const auto safe_name = printableName(participantName); - const auto bounded_name = safe_name.substr(0, - std::min(safe_name.size(), 10)); + const auto bounded_name = safe_name.substr(0, std::min(safe_name.size(), 10)); // We hash the participant name, ID and the current working directory // as part of the temporary file name, so we can have multiple local simulations // started from different working directories, but a shared temporary directory. // NB keep the variable part as short as possible. - const auto unique_id = std::hash{}(participantName - + std::to_string(id) - + uniqueValue - + fs::current_path().string() - ); + const auto unique_id = + std::hash{}(participantName + std::to_string(id) + uniqueValue + fs::current_path().string()); std::stringstream path; - path << fs::temp_directory_path().string() - << fs::path::preferred_separator - << bounded_name - << std::hex << unique_id - << ".silkit"; + path << fs::temp_directory_path().string() << fs::path::preferred_separator << bounded_name << std::hex << unique_id + << ".silkit"; result.path(path.str()); return result; @@ -129,7 +122,7 @@ auto makeLocalEndpoint(const std::string& participantName, const SilKit::Core::P auto fromAsioEndpoint(const asio::local::stream_protocol::endpoint& ep) { std::stringstream uri; - const std::string localPrefix{ "local://" }; + const std::string localPrefix{"local://"}; uri << localPrefix << ep.path(); return SilKit::Core::Uri::Parse(uri.str()); } @@ -269,12 +262,9 @@ namespace Core { namespace tt = Util::tuple_tools; -VAsioConnection::VAsioConnection( - IParticipantInternal* participant, - SilKit::Config::ParticipantConfiguration config, - std::string participantName, ParticipantId participantId, - Services::Orchestration::ITimeProvider* timeProvider, - ProtocolVersion version) +VAsioConnection::VAsioConnection(IParticipantInternal* participant, SilKit::Config::ParticipantConfiguration config, + std::string participantName, ParticipantId participantId, + Services::Orchestration::ITimeProvider* timeProvider, ProtocolVersion version) : _config{std::move(config)} , _participantName{std::move(participantName)} , _participantId{participantId} @@ -341,7 +331,7 @@ auto VAsioConnection::GetLogger() -> SilKit::Services::Logging::ILogger* return _logger; } -auto VAsioConnection::PrepareAcceptorEndpointUris(const std::string & connectUri) -> std::vector +auto VAsioConnection::PrepareAcceptorEndpointUris(const std::string& connectUri) -> std::vector { auto acceptorEndpointUris = _config.middleware.acceptorUris; @@ -360,7 +350,7 @@ auto VAsioConnection::PrepareAcceptorEndpointUris(const std::string & connectUri return acceptorEndpointUris; } -void VAsioConnection::OpenTcpAcceptors(const std::vector & acceptorEndpointUris) +void VAsioConnection::OpenTcpAcceptors(const std::vector& acceptorEndpointUris) { for (const auto& uriString : acceptorEndpointUris) { @@ -399,8 +389,7 @@ void VAsioConnection::OpenTcpAcceptors(const std::vector & acceptor } else { - SilKit::Services::Logging::Warn( - _logger, "OpenTcpAcceptors: Unused acceptor endpoint URI: {}", uriString); + SilKit::Services::Logging::Warn(_logger, "OpenTcpAcceptors: Unused acceptor endpoint URI: {}", uriString); } } } @@ -627,11 +616,9 @@ void VAsioConnection::LogAndPrintNetworkIncompatibility(const RegistryMsgHeader& const std::string& otherParticipantName) { const auto errorMsg = fmt::format("Network incompatibility between this version range ({})" - " and connecting participant '{}' ({})", - MapVersionToRelease(MakeRegistryMsgHeader(_version)), - otherParticipantName, - MapVersionToRelease(other) - ); + " and connecting participant '{}' ({})", + MapVersionToRelease(MakeRegistryMsgHeader(_version)), otherParticipantName, + MapVersionToRelease(other)); _logger->Critical(errorMsg); std::cerr << "ERROR: " << errorMsg << std::endl; } @@ -660,7 +647,8 @@ void VAsioConnection::SendParticipantAnnouncement(IVAsioPeer* peer) announcement.peerInfo = std::move(myPeerInfo); announcement.simulationName = _simulationName; - Services::Logging::Debug(_logger, "Sending participant announcement to '{}' ('{}')", peer->GetInfo().participantName, peer->GetSimulationName()); + Services::Logging::Debug(_logger, "Sending participant announcement to '{}' ('{}')", + peer->GetInfo().participantName, peer->GetSimulationName()); peer->SendSilKitMsg(SerializedMessage{announcement}); } @@ -755,9 +743,7 @@ void VAsioConnection::SendParticipantAnnouncementReply(IVAsioPeer* peer) reply.status = ParticipantAnnouncementReply::Status::Success; // fill in the service descriptors we want to subscribe to std::transform(_vasioReceivers.begin(), _vasioReceivers.end(), std::back_inserter(reply.subscribers), - [](const auto& subscriber) { - return subscriber->GetDescriptor(); - }); + [](const auto& subscriber) { return subscriber->GetDescriptor(); }); Services::Logging::Debug(_logger, "Sending ParticipantAnnouncementReply to '{}' ('{}') with protocol version {}", peer->GetInfo().participantName, peer->GetSimulationName(), @@ -929,7 +915,8 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest(IVAsioPeer* peer, S } } -void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Registry(IVAsioPeer* peer, RemoteParticipantConnectRequest msg) +void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Registry(IVAsioPeer* peer, + RemoteParticipantConnectRequest msg) { SILKIT_TRACE_METHOD_(_logger, "({} {} {})", msg.requestOrigin.participantName, msg.requestTarget.participantName, static_cast(msg.status)); @@ -979,7 +966,8 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Registry(IVAsioPeer destination->SendSilKitMsg(buffer); } -void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioPeer* peer, RemoteParticipantConnectRequest msg) +void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioPeer* peer, + RemoteParticipantConnectRequest msg) { SILKIT_TRACE_METHOD_(_logger, "({} {} {})", msg.requestOrigin.participantName, msg.requestTarget.participantName, static_cast(msg.status)); @@ -992,8 +980,7 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioP if (msg.status == RemoteParticipantConnectRequest::REQUEST) { SilKit::Services::Logging::Debug( - _logger, - "Received RemoteParticipantConnectRequest::REQUEST (request origin {}, request target {})", + _logger, "Received RemoteParticipantConnectRequest::REQUEST (request origin {}, request target {})", msg.requestOrigin.participantName, msg.requestTarget.participantName); // XXX check if already connected to origin @@ -1035,8 +1022,7 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioP if (msg.status == RemoteParticipantConnectRequest::CONNECTING) { SilKit::Services::Logging::Debug( - _logger, - "Received RemoteParticipantConnectRequest::CONNECTING (request origin {}, request target {})", + _logger, "Received RemoteParticipantConnectRequest::CONNECTING (request origin {}, request target {})", msg.requestOrigin.participantName, msg.requestTarget.participantName); // The remote participant informs us that it received the REQUEST and is starting to connect to us. @@ -1087,13 +1073,15 @@ void VAsioConnection::HandleConnectedPeer(IVAsioPeer* peer) } -void VAsioConnection::AssociateParticipantNameAndPeer(const std::string& simulationName, const std::string& participantName, IVAsioPeer* peer) +void VAsioConnection::AssociateParticipantNameAndPeer(const std::string& simulationName, + const std::string& participantName, IVAsioPeer* peer) { std::lock_guard lock{_mutex}; _participantNameToPeer[simulationName].insert({participantName, peer}); } -auto VAsioConnection::FindPeerByName(const std::string& simulationName, const std::string& participantName) const -> IVAsioPeer* +auto VAsioConnection::FindPeerByName(const std::string& simulationName, + const std::string& participantName) const -> IVAsioPeer* { std::lock_guard lock{_mutex}; @@ -1167,8 +1155,8 @@ void VAsioConnection::AcceptLocalConnections(const std::string& uniqueId) } } -auto VAsioConnection::AcceptTcpConnectionsOn(const std::string& hostName, uint16_t port) - -> std::pair +auto VAsioConnection::AcceptTcpConnectionsOn(const std::string& hostName, + uint16_t port) -> std::pair { // Default to TCP IPv4 catchallIp asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port); @@ -1227,7 +1215,7 @@ void VAsioConnection::AddPeer(std::unique_ptr newPeer) std::unique_lock lock{_peersLock}; - auto * const proxyPeer = dynamic_cast(newPeer.get()); + auto* const proxyPeer = dynamic_cast(newPeer.get()); if (proxyPeer != nullptr) { _peerToProxyPeers[proxyPeer->GetPeer()].insert(proxyPeer); @@ -1238,9 +1226,8 @@ void VAsioConnection::AddPeer(std::unique_ptr newPeer) void VAsioConnection::RegisterPeerShutdownCallback(std::function callback) { - ExecuteOnIoThread([this, callback{std::move(callback)}]{ - _peerShutdownCallbacks.emplace_back(std::move(callback)); - }); + ExecuteOnIoThread( + [this, callback{std::move(callback)}] { _peerShutdownCallbacks.emplace_back(std::move(callback)); }); } void VAsioConnection::OnPeerShutdown(IVAsioPeer* peer) @@ -1338,9 +1325,8 @@ void VAsioConnection::RemovePeerFromConnection(IVAsioPeer* peer) } } - auto it{std::find_if(_peers.begin(), _peers.end(), [needle = peer](const auto& hay) { - return hay.get() == needle; - })}; + auto it{ + std::find_if(_peers.begin(), _peers.end(), [needle = peer](const auto& hay) { return hay.get() == needle; })}; if (it != _peers.end()) { @@ -1466,14 +1452,13 @@ void VAsioConnection::ReceiveSubscriptionAnnouncement(IVAsioPeer* from, Serializ VersionT subscriptionVersion{0}; SilKitMessageTypes supportedMessageTypes{}; - tt::for_each(supportedMessageTypes, - [&subscriptionVersion, &typeName, remoteVersion](auto&& myType) { + tt::for_each(supportedMessageTypes, [&subscriptionVersion, &typeName, remoteVersion](auto&& myType) { using MsgT = std::decay_t; if (typeName == SilKitMsgTraits::SerdesName()) { - if(SilKitMsgTraits::Version() <= remoteVersion) + if (SilKitMsgTraits::Version() <= remoteVersion) { - subscriptionVersion = SilKitMsgTraits::Version(); + subscriptionVersion = SilKitMsgTraits::Version(); } } }); @@ -1488,9 +1473,9 @@ void VAsioConnection::ReceiveSubscriptionAnnouncement(IVAsioPeer* from, Serializ if (myMessageVersion == 0) { Services::Logging::Warn(_logger, - "Received SubscriptionAnnouncement from {} for message type {}" - " for an unknown subscriber version {}", - from->GetInfo().participantName, subscriber.msgTypeName, subscriber.version); + "Received SubscriptionAnnouncement from {} for message type {}" + " for an unknown subscriber version {}", + from->GetInfo().participantName, subscriber.msgTypeName, subscriber.version); } else { @@ -1500,9 +1485,7 @@ void VAsioConnection::ReceiveSubscriptionAnnouncement(IVAsioPeer* from, Serializ // send acknowledge SubscriptionAcknowledge ack; ack.subscriber = std::move(subscriber); - ack.status = wasAdded - ? SubscriptionAcknowledge::Status::Success - : SubscriptionAcknowledge::Status::Failed; + ack.status = wasAdded ? SubscriptionAcknowledge::Status::Success : SubscriptionAcknowledge::Status::Failed; from->SendSilKitMsg(SerializedMessage{from->GetProtocolVersion(), ack}); } @@ -1513,10 +1496,8 @@ void VAsioConnection::ReceiveSubscriptionAcknowledge(IVAsioPeer* from, Serialize if (ack.status != SubscriptionAcknowledge::Status::Success) { - Services::Logging::Error(_logger, "Failed to subscribe [{}] {} from {}" - , ack.subscriber.networkName - , ack.subscriber.msgTypeName - , from->GetInfo().participantName); + Services::Logging::Error(_logger, "Failed to subscribe [{}] {} from {}", ack.subscriber.networkName, + ack.subscriber.msgTypeName, from->GetInfo().participantName); } // We remove the pending subscription in any case as there will not follow a new, successful acknowledge from that peer @@ -1581,8 +1562,9 @@ bool VAsioConnection::TryAddRemoteSubscriber(IVAsioPeer* from, const VAsioMsgSub } else { - Services::Logging::Warn(_logger, "Participant '{}' could not be registered as receiver for messages of type '{}' on link '{}'", - from->GetInfo().participantName, subscriber.msgTypeName, subscriber.networkName); + Services::Logging::Warn( + _logger, "Participant '{}' could not be registered as receiver for messages of type '{}' on link '{}'", + from->GetInfo().participantName, subscriber.msgTypeName, subscriber.networkName); } return wasAdded; @@ -1590,7 +1572,7 @@ bool VAsioConnection::TryAddRemoteSubscriber(IVAsioPeer* from, const VAsioMsgSub void VAsioConnection::ReceiveRawSilKitMessage(IVAsioPeer* from, SerializedMessage&& buffer) { - auto receiverIdx = static_cast(buffer.GetRemoteIndex());//ExtractEndpointId(buffer); + auto receiverIdx = static_cast(buffer.GetRemoteIndex()); //ExtractEndpointId(buffer); if (receiverIdx >= _vasioReceivers.size()) { Services::Logging::Warn(_logger, "Ignoring RawSilKitMessage for unknown receiverIdx={}", receiverIdx); @@ -1663,11 +1645,11 @@ void VAsioConnection::ReceiveRegistryMessage(IVAsioPeer* from, SerializedMessage } } -void VAsioConnection::SetAsyncSubscriptionsCompletionHandler(std::function handler) +void VAsioConnection::AddAsyncSubscriptionsCompletionHandler(std::function handler) { if (_hasPendingAsyncSubscriptions) { - _asyncSubscriptionsCompletionHandler = std::move(handler); + _asyncSubscriptionsCompletionHandlers.Add(std::move(handler)); } else { @@ -1675,8 +1657,8 @@ void VAsioConnection::SetAsyncSubscriptionsCompletionHandler(std::function size_t +auto VAsioConnection::GetNumberOfRemoteReceivers(const IServiceEndpoint* service, + const std::string& msgTypeName) -> size_t { auto networkName = service->GetServiceDescriptor().GetNetworkName(); @@ -1704,8 +1686,7 @@ auto VAsioConnection::GetNumberOfRemoteReceivers(const IServiceEndpoint* service } auto VAsioConnection::GetParticipantNamesOfRemoteReceivers(const IServiceEndpoint* service, - const std::string& msgTypeName) - -> std::vector + const std::string& msgTypeName) -> std::vector { auto networkName = service->GetServiceDescriptor().GetNetworkName(); @@ -1739,11 +1720,8 @@ void VAsioConnection::SyncSubscriptionsCompleted() void VAsioConnection::AsyncSubscriptionsCompleted() { - if (_asyncSubscriptionsCompletionHandler) - { - _asyncSubscriptionsCompletionHandler(); - _asyncSubscriptionsCompletionHandler = nullptr; - } + _asyncSubscriptionsCompletionHandlers.InvokeAll(); + _asyncSubscriptionsCompletionHandlers.Clear(); _hasPendingAsyncSubscriptions = false; } @@ -1831,7 +1809,8 @@ void VAsioConnection::OnAsyncAcceptSuccess(IAcceptor& acceptor, std::unique_ptr< { SILKIT_TRACE_METHOD_(_logger, "({})", static_cast(&acceptor)); - Services::Logging::Debug(_logger, "New connection from [local={}, remote={}]", stream->GetLocalEndpoint(), stream->GetRemoteEndpoint()); + Services::Logging::Debug(_logger, "New connection from [local={}, remote={}]", stream->GetLocalEndpoint(), + stream->GetRemoteEndpoint()); try { @@ -1855,9 +1834,8 @@ void VAsioConnection::OnAsyncAcceptFailure(IAcceptor& acceptor) { std::unique_lock lock{_acceptorsMutex}; - auto it{std::find_if(_acceptors.begin(), _acceptors.end(), [needle = &acceptor](const auto& hay) { - return hay.get() == needle; - })}; + auto it{std::find_if(_acceptors.begin(), _acceptors.end(), + [needle = &acceptor](const auto& hay) { return hay.get() == needle; })}; if (it != _acceptors.end()) { @@ -1955,7 +1933,7 @@ bool VAsioConnection::TryRemoteConnectRequest(VAsioPeerInfo const& peerInfo) SILKIT_TRACE_METHOD_(_logger, "({})", peerInfo.participantName); SilKit::Services::Logging::Debug(_logger, "Trying to request remote connection from {} via the registry", - peerInfo.participantName); + peerInfo.participantName); if (!_capabilities.HasCapability(Capabilities::RequestParticipantConnection)) { @@ -2007,7 +1985,7 @@ bool VAsioConnection::TryProxyConnect(VAsioPeerInfo const& peerInfo) SILKIT_TRACE_METHOD_(_logger, "({})", peerInfo.participantName); SilKit::Services::Logging::Debug(_logger, "Trying to use the registry as a proxy to communicate with {}", - peerInfo.participantName); + peerInfo.participantName); // NB: Cannot check the capabilities of the registry, since we do not receive the PeerInfo from the // registry over the network, but build it ourselves in VAsioConnection::JoinSimulation. diff --git a/SilKit/source/core/vasio/VAsioConnection.hpp b/SilKit/source/core/vasio/VAsioConnection.hpp old mode 100755 new mode 100644 index 03b949302..3c1d5c89e --- a/SilKit/source/core/vasio/VAsioConnection.hpp +++ b/SilKit/source/core/vasio/VAsioConnection.hpp @@ -89,8 +89,9 @@ class VAsioConnection // Constructors and Destructor VAsioConnection(const VAsioConnection&) = delete; VAsioConnection(VAsioConnection&&) = delete; - VAsioConnection(IParticipantInternal* participant, SilKit::Config::ParticipantConfiguration config, std::string participantName, - ParticipantId participantId, Services::Orchestration::ITimeProvider* timeProvider, + VAsioConnection(IParticipantInternal* participant, SilKit::Config::ParticipantConfiguration config, + std::string participantName, ParticipantId participantId, + Services::Orchestration::ITimeProvider* timeProvider, ProtocolVersion version = CurrentProtocolVersion()); ~VAsioConnection() override; @@ -131,15 +132,15 @@ class VAsioConnection _hasPendingAsyncSubscriptions = true; } - _ioContext->Post([this, service]() { - this->RegisterSilKitServiceImpl(service); - }); + _ioContext->Post([this, service]() { this->RegisterSilKitServiceImpl(service); }); if (!SilKitServiceTraits::UseAsyncRegistration()) { - Trace(_logger, "SIL Kit waiting for subscription acknowledges for SilKitService {}.", typeid(*service).name()); + Trace(_logger, "SIL Kit waiting for subscription acknowledges for SilKitService {}.", + typeid(*service).name()); allAcked.wait(); - Trace(_logger, "SIL Kit received all subscription acknowledges for SilKitService {}.", typeid(*service).name()); + Trace(_logger, "SIL Kit received all subscription acknowledges for SilKitService {}.", + typeid(*service).name()); } } @@ -157,16 +158,17 @@ class VAsioConnection }); } - template + template void SendMsg(const IServiceEndpoint* from, SilKitMessageT&& msg) { ExecuteOnIoThread(&VAsioConnection::SendMsgImpl, from, std::forward(msg)); } - template + template void SendMsg(const IServiceEndpoint* from, const std::string& targetParticipantName, SilKitMessageT&& msg) { - ExecuteOnIoThread(&VAsioConnection::SendMsgToTargetImpl, from, targetParticipantName, std::forward(msg)); + ExecuteOnIoThread(&VAsioConnection::SendMsgToTargetImpl, from, targetParticipantName, + std::forward(msg)); } inline void OnAllMessagesDelivered(const std::function& callback) @@ -189,9 +191,9 @@ class VAsioConnection void RegisterMessageReceiver(std::function callback); // Prepare Acceptor Sockets (Local Domain and TCP) - auto PrepareAcceptorEndpointUris(const std::string &connectUri) -> std::vector; - void OpenTcpAcceptors(const std::vector & acceptorEndpointUris); - void OpenLocalAcceptors(const std::vector & acceptorEndpointUris); + auto PrepareAcceptorEndpointUris(const std::string& connectUri) -> std::vector; + void OpenTcpAcceptors(const std::vector& acceptorEndpointUris); + void OpenLocalAcceptors(const std::vector& acceptorEndpointUris); // Listening Sockets (acceptors) void AcceptLocalConnections(const std::string& uniqueId); @@ -204,7 +206,7 @@ class VAsioConnection void NotifyShutdown(); // Register handlers for completion of async service creation - void SetAsyncSubscriptionsCompletionHandler(std::function handler); + void AddAsyncSubscriptionsCompletionHandler(std::function handler); size_t GetNumberOfConnectedParticipants() { @@ -212,8 +214,8 @@ class VAsioConnection }; auto GetNumberOfRemoteReceivers(const IServiceEndpoint* service, const std::string& msgTypeName) -> size_t; - auto GetParticipantNamesOfRemoteReceivers(const IServiceEndpoint* service, const std::string& msgTypeName) - -> std::vector; + auto GetParticipantNamesOfRemoteReceivers(const IServiceEndpoint* service, + const std::string& msgTypeName) -> std::vector; bool ParticipantHasCapability(const std::string& participantName, const std::string& capability) const; @@ -231,50 +233,26 @@ class VAsioConnection using ParticipantAnnouncementReceiver = std::function; using SilKitMessageTypes = std::tuple< - Services::Logging::LogMsg, - Services::Orchestration::NextSimTask, - Services::Orchestration::SystemCommand, - Services::Orchestration::ParticipantStatus, - Services::Orchestration::WorkflowConfiguration, - Services::PubSub::WireDataMessageEvent, - Services::Rpc::FunctionCall, - Services::Rpc::FunctionCallResponse, - Services::Can::WireCanFrameEvent, - Services::Can::CanFrameTransmitEvent, - Services::Can::CanControllerStatus, - Services::Can::CanConfigureBaudrate, - Services::Can::CanSetControllerMode, - Services::Ethernet::WireEthernetFrameEvent, - Services::Ethernet::EthernetFrameTransmitEvent, - Services::Ethernet::EthernetStatus, - Services::Ethernet::EthernetSetMode, - Services::Lin::LinSendFrameRequest, - Services::Lin::LinSendFrameHeaderRequest, - Services::Lin::LinTransmission, - Services::Lin::LinWakeupPulse, - Services::Lin::WireLinControllerConfig, - Services::Lin::LinControllerStatusUpdate, - Services::Lin::LinFrameResponseUpdate, - Services::Flexray::WireFlexrayFrameEvent, - Services::Flexray::WireFlexrayFrameTransmitEvent, - Services::Flexray::FlexraySymbolEvent, - Services::Flexray::FlexraySymbolTransmitEvent, - Services::Flexray::FlexrayCycleStartEvent, - Services::Flexray::FlexrayHostCommand, - Services::Flexray::FlexrayControllerConfig, - Services::Flexray::FlexrayTxBufferConfigUpdate, - Services::Flexray::WireFlexrayTxBufferUpdate, - Services::Flexray::FlexrayPocStatusEvent, - Core::Discovery::ParticipantDiscoveryEvent, - Core::Discovery::ServiceDiscoveryEvent, - Core::RequestReply::RequestReplyCall, + Services::Logging::LogMsg, Services::Orchestration::NextSimTask, Services::Orchestration::SystemCommand, + Services::Orchestration::ParticipantStatus, Services::Orchestration::WorkflowConfiguration, + Services::PubSub::WireDataMessageEvent, Services::Rpc::FunctionCall, Services::Rpc::FunctionCallResponse, + Services::Can::WireCanFrameEvent, Services::Can::CanFrameTransmitEvent, Services::Can::CanControllerStatus, + Services::Can::CanConfigureBaudrate, Services::Can::CanSetControllerMode, + Services::Ethernet::WireEthernetFrameEvent, Services::Ethernet::EthernetFrameTransmitEvent, + Services::Ethernet::EthernetStatus, Services::Ethernet::EthernetSetMode, Services::Lin::LinSendFrameRequest, + Services::Lin::LinSendFrameHeaderRequest, Services::Lin::LinTransmission, Services::Lin::LinWakeupPulse, + Services::Lin::WireLinControllerConfig, Services::Lin::LinControllerStatusUpdate, + Services::Lin::LinFrameResponseUpdate, Services::Flexray::WireFlexrayFrameEvent, + Services::Flexray::WireFlexrayFrameTransmitEvent, Services::Flexray::FlexraySymbolEvent, + Services::Flexray::FlexraySymbolTransmitEvent, Services::Flexray::FlexrayCycleStartEvent, + Services::Flexray::FlexrayHostCommand, Services::Flexray::FlexrayControllerConfig, + Services::Flexray::FlexrayTxBufferConfigUpdate, Services::Flexray::WireFlexrayTxBufferUpdate, + Services::Flexray::FlexrayPocStatusEvent, Core::Discovery::ParticipantDiscoveryEvent, + Core::Discovery::ServiceDiscoveryEvent, Core::RequestReply::RequestReplyCall, Core::RequestReply::RequestReplyCallReturn, // Private testing data types - Core::Tests::Version1::TestMessage, - Core::Tests::Version2::TestMessage, - Core::Tests::TestFrameEvent - >; + Core::Tests::Version1::TestMessage, Core::Tests::Version2::TestMessage, Core::Tests::TestFrameEvent>; private: // ---------------------------------------- @@ -303,7 +281,8 @@ class VAsioConnection void LogAndPrintNetworkIncompatibility(const RegistryMsgHeader& other, const std::string& otherParticipantName); - void AssociateParticipantNameAndPeer(const std::string& simulationName, const std::string& participantName, IVAsioPeer* peer); + void AssociateParticipantNameAndPeer(const std::string& simulationName, const std::string& participantName, + IVAsioPeer* peer); auto FindPeerByName(const std::string& simulationName, const std::string& participantName) const -> IVAsioPeer*; // Subscriptions completed Helper @@ -317,7 +296,7 @@ class VAsioConnection void RemovePeerFromLinks(IVAsioPeer* peer); void RemovePeerFromConnection(IVAsioPeer* peer); - template + template auto GetLinkByName(const std::string& networkName) -> std::shared_ptr> { std::unique_lock lock{_linksMx}; @@ -330,7 +309,7 @@ class VAsioConnection return link; } - template + template void RegisterSilKitMsgReceiver(IMessageReceiver* receiver) { SILKIT_ASSERT(_logger); @@ -352,7 +331,8 @@ class VAsioConnection subscriptionInfo.msgTypeName = msgSerdesName; subscriptionInfo.version = SilKitMsgTraits::Version(); - std::unique_ptr rawReceiver = std::make_unique>(subscriptionInfo, link, _logger); + std::unique_ptr rawReceiver = + std::make_unique>(subscriptionInfo, link, _logger); auto* serviceEndpointPtr = dynamic_cast(rawReceiver.get()); ServiceDescriptor tmpServiceDescriptor(GetServiceDescriptor(receiver)); tmpServiceDescriptor.SetParticipantNameAndComputeId(_participantName); @@ -382,7 +362,7 @@ class VAsioConnection } } - template + template void RegisterSilKitMsgSender(const std::string& networkName) { auto link = GetLinkByName(networkName); @@ -390,26 +370,21 @@ class VAsioConnection serviceLinkMap[networkName] = link; } - template + template inline void RegisterSilKitServiceImpl(SilKitServiceT* service) { typename SilKitServiceT::SilKitReceiveMessagesTypes receiveMessageTypes{}; typename SilKitServiceT::SilKitSendMessagesTypes sendMessageTypes{}; - Util::tuple_tools::for_each(receiveMessageTypes, [this, service](auto&& message) - { + Util::tuple_tools::for_each(receiveMessageTypes, [this, service](auto&& message) { using SilKitMessageT = std::decay_t; this->RegisterSilKitMsgReceiver(service); - } - ); + }); - Util::tuple_tools::for_each(sendMessageTypes, - [this, service](auto&& message) - { + Util::tuple_tools::for_each(sendMessageTypes, [this, service](auto&& message) { using SilKitMessageT = std::decay_t; this->RegisterSilKitMsgSender(GetServiceDescriptor(service).GetNetworkName()); - } - ); + }); // We could have registered a receiver that only uses already acknowledged senders, thus no new handshake is // triggered. In that case, the pending acks might be already empty and the subscription is completed. @@ -437,7 +412,7 @@ class VAsioConnection auto& linkMap = std::get>>(_serviceToLinkMap); if (linkMap.count(key) < 1) { - throw SilKitError{ "SendMsgImpl: sending on empty link for " + key }; + throw SilKitError{"SendMsgImpl: sending on empty link for " + key}; } auto&& link = linkMap[key]; link->DistributeLocalSilKitMessage(from, std::forward(msg)); @@ -445,7 +420,7 @@ class VAsioConnection template void SendMsgToTargetImpl(const IServiceEndpoint* from, const std::string& targetParticipantName, - SilKitMessageT&& msg) + SilKitMessageT&& msg) { const auto& key = from->GetServiceDescriptor().GetNetworkName(); @@ -564,7 +539,7 @@ class VAsioConnection // Subscriptions for internal services that use async registration std::vector _pendingAsyncSubscriptionAcknowledges; - std::function _asyncSubscriptionsCompletionHandler; + Util::SynchronizedHandlers> _asyncSubscriptionsCompletionHandlers; std::atomic _hasPendingAsyncSubscriptions{false}; // The worker thread should be the last members in this class. This ensures @@ -575,10 +550,11 @@ class VAsioConnection std::atomic_bool _isShuttingDown{false}; // Hold mapping from simulationName to mapping from participantName to peer - std::unordered_map> _participantNameToPeer; + std::unordered_map> _participantNameToPeer; // Hold mapping from proxy source to all proxy destinations (used by registry for shutdown information) - std::unordered_map>> _proxySourceToDestinations; + std::unordered_map>> + _proxySourceToDestinations; // Hold mapping from proxied peer to all proxy peers being served via the key. std::unordered_map> _peerToProxyPeers; diff --git a/SilKit/source/core/vasio/VAsioConstants.hpp b/SilKit/source/core/vasio/VAsioConstants.hpp index 5399f91cf..1ceaae5e2 100644 --- a/SilKit/source/core/vasio/VAsioConstants.hpp +++ b/SilKit/source/core/vasio/VAsioConstants.hpp @@ -9,7 +9,7 @@ namespace VSilKit { constexpr const SilKit::Core::ParticipantId REGISTRY_PARTICIPANT_ID{0}; -constexpr const char * REGISTRY_PARTICIPANT_NAME{"SilKitRegistry"}; +constexpr const char* REGISTRY_PARTICIPANT_NAME{"SilKitRegistry"}; } // namespace VSilKit diff --git a/SilKit/source/core/vasio/VAsioDatatypes.hpp b/SilKit/source/core/vasio/VAsioDatatypes.hpp old mode 100755 new mode 100644 index 5becb798f..13d1eb205 --- a/SilKit/source/core/vasio/VAsioDatatypes.hpp +++ b/SilKit/source/core/vasio/VAsioDatatypes.hpp @@ -61,7 +61,8 @@ struct VAsioMsgSubscriber struct SubscriptionAcknowledge { - enum class Status : uint8_t { + enum class Status : uint8_t + { Failed = 0, Success = 1 }; @@ -79,7 +80,8 @@ struct ParticipantAnnouncement struct ParticipantAnnouncementReply { RegistryMsgHeader remoteHeader; - enum class Status : uint8_t { + enum class Status : uint8_t + { Failed = 0, Success = 1 }; @@ -150,26 +152,18 @@ struct ProxyMessage // ================================================================================ inline bool operator!=(const RegistryMsgHeader& lhs, const RegistryMsgHeader& rhs) { - return lhs.preamble != rhs.preamble - || lhs.versionHigh != rhs.versionHigh - || lhs.versionLow != rhs.versionLow - ; + return lhs.preamble != rhs.preamble || lhs.versionHigh != rhs.versionHigh || lhs.versionLow != rhs.versionLow; } inline bool operator==(const RegistryMsgHeader& lhs, const RegistryMsgHeader& rhs) { - return lhs.preamble == rhs.preamble - && lhs.versionHigh == rhs.versionHigh - && lhs.versionLow == rhs.versionLow - ; + return lhs.preamble == rhs.preamble && lhs.versionHigh == rhs.versionHigh && lhs.versionLow == rhs.versionLow; } inline bool operator==(const VAsioMsgSubscriber& lhs, const VAsioMsgSubscriber& rhs) { - return lhs.receiverIdx == rhs.receiverIdx - && lhs.networkName == rhs.networkName - && lhs.msgTypeName == rhs.msgTypeName - ; + return lhs.receiverIdx == rhs.receiverIdx && lhs.networkName == rhs.networkName + && lhs.msgTypeName == rhs.msgTypeName; } } // namespace Core diff --git a/SilKit/source/core/vasio/VAsioMsgKind.hpp b/SilKit/source/core/vasio/VAsioMsgKind.hpp index 441c45266..2958cd8c6 100644 --- a/SilKit/source/core/vasio/VAsioMsgKind.hpp +++ b/SilKit/source/core/vasio/VAsioMsgKind.hpp @@ -25,7 +25,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SilKit { namespace Core { -enum class VAsioMsgKind: uint8_t +enum class VAsioMsgKind : uint8_t { Invalid = 0, SubscriptionAnnouncement = 1, diff --git a/SilKit/source/core/vasio/VAsioPeer.cpp b/SilKit/source/core/vasio/VAsioPeer.cpp index 372648105..ea85c2ad2 100644 --- a/SilKit/source/core/vasio/VAsioPeer.cpp +++ b/SilKit/source/core/vasio/VAsioPeer.cpp @@ -35,9 +35,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_VAsioPeer -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif @@ -119,9 +119,7 @@ void VAsioPeer::SendSilKitMsg(SerializedMessage buffer) lock.unlock(); - _ioContext->Dispatch([this] { - StartAsyncWrite(); - }); + _ioContext->Dispatch([this] { StartAsyncWrite(); }); } } @@ -153,7 +151,8 @@ void VAsioPeer::WriteSomeAsync() void VAsioPeer::Subscribe(VAsioMsgSubscriber subscriber) { - Services::Logging::Debug(_logger, "VAsioTcpPeer: Subscribing to messages of type '{}' on link '{}' from participant '{}'", + Services::Logging::Debug(_logger, + "VAsioTcpPeer: Subscribing to messages of type '{}' on link '{}' from participant '{}'", subscriber.msgTypeName, subscriber.networkName, _info.participantName); SendSilKitMsg(SerializedMessage{subscriber}); } @@ -172,7 +171,7 @@ void VAsioPeer::ReadSomeAsync() { SILKIT_ASSERT(_msgBuffer.size() > 0); auto* wPtr = _msgBuffer.data() + _wPos; - auto size = _msgBuffer.size() - _wPos; + auto size = _msgBuffer.size() - _wPos; _currentReceivingBuffer = MutableBuffer{wPtr, size}; @@ -227,7 +226,7 @@ void VAsioPeer::DispatchBuffer() uint32_t msgSize{0u}; if (_msgBuffer.size() < sizeof msgSize) { - throw SilKitError{ "DispatchBuffer: Received message is too small to contain message size header" }; + throw SilKitError{"DispatchBuffer: Received message is too small to contain message size header"}; } memcpy(&msgSize, _msgBuffer.data(), sizeof msgSize); //ensure buffer does not contain data from contiguous messages diff --git a/SilKit/source/core/vasio/VAsioPeer.hpp b/SilKit/source/core/vasio/VAsioPeer.hpp index a31ddf53d..521b61cf3 100644 --- a/SilKit/source/core/vasio/VAsioPeer.hpp +++ b/SilKit/source/core/vasio/VAsioPeer.hpp @@ -85,10 +85,10 @@ class VAsioPeer // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; - inline void SetProtocolVersion(ProtocolVersion v) override; - inline auto GetProtocolVersion() const -> ProtocolVersion override; + inline void SetProtocolVersion(ProtocolVersion v) override; + inline auto GetProtocolVersion() const -> ProtocolVersion override; void Shutdown() override; diff --git a/SilKit/source/core/vasio/VAsioProtocolVersion.hpp b/SilKit/source/core/vasio/VAsioProtocolVersion.hpp index 56e6f1cd6..c6d994ead 100644 --- a/SilKit/source/core/vasio/VAsioProtocolVersion.hpp +++ b/SilKit/source/core/vasio/VAsioProtocolVersion.hpp @@ -65,19 +65,19 @@ auto MapVersionToRelease(const SilKit::Core::RegistryMsgHeader& registryMsgHeade { return {"< v2.0.0"}; } - else if (version == ProtocolVersion{2,0}) + else if (version == ProtocolVersion{2, 0}) { return {"v2.0.0 - v3.4.0"}; } - else if (version == ProtocolVersion{2,1}) + else if (version == ProtocolVersion{2, 1}) { return {"v3.4.1 - v3.99.21"}; } - else if (version == ProtocolVersion{3,0}) + else if (version == ProtocolVersion{3, 0}) { return {"v3.99.22"}; } - else if (version == ProtocolVersion{3,1}) + else if (version == ProtocolVersion{3, 1}) { return {"v3.99.23 - current"}; } @@ -88,12 +88,12 @@ auto MapVersionToRelease(const SilKit::Core::RegistryMsgHeader& registryMsgHeade bool ProtocolVersionSupported(const RegistryMsgHeader& header) { const auto version = ExtractProtocolVersion(header); - if(version == ProtocolVersion{3, 0}) + if (version == ProtocolVersion{3, 0}) { //3.99.21: bumped version to be explicitly incompatible with prior releases (MVP3, CANoe16) return true; } - else if (version == ProtocolVersion{3,1}) + else if (version == ProtocolVersion{3, 1}) { //3.99.23: bumped version to test backwards compatibility with removed VAsioPeerUri in ParticipantAnnouncement return true; @@ -101,7 +101,7 @@ bool ProtocolVersionSupported(const RegistryMsgHeader& header) // NB: Add your explicit backward compatibility here, ensure that Serialize/Deserialize can handle the ProtocolVersion transparently. return false; - } +} inline auto operator<<(std::ostream& out, const ProtocolVersion& header) -> std::ostream& { diff --git a/SilKit/source/core/vasio/VAsioProxyPeer.cpp b/SilKit/source/core/vasio/VAsioProxyPeer.cpp index 8bb7326f2..d4637f181 100644 --- a/SilKit/source/core/vasio/VAsioProxyPeer.cpp +++ b/SilKit/source/core/vasio/VAsioProxyPeer.cpp @@ -107,7 +107,8 @@ void VAsioProxyPeer::SetProtocolVersion(ProtocolVersion v) auto VAsioProxyPeer::GetProtocolVersion() const -> ProtocolVersion { - Log::Trace(_logger, "VAsioProxyPeer ({}): GetProtocolVersion: {}.{}", _peerInfo.participantName, _protocolVersion.major, _protocolVersion.minor); + Log::Trace(_logger, "VAsioProxyPeer ({}): GetProtocolVersion: {}.{}", _peerInfo.participantName, + _protocolVersion.major, _protocolVersion.minor); return _protocolVersion; } diff --git a/SilKit/source/core/vasio/VAsioReceiver.hpp b/SilKit/source/core/vasio/VAsioReceiver.hpp old mode 100755 new mode 100644 index 6435f648e..7e46a7c8e --- a/SilKit/source/core/vasio/VAsioReceiver.hpp +++ b/SilKit/source/core/vasio/VAsioReceiver.hpp @@ -34,14 +34,14 @@ namespace Core { struct RemoteServiceEndpoint : IServiceEndpoint { - void SetServiceDescriptor(const SilKit::Core::ServiceDescriptor&) override + void SetServiceDescriptor(const SilKit::Core::ServiceDescriptor&) override { throw LogicError("This method is not supposed to be used in this struct."); } - auto GetServiceDescriptor() const -> const ServiceDescriptor & override + auto GetServiceDescriptor() const -> const ServiceDescriptor& override { - return _serviceDescriptor; + return _serviceDescriptor; } RemoteServiceEndpoint(const ServiceDescriptor& descriptor) @@ -73,7 +73,8 @@ class VAsioReceiver public: // ---------------------------------------- // Constructors and Destructor - VAsioReceiver(VAsioMsgSubscriber subscriberInfo, std::shared_ptr> link, Services::Logging::ILogger* logger); + VAsioReceiver(VAsioMsgSubscriber subscriberInfo, std::shared_ptr> link, + Services::Logging::ILogger* logger); public: // ---------------------------------------- @@ -102,7 +103,8 @@ class VAsioReceiver // Inline Implementations // ================================================================================ template -VAsioReceiver::VAsioReceiver(VAsioMsgSubscriber subscriberInfo, std::shared_ptr> link, Services::Logging::ILogger* logger) +VAsioReceiver::VAsioReceiver(VAsioMsgSubscriber subscriberInfo, std::shared_ptr> link, + Services::Logging::ILogger* logger) : _subscriptionInfo{std::move(subscriberInfo)} , _link{link} , _logger{logger} @@ -117,7 +119,8 @@ auto VAsioReceiver::GetDescriptor() const -> const VAsioMsgSubscriber& } template -void VAsioReceiver::ReceiveRawMsg(IVAsioPeer* /*from*/, const ServiceDescriptor& descriptor, SerializedMessage&& buffer) +void VAsioReceiver::ReceiveRawMsg(IVAsioPeer* /*from*/, const ServiceDescriptor& descriptor, + SerializedMessage&& buffer) { MsgT msg = buffer.Deserialize(); @@ -125,7 +128,6 @@ void VAsioReceiver::ReceiveRawMsg(IVAsioPeer* /*from*/, const ServiceDescr auto remoteId = RemoteServiceEndpoint(descriptor); _link->DistributeRemoteSilKitMessage(&remoteId, std::move(msg)); - } } // namespace Core diff --git a/SilKit/source/core/vasio/VAsioRegistry.cpp b/SilKit/source/core/vasio/VAsioRegistry.cpp old mode 100755 new mode 100644 index fc1c8a411..75caea6fb --- a/SilKit/source/core/vasio/VAsioRegistry.cpp +++ b/SilKit/source/core/vasio/VAsioRegistry.cpp @@ -60,9 +60,7 @@ VAsioRegistry::VAsioRegistry(std::shared_ptrOnParticipantAnnouncement(from, announcement); }); - _connection.RegisterPeerShutdownCallback([this](IVAsioPeer* peer) { - OnPeerShutdown(peer); - }); + _connection.RegisterPeerShutdownCallback([this](IVAsioPeer* peer) { OnPeerShutdown(peer); }); _serviceDescriptor.SetParticipantNameAndComputeId(REGISTRY_PARTICIPANT_NAME); _serviceDescriptor.SetParticipantId(REGISTRY_PARTICIPANT_ID); @@ -175,8 +173,7 @@ auto VAsioRegistry::GetLogger() -> Services::Logging::ILogger* } auto VAsioRegistry::FindConnectedParticipant(const std::string& participantName, - const std::string& simulationName) const - -> const ConnectedParticipantInfo* + const std::string& simulationName) const -> const ConnectedParticipantInfo* { const auto simulationIt{_connectedParticipants.find(simulationName)}; if (simulationIt == _connectedParticipants.end()) diff --git a/SilKit/source/core/vasio/VAsioRegistry.hpp b/SilKit/source/core/vasio/VAsioRegistry.hpp old mode 100755 new mode 100644 index cd8373fb0..31df4617e --- a/SilKit/source/core/vasio/VAsioRegistry.hpp +++ b/SilKit/source/core/vasio/VAsioRegistry.hpp @@ -93,8 +93,8 @@ class VAsioRegistry private: // ---------------------------------------- // private methods - auto FindConnectedParticipant(const std::string& participantName, const std::string& simulationName) const - -> const ConnectedParticipantInfo*; + auto FindConnectedParticipant(const std::string& participantName, + const std::string& simulationName) const -> const ConnectedParticipantInfo*; void OnParticipantAnnouncement(IVAsioPeer* peer, const ParticipantAnnouncement& announcement); void SendKnownParticipants(IVAsioPeer* peer, const std::string& simulationName); diff --git a/SilKit/source/core/vasio/VAsioSerdes.cpp b/SilKit/source/core/vasio/VAsioSerdes.cpp old mode 100755 new mode 100644 index 55602718b..ec4315ed2 --- a/SilKit/source/core/vasio/VAsioSerdes.cpp +++ b/SilKit/source/core/vasio/VAsioSerdes.cpp @@ -35,71 +35,49 @@ namespace Core { inline MessageBuffer& operator<<(MessageBuffer& buffer, const RegistryMsgHeader& header) { - buffer << header.preamble - << header.versionHigh - << header.versionLow; + buffer << header.preamble << header.versionHigh << header.versionLow; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, RegistryMsgHeader& header) { - buffer >> header.preamble - >> header.versionHigh - >> header.versionLow; + buffer >> header.preamble >> header.versionHigh >> header.versionLow; return buffer; } inline MessageBuffer& operator<<(MessageBuffer& buffer, const VAsioPeerInfo& peerInfo) { - buffer << peerInfo.participantName - << peerInfo.participantId - << peerInfo.acceptorUris - << peerInfo.capabilities - ; + buffer << peerInfo.participantName << peerInfo.participantId << peerInfo.acceptorUris << peerInfo.capabilities; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, VAsioPeerInfo& peerInfo) { - buffer >> peerInfo.participantName - >> peerInfo.participantId - >> peerInfo.acceptorUris - >> peerInfo.capabilities - ; + buffer >> peerInfo.participantName >> peerInfo.participantId >> peerInfo.acceptorUris >> peerInfo.capabilities; return buffer; } inline MessageBuffer& operator<<(MessageBuffer& buffer, const VAsioMsgSubscriber& subscriber) { - buffer << subscriber.receiverIdx - << subscriber.networkName - << subscriber.msgTypeName - << subscriber.version - ; + buffer << subscriber.receiverIdx << subscriber.networkName << subscriber.msgTypeName << subscriber.version; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, VAsioMsgSubscriber& subscriber) { - buffer >> subscriber.receiverIdx - >> subscriber.networkName - >> subscriber.msgTypeName - >> subscriber.version - ; + buffer >> subscriber.receiverIdx >> subscriber.networkName >> subscriber.msgTypeName >> subscriber.version; return buffer; } inline MessageBuffer& operator<<(MessageBuffer& buffer, const SubscriptionAcknowledge& ack) { - buffer << ack.status - << ack.subscriber; + buffer << ack.status << ack.subscriber; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, SubscriptionAcknowledge& ack) { - buffer >> ack.status - >> ack.subscriber; + buffer >> ack.status >> ack.subscriber; return buffer; } @@ -108,17 +86,13 @@ inline MessageBuffer& operator<<(MessageBuffer& buffer, const ParticipantAnnounc // ParticipantAnnouncement is the first message sent during a handshake. // so we need to extract its version information for ser/des here. buffer.SetProtocolVersion(ExtractProtocolVersion(announcement.messageHeader)); - if (buffer.GetProtocolVersion() == ProtocolVersion{3,0}) + if (buffer.GetProtocolVersion() == ProtocolVersion{3, 0}) { SerializeV30(buffer, announcement); } else { - buffer - << announcement.messageHeader - << announcement.peerInfo - << announcement.simulationName - ; + buffer << announcement.messageHeader << announcement.peerInfo << announcement.simulationName; } return buffer; @@ -127,16 +101,14 @@ inline MessageBuffer& operator<<(MessageBuffer& buffer, const ParticipantAnnounc inline MessageBuffer& operator>>(MessageBuffer& buffer, ParticipantAnnouncement& announcement) { //Backward compatibility - if (buffer.GetProtocolVersion() == ProtocolVersion{3,0}) + if (buffer.GetProtocolVersion() == ProtocolVersion{3, 0}) { DeserializeV30(buffer, announcement); } else { // default - buffer - >> announcement.messageHeader - >> announcement.peerInfo; + buffer >> announcement.messageHeader >> announcement.peerInfo; if (buffer.RemainingBytesLeft() == 0) { @@ -151,34 +123,29 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, ParticipantAnnouncement& inline MessageBuffer& operator<<(MessageBuffer& buffer, const ParticipantAnnouncementReply& reply) { //Backward compatibility - if (buffer.GetProtocolVersion() == ProtocolVersion{3,0}) + if (buffer.GetProtocolVersion() == ProtocolVersion{3, 0}) { SerializeV30(buffer, reply); } else { - buffer - << reply.remoteHeader - << reply.status - << reply.subscribers - // Added in 4.0.8. - << reply.diagnostic; + buffer << reply.remoteHeader << reply.status + << reply.subscribers + // Added in 4.0.8. + << reply.diagnostic; } return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, ParticipantAnnouncementReply& reply) { //Backward compatibility - if (buffer.GetProtocolVersion() == ProtocolVersion{3,0}) + if (buffer.GetProtocolVersion() == ProtocolVersion{3, 0}) { DeserializeV30(buffer, reply); } else { - buffer - >> reply.remoteHeader - >> reply.status - >> reply.subscribers; + buffer >> reply.remoteHeader >> reply.status >> reply.subscribers; // Added in 4.0.8. if (buffer.RemainingBytesLeft() > 0) @@ -198,24 +165,20 @@ inline MessageBuffer& operator<<(MessageBuffer& buffer, const KnownParticipants& } else { - buffer << participants.messageHeader - << participants.peerInfos - ; + buffer << participants.messageHeader << participants.peerInfos; } return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, KnownParticipants& participants) { //Backward compatibility with legacy peers - if (buffer.GetProtocolVersion() == ProtocolVersion{3,0}) + if (buffer.GetProtocolVersion() == ProtocolVersion{3, 0}) { DeserializeV30(buffer, participants); } else { - buffer >> participants.messageHeader - >> participants.peerInfos - ; + buffer >> participants.messageHeader >> participants.peerInfos; } return buffer; } @@ -223,30 +186,26 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, KnownParticipants& parti inline MessageBuffer& operator<<(MessageBuffer& buffer, const ProxyMessageHeader& msg) { //Backward compatibility with legacy peers - if (buffer.GetProtocolVersion() < ProtocolVersion{3,1}) + if (buffer.GetProtocolVersion() < ProtocolVersion{3, 1}) { throw SilKit::ProtocolError{"ProxyMessage is not supported in protocol versions < 3.1"}; } else { - buffer - << msg.version - ; + buffer << msg.version; } return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, ProxyMessageHeader& out) { //Backward compatibility with legacy peers - if (buffer.GetProtocolVersion() < ProtocolVersion{3,1}) + if (buffer.GetProtocolVersion() < ProtocolVersion{3, 1}) { throw SilKit::ProtocolError{"ProxyMessage is not supported in protocol versions < 3.1"}; } else { - buffer - >> out.version - ; + buffer >> out.version; } return buffer; } @@ -254,36 +213,26 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, ProxyMessageHeader& out) inline MessageBuffer& operator<<(MessageBuffer& buffer, const ProxyMessage& msg) { //Backward compatibility with legacy peers - if (buffer.GetProtocolVersion() < ProtocolVersion{3,1}) + if (buffer.GetProtocolVersion() < ProtocolVersion{3, 1}) { throw SilKit::ProtocolError{"ProxyMessage is not supported in protocol versions < 3.1"}; } else { - buffer - << msg.header - << msg.source - << msg.destination - << msg.payload - ; + buffer << msg.header << msg.source << msg.destination << msg.payload; } return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, ProxyMessage& out) { //Backward compatibility with legacy peers - if (buffer.GetProtocolVersion() < ProtocolVersion{3,1}) + if (buffer.GetProtocolVersion() < ProtocolVersion{3, 1}) { throw SilKit::ProtocolError{"ProxyMessage is not supported in protocol versions < 3.1"}; } else { - buffer - >> out.header - >> out.source - >> out.destination - >> out.payload - ; + buffer >> out.header >> out.source >> out.destination >> out.payload; } return buffer; } @@ -291,20 +240,12 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, ProxyMessage& out) inline MessageBuffer& operator<<(MessageBuffer& buffer, const RemoteParticipantConnectRequest& msg) { - buffer - << msg.messageHeader - << msg.requestOrigin - << msg.requestTarget - << msg.status; + buffer << msg.messageHeader << msg.requestOrigin << msg.requestTarget << msg.status; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, RemoteParticipantConnectRequest& out) { - buffer - >> out.messageHeader - >> out.requestOrigin - >> out.requestTarget - >> out.status; + buffer >> out.messageHeader >> out.requestOrigin >> out.requestTarget >> out.status; return buffer; } @@ -382,7 +323,7 @@ void Serialize(MessageBuffer& buffer, const ParticipantAnnouncementReply& msg) { buffer << msg; } -void Deserialize(MessageBuffer& buffer,ParticipantAnnouncementReply& out) +void Deserialize(MessageBuffer& buffer, ParticipantAnnouncementReply& out) { buffer >> out; } @@ -396,7 +337,7 @@ void Deserialize(MessageBuffer& buffer, ParticipantAnnouncement& out) buffer >> out; } - void Serialize(MessageBuffer& buffer, const VAsioMsgSubscriber& msg) +void Serialize(MessageBuffer& buffer, const VAsioMsgSubscriber& msg) { buffer << msg; } @@ -406,9 +347,9 @@ void Deserialize(MessageBuffer& buffer, VAsioMsgSubscriber& out) buffer >> out; } - void Serialize(MessageBuffer& buffer, const SubscriptionAcknowledge& msg) +void Serialize(MessageBuffer& buffer, const SubscriptionAcknowledge& msg) { - buffer<< msg; + buffer << msg; } void Deserialize(MessageBuffer& buffer, SubscriptionAcknowledge& out) { @@ -419,7 +360,7 @@ void Serialize(MessageBuffer& buffer, const KnownParticipants& msg) { buffer << msg; } -void Deserialize(MessageBuffer& buffer,KnownParticipants& out) +void Deserialize(MessageBuffer& buffer, KnownParticipants& out) { buffer >> out; } diff --git a/SilKit/source/core/vasio/VAsioSerdes.hpp b/SilKit/source/core/vasio/VAsioSerdes.hpp index 0363e3512..b076859ea 100644 --- a/SilKit/source/core/vasio/VAsioSerdes.hpp +++ b/SilKit/source/core/vasio/VAsioSerdes.hpp @@ -43,8 +43,8 @@ auto ExtractRegistryMessageKind(MessageBuffer& buffer) -> RegistryMessageKind; auto PeekRegistryMessageHeader(MessageBuffer& buffer) -> RegistryMsgHeader; auto PeekProxyMessageHeader(MessageBuffer& buffer) -> ProxyMessageHeader; -auto ExtractEndpointId(MessageBuffer& buffer) ->EndpointId; -auto ExtractEndpointAddress(MessageBuffer& buffer) ->EndpointAddress; +auto ExtractEndpointId(MessageBuffer& buffer) -> EndpointId; +auto ExtractEndpointAddress(MessageBuffer& buffer) -> EndpointAddress; //! Handshake: Serialize ParticipantAnnouncementReply (contains remote peer's protocol version) // VAsioMsgKind: SilKitRegistryMessage @@ -57,10 +57,10 @@ void Serialize(MessageBuffer& buffer, const ProxyMessage& msg); void Serialize(MessageBuffer& buffer, const RemoteParticipantConnectRequest& msg); void Deserialize(MessageBuffer& buffer, ParticipantAnnouncement& out); -void Deserialize(MessageBuffer& buffer,ParticipantAnnouncementReply& out); +void Deserialize(MessageBuffer& buffer, ParticipantAnnouncementReply& out); void Deserialize(MessageBuffer&, VAsioMsgSubscriber&); void Deserialize(MessageBuffer&, SubscriptionAcknowledge&); -void Deserialize(MessageBuffer& buffer,KnownParticipants& out); +void Deserialize(MessageBuffer& buffer, KnownParticipants& out); void Deserialize(MessageBuffer& buffer, ProxyMessage& out); void Deserialize(MessageBuffer& buffer, RemoteParticipantConnectRequest& out); diff --git a/SilKit/source/core/vasio/VAsioSerdes_Protocol30.cpp b/SilKit/source/core/vasio/VAsioSerdes_Protocol30.cpp index f2afaa5c5..c2568c6db 100644 --- a/SilKit/source/core/vasio/VAsioSerdes_Protocol30.cpp +++ b/SilKit/source/core/vasio/VAsioSerdes_Protocol30.cpp @@ -41,16 +41,12 @@ struct RegistryMsgHeader inline MessageBuffer& operator<<(MessageBuffer& buffer, const RegistryMsgHeader& header) { - buffer << header.preambel - << header.versionHigh - << header.versionLow; + buffer << header.preambel << header.versionHigh << header.versionLow; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, RegistryMsgHeader& header) { - buffer >> header.preambel - >> header.versionHigh - >> header.versionLow; + buffer >> header.preambel >> header.versionHigh >> header.versionLow; return buffer; } @@ -64,19 +60,13 @@ struct VAsioMsgSubscriber inline MessageBuffer& operator<<(MessageBuffer& buffer, const VAsioMsgSubscriber& subscriber) { - buffer << subscriber.receiverIdx - << subscriber.networkName - << subscriber.msgTypeName - ; + buffer << subscriber.receiverIdx << subscriber.networkName << subscriber.msgTypeName; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, VAsioMsgSubscriber& subscriber) { - buffer >> subscriber.receiverIdx - >> subscriber.networkName - >> subscriber.msgTypeName - ; + buffer >> subscriber.receiverIdx >> subscriber.networkName >> subscriber.msgTypeName; return buffer; } @@ -120,71 +110,53 @@ struct KnownParticipants // Actual Serdes Code inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const VAsioPeerInfo& peerInfo) { - buffer << peerInfo.participantName - << peerInfo.participantId - << peerInfo.acceptorHost - << peerInfo.acceptorPort; + buffer << peerInfo.participantName << peerInfo.participantId << peerInfo.acceptorHost << peerInfo.acceptorPort; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, VAsioPeerInfo& peerInfo) { - buffer >> peerInfo.participantName - >> peerInfo.participantId - >> peerInfo.acceptorHost - >> peerInfo.acceptorPort; + buffer >> peerInfo.participantName >> peerInfo.participantId >> peerInfo.acceptorHost >> peerInfo.acceptorPort; return buffer; } //SerDes v3.1 inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const VAsioPeerUri& peerUri) { - buffer << peerUri.participantName - << peerUri.participantId - << peerUri.acceptorUris - ; + buffer << peerUri.participantName << peerUri.participantId << peerUri.acceptorUris; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, VAsioPeerUri& peerUri) { - buffer >> peerUri.participantName - >> peerUri.participantId - >> peerUri.acceptorUris - ; + buffer >> peerUri.participantName >> peerUri.participantId >> peerUri.acceptorUris; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const ParticipantAnnouncement& announcement) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const ParticipantAnnouncement& announcement) { - buffer << announcement.messageHeader - << announcement.peerInfo - << announcement.peerUri - ; + buffer << announcement.messageHeader << announcement.peerInfo << announcement.peerUri; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, ParticipantAnnouncement& announcement) +inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, + ParticipantAnnouncement& announcement) { - buffer >> announcement.messageHeader - >> announcement.peerInfo - >> announcement.peerUri - ; + buffer >> announcement.messageHeader >> announcement.peerInfo >> announcement.peerUri; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const KnownParticipants& participants) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const KnownParticipants& participants) { - buffer << participants.messageHeader - << participants.peerInfos - << participants.peerUris; + buffer << participants.messageHeader << participants.peerInfos << participants.peerUris; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, KnownParticipants& participants) { - buffer >> participants.messageHeader - >> participants.peerInfos; + buffer >> participants.messageHeader >> participants.peerInfos; if (buffer.RemainingBytesLeft() > 0) { buffer >> participants.peerUris; @@ -192,7 +164,8 @@ inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buff return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const ParticipantAnnouncementReply& reply) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const ParticipantAnnouncementReply& reply) { buffer << reply.subscribers; return buffer; @@ -262,7 +235,6 @@ void SerializeV30(MessageBuffer& buffer, const ParticipantAnnouncementReply& rep protocol_3_0::ParticipantAnnouncementReply oldReply; for (const auto& subscriber : reply.subscribers) { - protocol_3_0::VAsioMsgSubscriber oldSubscriber; oldSubscriber.msgTypeName = subscriber.msgTypeName; oldSubscriber.networkName = subscriber.networkName; diff --git a/SilKit/source/core/vasio/VAsioSerdes_Protocol30.hpp b/SilKit/source/core/vasio/VAsioSerdes_Protocol30.hpp index 21b336846..be6bac710 100644 --- a/SilKit/source/core/vasio/VAsioSerdes_Protocol30.hpp +++ b/SilKit/source/core/vasio/VAsioSerdes_Protocol30.hpp @@ -37,4 +37,3 @@ void DeserializeV30(MessageBuffer& buffer, KnownParticipants& reply); } // namespace Core } // namespace SilKit - diff --git a/SilKit/source/core/vasio/VAsioTransmitter.hpp b/SilKit/source/core/vasio/VAsioTransmitter.hpp index 7e1eb84ce..28de3f01d 100644 --- a/SilKit/source/core/vasio/VAsioTransmitter.hpp +++ b/SilKit/source/core/vasio/VAsioTransmitter.hpp @@ -36,24 +36,28 @@ namespace SilKit { namespace Core { //auxiliary class for conditional compilation using silkit message traits -template -struct MessageHistory {}; +template +struct MessageHistory +{ +}; // MessageHistory<.., 0>: message history is disabled -template struct MessageHistory +template +struct MessageHistory { void SetHistoryLength(size_t) {} - void Save(const IServiceEndpoint*, const MsgT& ) {} + void Save(const IServiceEndpoint*, const MsgT&) {} void NotifyPeer(IVAsioPeer*, EndpointId) {} }; // MessageHistory<.., 1>: save last message and notify peers about it -template struct MessageHistory +template +struct MessageHistory { void SetHistoryLength(size_t historyLength) { _hasHistory = historyLength != 0; } - void Save(const IServiceEndpoint* from , const MsgT& msg) + void Save(const IServiceEndpoint* from, const MsgT& msg) { if (!_hasHistory) return; @@ -70,6 +74,7 @@ template struct MessageHistory auto buffer = SerializedMessage(_last, _from, remoteIdx); peer->SendSilKitMsg(std::move(buffer)); } + private: MsgT _last; EndpointAddress _from; @@ -78,18 +83,20 @@ template struct MessageHistory }; -struct RemoteReceiver { +struct RemoteReceiver +{ IVAsioPeer* peer; EndpointId remoteIdx; }; template -class VAsioTransmitter +class VAsioTransmitter : public IMessageReceiver , public IServiceEndpoint { using History = MessageHistory::HistSize()>; History _hist; + public: // ---------------------------------------- // Public methods @@ -122,33 +129,32 @@ class VAsioTransmitter } size_t GetNumberOfRemoteReceivers() - { + { return _remoteReceivers.size(); } - std::vector GetParticipantNamesOfRemoteReceivers() + std::vector GetParticipantNamesOfRemoteReceivers() { std::vector participantNames{}; for (auto it = _remoteReceivers.begin(); it != _remoteReceivers.end(); ++it) { participantNames.push_back((*it).peer->GetInfo().participantName); } - return participantNames; + return participantNames; } void SendMessageToTarget(const IServiceEndpoint* from, const std::string& targetParticipantName, const MsgT& msg) { _hist.Save(from, msg); - auto&& receiverIter = std::find_if(_remoteReceivers.begin(), _remoteReceivers.end(), [targetParticipantName](auto&& receiver) - { - return receiver.peer->GetInfo().participantName == targetParticipantName; - }); + auto&& receiverIter = + std::find_if(_remoteReceivers.begin(), _remoteReceivers.end(), [targetParticipantName](auto&& receiver) { + return receiver.peer->GetInfo().participantName == targetParticipantName; + }); if (receiverIter == _remoteReceivers.end()) { std::stringstream ss; - ss << "Error: Attempt to send targeted message to participant '" - << targetParticipantName - << "', which is not a valid remote receiver."; + ss << "Error: Attempt to send targeted message to participant '" << targetParticipantName + << "', which is not a valid remote receiver."; throw SilKitError{ss.str()}; } auto buffer = SerializedMessage(msg, to_endpointAddress(from->GetServiceDescriptor()), receiverIter->remoteIdx); @@ -182,6 +188,7 @@ class VAsioTransmitter { return _serviceDescriptor; } + private: // ---------------------------------------- // private members @@ -194,8 +201,7 @@ class VAsioTransmitter // ================================================================================ inline bool operator==(const RemoteReceiver& lhs, const RemoteReceiver& rhs) { - return lhs.peer == rhs.peer - && lhs.remoteIdx == rhs.remoteIdx; + return lhs.peer == rhs.peer && lhs.remoteIdx == rhs.remoteIdx; } } // namespace Core diff --git a/SilKit/source/core/vasio/io/Test_AsioIoContext.cpp b/SilKit/source/core/vasio/io/Test_AsioIoContext.cpp index 97aa6b308..f1e4eaeeb 100644 --- a/SilKit/source/core/vasio/io/Test_AsioIoContext.cpp +++ b/SilKit/source/core/vasio/io/Test_AsioIoContext.cpp @@ -40,9 +40,7 @@ void CheckIoContextDispatchBeforeRunIsExecutedAtRun(VSilKit::IIoContext& ioConte { bool flag{false}; - ioContext.Dispatch([&flag] { - flag = true; - }); + ioContext.Dispatch([&flag] { flag = true; }); ASSERT_FALSE(flag); ioContext.Run(); @@ -54,9 +52,7 @@ void CheckIoContextPostBeforeRunIsExecutedAtRun(VSilKit::IIoContext& ioContext) { bool flag{false}; - ioContext.Post([&flag] { - flag = true; - }); + ioContext.Post([&flag] { flag = true; }); ASSERT_FALSE(flag); ioContext.Run(); diff --git a/SilKit/source/core/vasio/io/Test_IoContext.cpp b/SilKit/source/core/vasio/io/Test_IoContext.cpp index 43894d848..8dd40505e 100644 --- a/SilKit/source/core/vasio/io/Test_IoContext.cpp +++ b/SilKit/source/core/vasio/io/Test_IoContext.cpp @@ -98,13 +98,9 @@ TEST_F(Test_IoContext, sequential_post_keeps_order) auto ioContext = VSilKit::MakeAsioIoContext({}); - ioContext->Post([&callbacks]() { - callbacks.Handle(0); - }); + ioContext->Post([&callbacks]() { callbacks.Handle(0); }); - ioContext->Post([&callbacks]() { - callbacks.Handle(1); - }); + ioContext->Post([&callbacks]() { callbacks.Handle(1); }); ioContext->Run(); } @@ -123,15 +119,11 @@ TEST_F(Test_IoContext, nested_post_is_executed_last) ioContext->Post([&ioContext, &callbacks]() { callbacks.Handle(0); - ioContext->Post([&callbacks]() { - callbacks.Handle(3); - }); + ioContext->Post([&callbacks]() { callbacks.Handle(3); }); callbacks.Handle(1); }); - ioContext->Post([&callbacks]() { - callbacks.Handle(2); - }); + ioContext->Post([&callbacks]() { callbacks.Handle(2); }); ioContext->Run(); } @@ -146,13 +138,9 @@ TEST_F(Test_IoContext, sequential_dispatch_keeps_order) auto ioContext = VSilKit::MakeAsioIoContext({}); - ioContext->Dispatch([&callbacks]() { - callbacks.Handle(0); - }); + ioContext->Dispatch([&callbacks]() { callbacks.Handle(0); }); - ioContext->Dispatch([&callbacks]() { - callbacks.Handle(1); - }); + ioContext->Dispatch([&callbacks]() { callbacks.Handle(1); }); ioContext->Run(); } @@ -171,15 +159,11 @@ TEST_F(Test_IoContext, nested_dispatch_is_executed_immediately) ioContext->Dispatch([&ioContext, &callbacks]() { callbacks.Handle(0); - ioContext->Dispatch([&callbacks]() { - callbacks.Handle(1); - }); + ioContext->Dispatch([&callbacks]() { callbacks.Handle(1); }); callbacks.Handle(2); }); - ioContext->Dispatch([&callbacks]() { - callbacks.Handle(3); - }); + ioContext->Dispatch([&callbacks]() { callbacks.Handle(3); }); ioContext->Run(); } @@ -348,9 +332,7 @@ struct Test_IoContext_AcceptorConnector_PingPong : Test_IoContext accepted.stream->AsyncWriteSome(ConstBufferSequence{&writeBuffer, 1}); }); - EXPECT_CALL(accepted.listener, OnAsyncWriteSomeDone).WillOnce([this] { - callbacks.Handle(12); - }); + EXPECT_CALL(accepted.listener, OnAsyncWriteSomeDone).WillOnce([this] { callbacks.Handle(12); }); // expectations and behavior of the connected stream diff --git a/SilKit/source/core/vasio/io/impl/AsioAcceptor.hpp b/SilKit/source/core/vasio/io/impl/AsioAcceptor.hpp index d6dae9984..d3c80c4e8 100644 --- a/SilKit/source/core/vasio/io/impl/AsioAcceptor.hpp +++ b/SilKit/source/core/vasio/io/impl/AsioAcceptor.hpp @@ -25,9 +25,9 @@ #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_AsioAcceptor -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif @@ -130,17 +130,13 @@ void AsioAcceptor::AsyncAccept(std::chrono::milliseconds timeout) throw InvalidStateError{}; } - auto acceptCompletionHandler = - asio::bind_cancellation_slot(_acceptCancelSignal.slot(), [this](const auto& e, auto s) { - OnAsioAsyncAcceptComplete(e, std::move(s)); - }); + auto acceptCompletionHandler = asio::bind_cancellation_slot( + _acceptCancelSignal.slot(), [this](const auto& e, auto s) { OnAsioAsyncAcceptComplete(e, std::move(s)); }); if (timeout.count() > 0) { - auto timeoutCompletionHandler = - asio::bind_cancellation_slot(_timeoutCancelSignal.slot(), [this](const auto& e) { - OnAsioAsyncWaitComplete(e); - }); + auto timeoutCompletionHandler = asio::bind_cancellation_slot( + _timeoutCancelSignal.slot(), [this](const auto& e) { OnAsioAsyncWaitComplete(e); }); _timeoutTimer.expires_after(timeout); _timeoutTimer.async_wait(timeoutCompletionHandler); diff --git a/SilKit/source/core/vasio/io/impl/AsioConnector.hpp b/SilKit/source/core/vasio/io/impl/AsioConnector.hpp index 346c27377..28ca01340 100644 --- a/SilKit/source/core/vasio/io/impl/AsioConnector.hpp +++ b/SilKit/source/core/vasio/io/impl/AsioConnector.hpp @@ -26,9 +26,9 @@ #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_AsioConnector -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif @@ -187,17 +187,15 @@ void AsioConnector::Op::Initiate(std::chrono::milliseconds timeout) return; } - auto connectCompletionHandler = - asio::bind_cancellation_slot(_connectCancelSignal.slot(), [self = this->shared_from_this()](const auto& e) { - self->OnAsioAsyncConnectComplete(e); - }); + auto connectCompletionHandler = asio::bind_cancellation_slot( + _connectCancelSignal.slot(), + [self = this->shared_from_this()](const auto& e) { self->OnAsioAsyncConnectComplete(e); }); if (timeout.count() > 0) { - auto timeoutCompletionHandler = - asio::bind_cancellation_slot(_timeoutCancelSignal.slot(), [self = this->shared_from_this()](const auto& e) { - self->OnAsioAsyncWaitComplete(e); - }); + auto timeoutCompletionHandler = asio::bind_cancellation_slot( + _timeoutCancelSignal.slot(), + [self = this->shared_from_this()](const auto& e) { self->OnAsioAsyncWaitComplete(e); }); _timeoutTimer.expires_after(timeout); _timeoutTimer.async_wait(timeoutCompletionHandler); diff --git a/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp b/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp index 4023813e8..1b10f2054 100644 --- a/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp +++ b/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp @@ -21,16 +21,16 @@ // For EnableQuickAck #if defined(__linux__) -# include -# include -# include +#include +#include +#include #endif #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_AsioGenericRawByteStream -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif @@ -122,12 +122,11 @@ void AsioGenericRawByteStream::AsyncReadSome(MutableBufferSequence bufferSequenc _readBufferSequence.resize(bufferSequence.size()); std::transform(bufferSequence.begin(), bufferSequence.end(), _readBufferSequence.begin(), [](const MutableBuffer& buffer) -> asio::mutable_buffer { - return asio::mutable_buffer{buffer.GetData(), buffer.GetSize()}; - }); - - _socket.async_read_some(_readBufferSequence, [this](const auto& e, auto s) { - OnAsioAsyncReadSomeComplete(e, s); + return asio::mutable_buffer{buffer.GetData(), buffer.GetSize()}; }); + + _socket.async_read_some(_readBufferSequence, + [this](const auto& e, auto s) { OnAsioAsyncReadSomeComplete(e, s); }); } } @@ -157,12 +156,11 @@ void AsioGenericRawByteStream::AsyncWriteSome(ConstBufferSequence bufferSequence _writeBufferSequence.resize(bufferSequence.size()); std::transform(bufferSequence.begin(), bufferSequence.end(), _writeBufferSequence.begin(), [](const ConstBuffer& buffer) -> asio::const_buffer { - return asio::const_buffer{buffer.GetData(), buffer.GetSize()}; - }); - - _socket.async_write_some(_writeBufferSequence, [this](const auto& e, auto s) { - OnAsioAsyncWriteSomeComplete(e, s); + return asio::const_buffer{buffer.GetData(), buffer.GetSize()}; }); + + _socket.async_write_some(_writeBufferSequence, + [this](const auto& e, auto s) { OnAsioAsyncWriteSomeComplete(e, s); }); } } @@ -207,9 +205,8 @@ void AsioGenericRawByteStream::OnAsioAsyncReadSomeComplete(asio::error_code cons // only re-trigger the read if no bytes were transferred, otherwise treat it as a 'normal' completion _reading = true; - _socket.async_read_some(_readBufferSequence, [this](const auto& e, auto s) { - OnAsioAsyncReadSomeComplete(e, s); - }); + _socket.async_read_some(_readBufferSequence, + [this](const auto& e, auto s) { OnAsioAsyncReadSomeComplete(e, s); }); return; } @@ -246,9 +243,8 @@ void AsioGenericRawByteStream::OnAsioAsyncWriteSomeComplete(asio::error_code con // only re-trigger the write if no bytes were transferred, otherwise treat it as a 'normal' completion _writing = true; - _socket.async_write_some(_writeBufferSequence, [this](const auto& e, auto s) { - OnAsioAsyncWriteSomeComplete(e, s); - }); + _socket.async_write_some(_writeBufferSequence, + [this](const auto& e, auto s) { OnAsioAsyncWriteSomeComplete(e, s); }); return; } @@ -260,8 +256,8 @@ void AsioGenericRawByteStream::OnAsioAsyncWriteSomeComplete(asio::error_code con void AsioGenericRawByteStream::HandleShutdownOrError() { - SILKIT_TRACE_METHOD_(_logger, "() [shutdownPosted={}, shutdownPending={}, reading={}, writing={}]", _shutdownPending, - _shutdownPosted, _reading, _writing); + SILKIT_TRACE_METHOD_(_logger, "() [shutdownPosted={}, shutdownPending={}, reading={}, writing={}]", + _shutdownPending, _shutdownPosted, _reading, _writing); if (!_shutdownPending) { @@ -287,9 +283,7 @@ void AsioGenericRawByteStream::HandleShutdownOrError() _shutdownPosted = true; - _asioIoContext->post([this] { - _listener->OnShutdown(*this); - }); + _asioIoContext->post([this] { _listener->OnShutdown(*this); }); } } } diff --git a/SilKit/source/core/vasio/io/impl/AsioIoContext.cpp b/SilKit/source/core/vasio/io/impl/AsioIoContext.cpp index 1f94598d7..50cdaf922 100644 --- a/SilKit/source/core/vasio/io/impl/AsioIoContext.cpp +++ b/SilKit/source/core/vasio/io/impl/AsioIoContext.cpp @@ -22,9 +22,9 @@ #if SILKIT_ENABLE_TRACING_INSTRUMENTATION_AsioIoContext -# define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) +#define SILKIT_TRACE_METHOD_(logger, ...) SILKIT_TRACE_METHOD(logger, __VA_ARGS__) #else -# define SILKIT_TRACE_METHOD_(...) +#define SILKIT_TRACE_METHOD_(...) #endif @@ -58,7 +58,7 @@ void SetConnectOptions(SilKit::Services::Logging::ILogger*, SocketT&) // platform specific definitions of utilities #if defined(_WIN32) -# include +#include template <> void SetPlatformOptions(asio::ip::tcp::acceptor& acceptor) @@ -67,7 +67,7 @@ void SetPlatformOptions(asio::ip::tcp::acceptor& acceptor) acceptor.set_option(exclusive_addruse{true}); } -# if !defined(__MINGW32__) +#if !defined(__MINGW32__) template <> void SetListenOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp::acceptor& acceptor) @@ -103,7 +103,7 @@ void SetConnectOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp } } -# endif // !__MINGW32__ +#endif // !__MINGW32__ #else diff --git a/SilKit/source/core/vasio/io/impl/AsioTimer.cpp b/SilKit/source/core/vasio/io/impl/AsioTimer.cpp index 11db4c1e4..e0d444a8e 100644 --- a/SilKit/source/core/vasio/io/impl/AsioTimer.cpp +++ b/SilKit/source/core/vasio/io/impl/AsioTimer.cpp @@ -54,9 +54,8 @@ AsioTimer::Op::Op(VSilKit::AsioTimer& parent) void AsioTimer::Op::Initiate(std::chrono::nanoseconds duration) { _timer.expires_after(duration); - _timer.async_wait([self = this->shared_from_this()](const asio::error_code& e) { - self->OnAsioAsyncWaitComplete(e); - }); + _timer.async_wait( + [self = this->shared_from_this()](const asio::error_code& e) { self->OnAsioAsyncWaitComplete(e); }); } diff --git a/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.cpp b/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.cpp index f4b94ba3b..078dedf28 100644 --- a/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.cpp +++ b/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.cpp @@ -16,7 +16,7 @@ namespace VSilKit { void SetAsioSocketOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp::socket& socket, - const AsioSocketOptions& socketOptions, std::error_code& errorCode) + const AsioSocketOptions& socketOptions, std::error_code& errorCode) { if (socketOptions.tcp.noDelay) { @@ -53,7 +53,7 @@ void SetAsioSocketOptions(SilKit::Services::Logging::ILogger* logger, asio::ip:: void SetAsioSocketOptions(SilKit::Services::Logging::ILogger*, asio::local::stream_protocol::socket&, - const AsioSocketOptions&, std::error_code&) + const AsioSocketOptions&, std::error_code&) { // no local-domain specific options } diff --git a/SilKit/source/core/vasio/io/util/TracingMacros.hpp b/SilKit/source/core/vasio/io/util/TracingMacros.hpp index 74455700f..afde818c0 100644 --- a/SilKit/source/core/vasio/io/util/TracingMacros.hpp +++ b/SilKit/source/core/vasio/io/util/TracingMacros.hpp @@ -96,16 +96,16 @@ inline constexpr auto ExtractFileNameFromFileMacro(fmt::string_view s) -> fmt::s #ifdef SILKIT_ENABLE_TRACING_INSTRUMENTATION -# define DETAILS_VSILKIT_TRACE_EVENT(logger, object, ...) \ - ::VSilKit::TraceEvent(logger, ::VSilKit::Details::ExtractFileNameFromFileMacro(__FILE__), __LINE__, __func__, \ - object, __VA_ARGS__) +#define DETAILS_VSILKIT_TRACE_EVENT(logger, object, ...) \ + ::VSilKit::TraceEvent(logger, ::VSilKit::Details::ExtractFileNameFromFileMacro(__FILE__), __LINE__, __func__, \ + object, __VA_ARGS__) #else -# define DETAILS_VSILKIT_TRACE_EVENT(logger, object, ...) \ - do \ - { \ - } while (false) +#define DETAILS_VSILKIT_TRACE_EVENT(logger, object, ...) \ + do \ + { \ + } while (false) #endif diff --git a/SilKit/source/core/vasio/mock/MockVAsioPeer.hpp b/SilKit/source/core/vasio/mock/MockVAsioPeer.hpp index d9712d5ec..e3fd67310 100644 --- a/SilKit/source/core/vasio/mock/MockVAsioPeer.hpp +++ b/SilKit/source/core/vasio/mock/MockVAsioPeer.hpp @@ -32,8 +32,8 @@ struct MockVAsioPeer : IVAsioPeer MOCK_METHOD(void, SetInfo, (VAsioPeerInfo), (override)); MOCK_METHOD(std::string, GetRemoteAddress, (), (const, override)); MOCK_METHOD(std::string, GetLocalAddress, (), (const, override)); - MOCK_METHOD(void, SetSimulationName, (const std::string&), (override)); - MOCK_METHOD(const std::string&, GetSimulationName, (), (const, override)); + MOCK_METHOD(void, SetSimulationName, (const std::string &), (override)); + MOCK_METHOD(const std::string &, GetSimulationName, (), (const, override)); MOCK_METHOD(void, StartAsyncRead, (), (override)); MOCK_METHOD(void, Shutdown, (), (override)); MOCK_METHOD(void, SetProtocolVersion, (ProtocolVersion), (override)); diff --git a/SilKit/source/dashboard/Client/DashboardComponents.hpp b/SilKit/source/dashboard/Client/DashboardComponents.hpp index 3586a0e57..8767e6f9f 100644 --- a/SilKit/source/dashboard/Client/DashboardComponents.hpp +++ b/SilKit/source/dashboard/Client/DashboardComponents.hpp @@ -44,12 +44,13 @@ class DashboardComponents } public: - OATPP_CREATE_COMPONENT(std::shared_ptr, clientConnectionProvider) - ("DashboardComponents_clientConnectionProvider", [this]() -> std::shared_ptr { + ("DashboardComponents_clientConnectionProvider", + [this]() -> std::shared_ptr { auto connectionProvider = oatpp::network::tcp::client::ConnectionProvider::createShared({_host, _port}); - return oatpp::network::ClientConnectionPool::createShared(connectionProvider, 5, std::chrono::seconds(10), std::chrono::seconds(5)); - }()); + return oatpp::network::ClientConnectionPool::createShared(connectionProvider, 5, std::chrono::seconds(10), + std::chrono::seconds(5)); + }()); OATPP_CREATE_COMPONENT(std::shared_ptr, apiObjectMapper) ("DashboardComponents_apiObjectMapper", [] { @@ -57,7 +58,6 @@ class DashboardComponents objectMapper->getDeserializer()->getConfig()->allowUnknownFields = false; return objectMapper; }()); - }; } // namespace Dashboard diff --git a/SilKit/source/dashboard/Client/DashboardSystemApiClient.hpp b/SilKit/source/dashboard/Client/DashboardSystemApiClient.hpp index ab426e969..251e04d9b 100644 --- a/SilKit/source/dashboard/Client/DashboardSystemApiClient.hpp +++ b/SilKit/source/dashboard/Client/DashboardSystemApiClient.hpp @@ -45,53 +45,48 @@ class DashboardSystemApiClient : public oatpp::web::client::ApiClient // notify a simulation has been started // get a simulationId in return that can be used to send additional data API_CALL("POST", "system-service/v1.0/simulations", createSimulation, - BODY_DTO(Object, simulation)) + BODY_DTO(Object, simulation)) // notify a participant has been created for a given simulation API_CALL("PUT", "system-service/v1.0/simulations/{simulationId}/participants/{participantName}", - addParticipantToSimulation, PATH(UInt64, simulationId), PATH(String, participantName)) + addParticipantToSimulation, PATH(UInt64, simulationId), PATH(String, participantName)) // notify a participant has entered a new state for a given simulation API_CALL("POST", "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/statuses", - addParticipantStatusForSimulation, PATH(UInt64, simulationId), PATH(String, participantName), - BODY_DTO(Object, participantStatus)) + addParticipantStatusForSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + BODY_DTO(Object, participantStatus)) // notify a participant has created a CAN controller for a given simulation - API_CALL( - "PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/cancontrollers/{serviceId}", - addCanControllerForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), - PATH(UInt64, serviceId), BODY_DTO(Object, canController)) + API_CALL("PUT", + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/cancontrollers/{serviceId}", + addCanControllerForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(UInt64, serviceId), BODY_DTO(Object, canController)) // notify a participant has created an Ethernet controller for a given simulation API_CALL("PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/ethernetcontrollers/" - "{serviceId}", - addEthernetControllerForParticipantOfSimulation, PATH(UInt64, simulationId), - PATH(String, participantName), PATH(UInt64, serviceId), - BODY_DTO(Object, ethernetController)) + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/ethernetcontrollers/" + "{serviceId}", + addEthernetControllerForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(UInt64, serviceId), BODY_DTO(Object, ethernetController)) // notify a participant has created a FlexRay controller for a given simulation API_CALL("PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/flexraycontrollers/" - "{serviceId}", - addFlexrayControllerForParticipantOfSimulation, PATH(UInt64, simulationId), - PATH(String, participantName), PATH(UInt64, serviceId), - BODY_DTO(Object, flexrayController)) + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/flexraycontrollers/" + "{serviceId}", + addFlexrayControllerForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(UInt64, serviceId), BODY_DTO(Object, flexrayController)) // notify a participant has created a LIN controller for a given simulation - API_CALL( - "PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/lincontrollers/{serviceId}", - addLinControllerForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), - PATH(UInt64, serviceId), BODY_DTO(Object, linController)) + API_CALL("PUT", + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/lincontrollers/{serviceId}", + addLinControllerForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(UInt64, serviceId), BODY_DTO(Object, linController)) // notify a participant has created a data publisher for a given simulation - API_CALL( - "PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/datapublishers/{serviceId}", - addDataPublisherForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), - PATH(UInt64, serviceId), BODY_DTO(Object, dataPublisher)) + API_CALL("PUT", + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/datapublishers/{serviceId}", + addDataPublisherForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(UInt64, serviceId), BODY_DTO(Object, dataPublisher)) // notify a participant has created a data subscriber for a given simulation API_CALL( @@ -102,37 +97,36 @@ class DashboardSystemApiClient : public oatpp::web::client::ApiClient // notify a participant has created a data subscriber internal for a given simulation API_CALL("PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/" - "datasubscribers/{parentServiceId}/internals/{serviceId}", - addDataSubscriberInternalForParticipantOfSimulation, PATH(UInt64, simulationId), - PATH(String, participantName), PATH(String, parentServiceId), PATH(UInt64, serviceId), - BODY_DTO(Object, dataSubscriberInternal)) + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/" + "datasubscribers/{parentServiceId}/internals/{serviceId}", + addDataSubscriberInternalForParticipantOfSimulation, PATH(UInt64, simulationId), + PATH(String, participantName), PATH(String, parentServiceId), PATH(UInt64, serviceId), + BODY_DTO(Object, dataSubscriberInternal)) // notify a participant has created a Rpc client for a given simulation - API_CALL( - "PUT", "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/rpcclients/{serviceId}", - addRpcClientForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), - PATH(UInt64, serviceId), BODY_DTO(Object, rpcClient)) + API_CALL("PUT", + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/rpcclients/{serviceId}", + addRpcClientForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(UInt64, serviceId), BODY_DTO(Object, rpcClient)) // notify a participant has created a rpc server for a given simulation - API_CALL( - "PUT", "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/rpcservers/{serviceId}", - addRpcServerForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), - PATH(UInt64, serviceId), BODY_DTO(Object, rpcServer)) + API_CALL("PUT", + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/rpcservers/{serviceId}", + addRpcServerForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(UInt64, serviceId), BODY_DTO(Object, rpcServer)) // notify a participant has created a rpc server internal for a given simulation API_CALL("PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/rpcservers/" - "{parentServiceId}/internals/{serviceId}", - addRpcServerInternalForParticipantOfSimulation, PATH(UInt64, simulationId), - PATH(String, participantName), PATH(String, parentServiceId), PATH(UInt64, serviceId), - BODY_DTO(Object, rpcServerInternal)) + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/rpcservers/" + "{parentServiceId}/internals/{serviceId}", + addRpcServerInternalForParticipantOfSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(String, parentServiceId), PATH(UInt64, serviceId), BODY_DTO(Object, rpcServerInternal)) // notify a simulated CAN network has been created for a given simulation - API_CALL( - "PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/cannetworks/{networkName}", - addCanNetworkToSimulation, PATH(UInt64, simulationId), PATH(String, participantName), PATH(String, networkName)) + API_CALL("PUT", + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/cannetworks/{networkName}", + addCanNetworkToSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(String, networkName)) // notify a simulated Ethernet network has been created for a given simulation API_CALL( @@ -149,19 +143,18 @@ class DashboardSystemApiClient : public oatpp::web::client::ApiClient PATH(String, networkName)) // notify a simulated LIN network has been created for a given simulation - API_CALL( - "PUT", - "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/linnetworks/{networkName}", - addLinNetworkToSimulation, PATH(UInt64, simulationId), PATH(String, participantName), PATH(String, networkName)) + API_CALL("PUT", + "system-service/v1.0/simulations/{simulationId}/participants/{participantName}/linnetworks/{networkName}", + addLinNetworkToSimulation, PATH(UInt64, simulationId), PATH(String, participantName), + PATH(String, networkName)) // notify the system has entered a new state for a given simulation - API_CALL("PUT", "system-service/v1.0/simulations/{simulationId}/system/status", - updateSystemStatusForSimulation, PATH(UInt64, simulationId), - BODY_DTO(Object, systemStatus)) + API_CALL("PUT", "system-service/v1.0/simulations/{simulationId}/system/status", updateSystemStatusForSimulation, + PATH(UInt64, simulationId), BODY_DTO(Object, systemStatus)) // notify the end of a simulation - API_CALL("POST", "system-service/v1.0/simulations/{simulationId}", setSimulationEnd, - PATH(UInt64, simulationId), BODY_DTO(Object, simulation)) + API_CALL("POST", "system-service/v1.0/simulations/{simulationId}", setSimulationEnd, PATH(UInt64, simulationId), + BODY_DTO(Object, simulation)) }; } // namespace Dashboard diff --git a/SilKit/source/dashboard/Client/DashboardSystemServiceClient.cpp b/SilKit/source/dashboard/Client/DashboardSystemServiceClient.cpp index 51f569c26..6fd2da9a3 100644 --- a/SilKit/source/dashboard/Client/DashboardSystemServiceClient.cpp +++ b/SilKit/source/dashboard/Client/DashboardSystemServiceClient.cpp @@ -39,9 +39,7 @@ DashboardSystemServiceClient::DashboardSystemServiceClient( { } -DashboardSystemServiceClient::~DashboardSystemServiceClient() -{ -} +DashboardSystemServiceClient::~DashboardSystemServiceClient() {} oatpp::Object DashboardSystemServiceClient::CreateSimulation( oatpp::Object simulation) @@ -210,7 +208,8 @@ void DashboardSystemServiceClient::SetSimulationEnd(oatpp::UInt64 simulationId, Log(response, "setting simulation end"); } -void DashboardSystemServiceClient::Log(std::shared_ptr response, const std::string& message) +void DashboardSystemServiceClient::Log(std::shared_ptr response, + const std::string& message) { if (!response) { diff --git a/SilKit/source/dashboard/Client/Mocks/MockBodyDecoder.hpp b/SilKit/source/dashboard/Client/Mocks/MockBodyDecoder.hpp index 8e93614a4..a59a7999f 100644 --- a/SilKit/source/dashboard/Client/Mocks/MockBodyDecoder.hpp +++ b/SilKit/source/dashboard/Client/Mocks/MockBodyDecoder.hpp @@ -30,8 +30,15 @@ namespace Dashboard { class MockBodyDecoder : public oatpp::web::protocol::http::incoming::BodyDecoder { public: - MOCK_METHOD(void, decode, (const oatpp::web::protocol::http::Headers &, oatpp::data::stream::InputStream *, oatpp::data ::stream::WriteCallback *, oatpp::data::stream::IOStream *), (const, override)); - MOCK_METHOD(oatpp::async::CoroutineStarter, decodeAsync, (const oatpp::web::protocol::http::Headers &, const std::shared_ptr &, const std::shared_ptr &, const std::shared_ptr &), (const, override)); + MOCK_METHOD(void, decode, + (const oatpp::web::protocol::http::Headers &, oatpp::data::stream::InputStream *, + oatpp::data ::stream::WriteCallback *, oatpp::data::stream::IOStream *), + (const, override)); + MOCK_METHOD(oatpp::async::CoroutineStarter, decodeAsync, + (const oatpp::web::protocol::http::Headers &, const std::shared_ptr &, + const std::shared_ptr &, + const std::shared_ptr &), + (const, override)); }; } // namespace Dashboard } // namespace SilKit diff --git a/SilKit/source/dashboard/Client/Mocks/MockDashboardSystemApiClient.hpp b/SilKit/source/dashboard/Client/Mocks/MockDashboardSystemApiClient.hpp index 2f786b5c6..528a28887 100644 --- a/SilKit/source/dashboard/Client/Mocks/MockDashboardSystemApiClient.hpp +++ b/SilKit/source/dashboard/Client/Mocks/MockDashboardSystemApiClient.hpp @@ -34,12 +34,27 @@ class MockDashboardSystemApiClient : public DashboardSystemApiClient public: MockDashboardSystemApiClient(const std::shared_ptr& objectMapper) - : DashboardSystemApiClient(std::shared_ptr(nullptr), objectMapper){} + : DashboardSystemApiClient(std::shared_ptr(nullptr), objectMapper) + { + } MOCK_METHOD(std::shared_ptr, getConnection, (), (override)); - MOCK_METHOD(oatpp::async::CoroutineStarterForResult&>, getConnectionAsync, (), (override)); - MOCK_METHOD(std::shared_ptr, executeRequest, (const oatpp::String&, const StringTemplate&, const Headers&, (const std::unordered_map&), (const std::unordered_map&), const std::shared_ptr&, const std::shared_ptr&), (override)); - MOCK_METHOD(oatpp::async::CoroutineStarterForResult&>, executeRequestAsync, (const oatpp::String&, const StringTemplate&, const Headers&, (const std::unordered_map&), (const std::unordered_map&), const std::shared_ptr&, const std::shared_ptr&), (override)); + MOCK_METHOD(oatpp::async::CoroutineStarterForResult&>, + getConnectionAsync, (), (override)); + MOCK_METHOD(std::shared_ptr, executeRequest, + (const oatpp::String&, const StringTemplate&, const Headers&, + (const std::unordered_map&), + (const std::unordered_map&), + const std::shared_ptr&, + const std::shared_ptr&), + (override)); + MOCK_METHOD(oatpp::async::CoroutineStarterForResult&>, executeRequestAsync, + (const oatpp::String&, const StringTemplate&, const Headers&, + (const std::unordered_map&), + (const std::unordered_map&), + const std::shared_ptr&, + const std::shared_ptr&), + (override)); }; } // namespace Dashboard } // namespace SilKit diff --git a/SilKit/source/dashboard/Client/Mocks/MockDashboardSystemServiceClient.hpp b/SilKit/source/dashboard/Client/Mocks/MockDashboardSystemServiceClient.hpp index 8f6aedba8..d470de175 100644 --- a/SilKit/source/dashboard/Client/Mocks/MockDashboardSystemServiceClient.hpp +++ b/SilKit/source/dashboard/Client/Mocks/MockDashboardSystemServiceClient.hpp @@ -30,13 +30,10 @@ namespace Dashboard { class MockDashboardSystemServiceClient : public IDashboardSystemServiceClient { public: - MockDashboardSystemServiceClient() - { - } + MockDashboardSystemServiceClient() {} MOCK_METHOD(oatpp::Object, CreateSimulation, - (oatpp::Object), - (override)); + (oatpp::Object), (override)); MOCK_METHOD(void, AddParticipantToSimulation, (oatpp::UInt64, oatpp::String), (override)); diff --git a/SilKit/source/dashboard/Client/Mocks/MockObjectMapper.hpp b/SilKit/source/dashboard/Client/Mocks/MockObjectMapper.hpp index bdb633008..5160cbac2 100644 --- a/SilKit/source/dashboard/Client/Mocks/MockObjectMapper.hpp +++ b/SilKit/source/dashboard/Client/Mocks/MockObjectMapper.hpp @@ -30,7 +30,10 @@ namespace Dashboard { class MockObjectMapper : public oatpp::data::mapping::ObjectMapper { public: - explicit MockObjectMapper(const Info& info) : ObjectMapper(info) {} + explicit MockObjectMapper(const Info& info) + : ObjectMapper(info) + { + } virtual ~MockObjectMapper() = default; diff --git a/SilKit/source/dashboard/Client/Test_DashboardSystemServiceClient.cpp b/SilKit/source/dashboard/Client/Test_DashboardSystemServiceClient.cpp index acfd33acf..678d71e4f 100644 --- a/SilKit/source/dashboard/Client/Test_DashboardSystemServiceClient.cpp +++ b/SilKit/source/dashboard/Client/Test_DashboardSystemServiceClient.cpp @@ -21,7 +21,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4702) +#pragma warning(disable : 4702) #endif #include "gmock/gmock.h" @@ -77,8 +77,8 @@ class Test_DashboardSystemServiceClient : public Test _nullInput, _mockBodyDecoder); EXPECT_CALL(*_mockDashboardSystemApiClient, executeRequest) .WillOnce(DoAll(WithArgs<0, 1, 3>([OnRequest](auto currentMethod, auto pathTemplate, auto map) { - OnRequest(currentMethod, pathTemplate, map); - }), + OnRequest(currentMethod, pathTemplate, map); + }), Return(response))); } @@ -99,9 +99,9 @@ TEST_F(Test_DashboardSystemServiceClient, CreateSimulation_Success) oatpp::String actualMethod; SetupExecuteRequest(Status::CODE_201, [&actualPath, &actualMethod](auto currentMethod, auto pathTemplate, auto map) { - actualMethod = currentMethod; - actualPath = pathTemplate.format(map); - }); + actualMethod = currentMethod; + actualPath = pathTemplate.format(map); + }); EXPECT_CALL(*_mockBodyDecoder, decode); auto expectedResponse = SimulationCreationResponseDto::createShared(); expectedResponse->id = 123; @@ -130,9 +130,9 @@ TEST_F(Test_DashboardSystemServiceClient, CreateSimulation_Failure) oatpp::String actualMethod; SetupExecuteRequest(Status::CODE_500, [&actualPath, &actualMethod](auto currentMethod, auto pathTemplate, auto map) { - actualMethod = currentMethod; - actualPath = pathTemplate.format(map); - }); + actualMethod = currentMethod; + actualPath = pathTemplate.format(map); + }); EXPECT_CALL(_dummyLogger, Log(Services::Logging::Level::Error, "Dashboard: creating simulation returned 500")); // Act @@ -157,9 +157,9 @@ TEST_F(Test_DashboardSystemServiceClient, SetSimulationEnd_Success) oatpp::String actualMethod; SetupExecuteRequest(Status::CODE_204, [&actualPath, &actualMethod](auto currentMethod, auto pathTemplate, auto map) { - actualMethod = currentMethod; - actualPath = pathTemplate.format(map); - }); + actualMethod = currentMethod; + actualPath = pathTemplate.format(map); + }); EXPECT_CALL(_dummyLogger, Log(Services::Logging::Level::Debug, "Dashboard: setting simulation end returned 204")); // Act @@ -183,9 +183,9 @@ TEST_F(Test_DashboardSystemServiceClient, SetSimulationEnd_Failure) oatpp::String actualMethod; SetupExecuteRequest(Status::CODE_500, [&actualPath, &actualMethod](auto currentMethod, auto pathTemplate, auto map) { - actualMethod = currentMethod; - actualPath = pathTemplate.format(map); - }); + actualMethod = currentMethod; + actualPath = pathTemplate.format(map); + }); EXPECT_CALL(_dummyLogger, Log(Services::Logging::Level::Error, "Dashboard: setting simulation end returned 500")); // Act diff --git a/SilKit/source/dashboard/CreateDashboard.cpp b/SilKit/source/dashboard/CreateDashboard.cpp old mode 100755 new mode 100644 index 4d2c6de0d..598bbe9e0 --- a/SilKit/source/dashboard/CreateDashboard.cpp +++ b/SilKit/source/dashboard/CreateDashboard.cpp @@ -34,8 +34,8 @@ namespace SilKit { namespace Dashboard { auto CreateDashboard(std::shared_ptr participantConfig, - const std::string& registryUri, const std::string& dashboardUri) - -> std::unique_ptr + const std::string& registryUri, + const std::string& dashboardUri) -> std::unique_ptr { return std::make_unique(participantConfig, registryUri, dashboardUri); } @@ -56,15 +56,13 @@ auto RunDashboardTest(std::shared_ptr creationTimeout, updateTimeout); runner.addController(controller); - runner.run( - [testCode = std::move(testCode), participantConfig, ®istryUri, controller]() { - auto dashboard = std::make_unique(participantConfig, registryUri); - SILKIT_UNUSED_ARG(dashboard); + runner.run([testCode = std::move(testCode), participantConfig, ®istryUri, controller]() { + auto dashboard = std::make_unique(participantConfig, registryUri); + SILKIT_UNUSED_ARG(dashboard); - testCode(); - controller->WaitSimulationsFinished(); - }, - std::chrono::seconds(30)); + testCode(); + controller->WaitSimulationsFinished(); + }, std::chrono::seconds(30)); testResult.dataBySimulation = controller->GetData(); testResult.allSimulationsFinished = controller->AllSimulationsFinished(); diff --git a/SilKit/source/dashboard/CreateDashboard.hpp b/SilKit/source/dashboard/CreateDashboard.hpp old mode 100755 new mode 100644 index 5b6178cfa..83c3d7663 --- a/SilKit/source/dashboard/CreateDashboard.hpp +++ b/SilKit/source/dashboard/CreateDashboard.hpp @@ -33,15 +33,15 @@ namespace SilKit { namespace Dashboard { auto CreateDashboard(std::shared_ptr participantConfig, - const std::string& registryUri, const std::string& dashboardUri) - -> std::unique_ptr; + const std::string& registryUri, + const std::string& dashboardUri) -> std::unique_ptr; //! returns information about simulation, participants and networks auto RunDashboardTest(std::shared_ptr participantConfig, - const std::string& registryUri, const std::string& dashboardUri, - std::function testCode, uint64_t expectedSimulationsCount = 1, - std::chrono::seconds creationTimeout = std::chrono::seconds{0}, - std::chrono::seconds updateTimeout = std::chrono::seconds{0}) -> TestResult; + const std::string& registryUri, const std::string& dashboardUri, std::function testCode, + uint64_t expectedSimulationsCount = 1, + std::chrono::seconds creationTimeout = std::chrono::seconds{0}, + std::chrono::seconds updateTimeout = std::chrono::seconds{0}) -> TestResult; } // namespace Dashboard } // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/dashboard/Dashboard.hpp b/SilKit/source/dashboard/Dashboard.hpp old mode 100755 new mode 100644 index 61db6fd73..c3ab5533b --- a/SilKit/source/dashboard/Dashboard.hpp +++ b/SilKit/source/dashboard/Dashboard.hpp @@ -30,7 +30,7 @@ namespace Dashboard { class DashboardRetryPolicy; -class Dashboard +class Dashboard { public: Dashboard(std::shared_ptr participantConfig, diff --git a/SilKit/source/dashboard/DashboardInstance.cpp b/SilKit/source/dashboard/DashboardInstance.cpp index 3f11400eb..d0e4b3859 100644 --- a/SilKit/source/dashboard/DashboardInstance.cpp +++ b/SilKit/source/dashboard/DashboardInstance.cpp @@ -54,6 +54,11 @@ DashboardInstance::DashboardInstance() DashboardInstance::~DashboardInstance() { + if (_retryPolicy != nullptr) + { + _retryPolicy->AbortAllRetries(); + } + try { _eventQueueWorkerThreadAbort.set_value(); @@ -63,6 +68,11 @@ DashboardInstance::~DashboardInstance() // ignored } + if (_silKitEventQueue != nullptr) + { + _silKitEventQueue->Stop(); + } + if (_eventQueueWorkerThread.joinable()) { _eventQueueWorkerThread.join(); @@ -83,10 +93,10 @@ void DashboardInstance::SetupDashboardConnection(std::string const &dashboardUri _objectMapper = OATPP_GET_COMPONENT(std::shared_ptr); - auto retryPolicy = std::make_shared(3); + _retryPolicy = std::make_shared(3); OATPP_COMPONENT(std::shared_ptr, connectionProvider); - auto requestExecutor = oatpp::web::client::HttpRequestExecutor::createShared(connectionProvider, retryPolicy); + auto requestExecutor = oatpp::web::client::HttpRequestExecutor::createShared(connectionProvider, _retryPolicy); _apiClient = SilKit::Dashboard::DashboardSystemApiClient::createShared(requestExecutor, _objectMapper); _silKitToOatppMapper = std::make_shared(); @@ -98,8 +108,6 @@ void DashboardInstance::SetupDashboardConnection(std::string const &dashboardUri std::make_shared(_logger, serviceClient, _silKitToOatppMapper); _silKitEventQueue = std::make_shared(); - retryPolicy->AbortAllRetries(); // ??? - RunEventQueueWorkerThread(); } @@ -144,6 +152,13 @@ struct EventQueueWorkerThread const auto &simulationStart = event.GetSimulationStart(); const auto simulationId = eventHandler->OnSimulationStart(simulationStart.connectUri, simulationStart.time); + + if (simulationId == 0) + { + Log::Warn(logger, "Dashboard: Simulation {} could not be created", event.GetSimulationName()); + continue; + } + simulationNameToId.emplace(event.GetSimulationName(), simulationId); continue; diff --git a/SilKit/source/dashboard/DashboardInstance.hpp b/SilKit/source/dashboard/DashboardInstance.hpp index 444e984a7..5626ae5c2 100644 --- a/SilKit/source/dashboard/DashboardInstance.hpp +++ b/SilKit/source/dashboard/DashboardInstance.hpp @@ -16,6 +16,7 @@ #include "Client/DashboardSystemApiClient.hpp" #include "Service/ISilKitToOatppMapper.hpp" #include "SystemStateTracker.hpp" +#include "DashboardRetryPolicy.hpp" #include #include @@ -76,6 +77,7 @@ class DashboardInstance final std::unique_ptr _registryUri; std::shared_ptr _objectMapper; + std::shared_ptr _retryPolicy; std::shared_ptr _apiClient; std::shared_ptr _silKitToOatppMapper; std::shared_ptr _silKitEventHandler; diff --git a/SilKit/source/dashboard/DashboardParticipant.cpp b/SilKit/source/dashboard/DashboardParticipant.cpp index ed7967d65..282ecb5fb 100644 --- a/SilKit/source/dashboard/DashboardParticipant.cpp +++ b/SilKit/source/dashboard/DashboardParticipant.cpp @@ -57,18 +57,14 @@ DashboardParticipant::DashboardParticipant(std::shared_ptr(); _cachingEventHandler = std::make_unique(registryUri, _logger, eventHandler, eventQueue); - _systemMonitor->SetParticipantConnectedHandler([this](auto&& participantInformation) { - OnParticipantConnected(participantInformation); - }); - _systemMonitor->SetParticipantDisconnectedHandler([this](auto&& participantInformation) { - OnParticipantDisconnected(participantInformation); - }); - _participantStatusHandlerId = _systemMonitor->AddParticipantStatusHandler([this](auto&& participantStatus) { - OnParticipantStatusChanged(participantStatus); - }); - _systemStateHandlerId = _systemMonitor->AddSystemStateHandler([this](auto&& systemState) { - OnSystemStateChanged(systemState); - }); + _systemMonitor->SetParticipantConnectedHandler( + [this](auto&& participantInformation) { OnParticipantConnected(participantInformation); }); + _systemMonitor->SetParticipantDisconnectedHandler( + [this](auto&& participantInformation) { OnParticipantDisconnected(participantInformation); }); + _participantStatusHandlerId = _systemMonitor->AddParticipantStatusHandler( + [this](auto&& participantStatus) { OnParticipantStatusChanged(participantStatus); }); + _systemStateHandlerId = + _systemMonitor->AddSystemStateHandler([this](auto&& systemState) { OnSystemStateChanged(systemState); }); _serviceDiscovery->RegisterServiceDiscoveryHandler([this](auto&& discoveryType, auto&& serviceDescriptor) { OnServiceDiscoveryEvent(discoveryType, serviceDescriptor); }); diff --git a/SilKit/source/dashboard/DashboardParticipant.hpp b/SilKit/source/dashboard/DashboardParticipant.hpp index 0dc412caf..8b3540255 100644 --- a/SilKit/source/dashboard/DashboardParticipant.hpp +++ b/SilKit/source/dashboard/DashboardParticipant.hpp @@ -38,7 +38,7 @@ namespace Core { class IParticipantInternal; namespace Discovery { class IServiceDiscovery; -} // Discovery +} // namespace Discovery } // namespace Core namespace Config { class IParticipantConfiguration; @@ -48,7 +48,7 @@ class IParticipantConfiguration; namespace SilKit { namespace Dashboard { -class DashboardParticipant +class DashboardParticipant { public: DashboardParticipant(std::shared_ptr participantConfig, @@ -70,7 +70,7 @@ class DashboardParticipant void OnParticipantStatusChanged(const Services::Orchestration::ParticipantStatus& participantStatus); void OnSystemStateChanged(Services::Orchestration::SystemState systemState); void OnServiceDiscoveryEvent(Core::Discovery::ServiceDiscoveryEvent::Type discoveryType, - const Core::ServiceDescriptor& serviceDescriptor); + const Core::ServiceDescriptor& serviceDescriptor); bool LastParticipantDisconnected( const Services::Orchestration::ParticipantConnectionInformation& participantInformation); bool NoParticipantConnected(); diff --git a/SilKit/source/dashboard/DashboardUnavailable.cpp b/SilKit/source/dashboard/DashboardUnavailable.cpp index 53b5da4ed..7123a33ff 100644 --- a/SilKit/source/dashboard/DashboardUnavailable.cpp +++ b/SilKit/source/dashboard/DashboardUnavailable.cpp @@ -27,8 +27,8 @@ namespace SilKit { namespace Dashboard { auto CreateDashboard(std::shared_ptr participantConfig, - const std::string& registryUri, const std::string& dashboardUri) - -> std::unique_ptr + const std::string& registryUri, + const std::string& dashboardUri) -> std::unique_ptr { SILKIT_UNUSED_ARG(participantConfig); SILKIT_UNUSED_ARG(registryUri); @@ -37,8 +37,8 @@ auto CreateDashboard(std::shared_ptr } auto RunDashboardTest(std::shared_ptr participantConfig, - const std::string& registryUri, const std::string& dashboardUri, std::function testCode) - -> TestResult + const std::string& registryUri, const std::string& dashboardUri, + std::function testCode) -> TestResult { SILKIT_UNUSED_ARG(participantConfig); SILKIT_UNUSED_ARG(registryUri); diff --git a/SilKit/source/dashboard/Dto/DataPublisherDto.hpp b/SilKit/source/dashboard/Dto/DataPublisherDto.hpp index 3b98c269c..fab768210 100644 --- a/SilKit/source/dashboard/Dto/DataPublisherDto.hpp +++ b/SilKit/source/dashboard/Dto/DataPublisherDto.hpp @@ -32,13 +32,22 @@ class DataPublisherDto : public oatpp::DTO { DTO_INIT(DataPublisherDto, DTO) - DTO_FIELD_INFO(name) { info->description = "Name of the service"; } + DTO_FIELD_INFO(name) + { + info->description = "Name of the service"; + } DTO_FIELD(String, name); - DTO_FIELD_INFO(networkName) { info->description = "Name of the network"; } + DTO_FIELD_INFO(networkName) + { + info->description = "Name of the network"; + } DTO_FIELD(String, networkName); - DTO_FIELD_INFO(spec) { info->description = "Data spec"; } + DTO_FIELD_INFO(spec) + { + info->description = "Data spec"; + } DTO_FIELD(Object, spec); }; diff --git a/SilKit/source/dashboard/Dto/DataSpecDto.hpp b/SilKit/source/dashboard/Dto/DataSpecDto.hpp index 3726b85b8..2f91004cd 100644 --- a/SilKit/source/dashboard/Dto/DataSpecDto.hpp +++ b/SilKit/source/dashboard/Dto/DataSpecDto.hpp @@ -32,13 +32,22 @@ class DataSpecDto : public oatpp::DTO { DTO_INIT(DataSpecDto, DTO) - DTO_FIELD_INFO(topic) { info->description = "Topic"; } + DTO_FIELD_INFO(topic) + { + info->description = "Topic"; + } DTO_FIELD(String, topic); - DTO_FIELD_INFO(mediaType) { info->description = "Media type"; } + DTO_FIELD_INFO(mediaType) + { + info->description = "Media type"; + } DTO_FIELD(String, mediaType); - DTO_FIELD_INFO(labels) { info->description = "Labels"; } + DTO_FIELD_INFO(labels) + { + info->description = "Labels"; + } DTO_FIELD(Vector>, labels); }; diff --git a/SilKit/source/dashboard/Dto/DataSubscriberDto.hpp b/SilKit/source/dashboard/Dto/DataSubscriberDto.hpp index 5e907710d..7bf006fee 100644 --- a/SilKit/source/dashboard/Dto/DataSubscriberDto.hpp +++ b/SilKit/source/dashboard/Dto/DataSubscriberDto.hpp @@ -32,10 +32,16 @@ class DataSubscriberDto : public oatpp::DTO { DTO_INIT(DataSubscriberDto, DTO) - DTO_FIELD_INFO(name) { info->description = "Name of the service"; } + DTO_FIELD_INFO(name) + { + info->description = "Name of the service"; + } DTO_FIELD(String, name); - DTO_FIELD_INFO(spec) { info->description = "Data spec"; } + DTO_FIELD_INFO(spec) + { + info->description = "Data spec"; + } DTO_FIELD(Object, spec); }; diff --git a/SilKit/source/dashboard/Dto/MatchingLabelDto.hpp b/SilKit/source/dashboard/Dto/MatchingLabelDto.hpp index a343e7bee..a6c030df2 100644 --- a/SilKit/source/dashboard/Dto/MatchingLabelDto.hpp +++ b/SilKit/source/dashboard/Dto/MatchingLabelDto.hpp @@ -36,13 +36,22 @@ class MatchingLabelDto : public oatpp::DTO { DTO_INIT(MatchingLabelDto, DTO) - DTO_FIELD_INFO(key) { info->description = "Key of the label"; } + DTO_FIELD_INFO(key) + { + info->description = "Key of the label"; + } DTO_FIELD(String, key); - DTO_FIELD_INFO(value) { info->description = "Value of the label"; } + DTO_FIELD_INFO(value) + { + info->description = "Value of the label"; + } DTO_FIELD(String, value); - DTO_FIELD_INFO(kind) { info->description = "Kind of the label"; } + DTO_FIELD_INFO(kind) + { + info->description = "Kind of the label"; + } DTO_FIELD(Enum::AsString, kind); }; diff --git a/SilKit/source/dashboard/Dto/ParticipantStatusDto.hpp b/SilKit/source/dashboard/Dto/ParticipantStatusDto.hpp index fd77743a2..ad9e7ef1c 100644 --- a/SilKit/source/dashboard/Dto/ParticipantStatusDto.hpp +++ b/SilKit/source/dashboard/Dto/ParticipantStatusDto.hpp @@ -48,13 +48,22 @@ class ParticipantStatusDto : public oatpp::DTO { DTO_INIT(ParticipantStatusDto, DTO) - DTO_FIELD_INFO(state) { info->description = "Name of the state"; } + DTO_FIELD_INFO(state) + { + info->description = "Name of the state"; + } DTO_FIELD(Enum::AsString, state); - DTO_FIELD_INFO(enterReason) { info->description = "Reason for entering the state"; } + DTO_FIELD_INFO(enterReason) + { + info->description = "Reason for entering the state"; + } DTO_FIELD(String, enterReason); - DTO_FIELD_INFO(enterTime) { info->description = "Time when state got entered"; } + DTO_FIELD_INFO(enterTime) + { + info->description = "Time when state got entered"; + } DTO_FIELD(UInt64, enterTime); }; diff --git a/SilKit/source/dashboard/Dto/RpcClientDto.hpp b/SilKit/source/dashboard/Dto/RpcClientDto.hpp index c41dfbda8..7d259883b 100644 --- a/SilKit/source/dashboard/Dto/RpcClientDto.hpp +++ b/SilKit/source/dashboard/Dto/RpcClientDto.hpp @@ -32,13 +32,22 @@ class RpcClientDto : public oatpp::DTO { DTO_INIT(RpcClientDto, DTO) - DTO_FIELD_INFO(name) { info->description = "Name of the service"; } + DTO_FIELD_INFO(name) + { + info->description = "Name of the service"; + } DTO_FIELD(String, name); - DTO_FIELD_INFO(networkName) { info->description = "Name of the network"; } + DTO_FIELD_INFO(networkName) + { + info->description = "Name of the network"; + } DTO_FIELD(String, networkName); - DTO_FIELD_INFO(spec) { info->description = "Rpc spec"; } + DTO_FIELD_INFO(spec) + { + info->description = "Rpc spec"; + } DTO_FIELD(Object, spec); }; diff --git a/SilKit/source/dashboard/Dto/RpcServerDto.hpp b/SilKit/source/dashboard/Dto/RpcServerDto.hpp index 20f32d10a..d91acbafe 100644 --- a/SilKit/source/dashboard/Dto/RpcServerDto.hpp +++ b/SilKit/source/dashboard/Dto/RpcServerDto.hpp @@ -32,10 +32,16 @@ class RpcServerDto : public oatpp::DTO { DTO_INIT(RpcServerDto, DTO) - DTO_FIELD_INFO(name) { info->description = "Name of the service"; } + DTO_FIELD_INFO(name) + { + info->description = "Name of the service"; + } DTO_FIELD(String, name); - DTO_FIELD_INFO(spec) { info->description = "Rpc spec"; } + DTO_FIELD_INFO(spec) + { + info->description = "Rpc spec"; + } DTO_FIELD(Object, spec); }; diff --git a/SilKit/source/dashboard/Dto/RpcSpecDto.hpp b/SilKit/source/dashboard/Dto/RpcSpecDto.hpp index 21c2d47f4..ebecd84a9 100644 --- a/SilKit/source/dashboard/Dto/RpcSpecDto.hpp +++ b/SilKit/source/dashboard/Dto/RpcSpecDto.hpp @@ -32,13 +32,22 @@ class RpcSpecDto : public oatpp::DTO { DTO_INIT(RpcSpecDto, DTO) - DTO_FIELD_INFO(functionName) { info->description = "Function name"; } + DTO_FIELD_INFO(functionName) + { + info->description = "Function name"; + } DTO_FIELD(String, functionName); - DTO_FIELD_INFO(mediaType) { info->description = "Media type"; } + DTO_FIELD_INFO(mediaType) + { + info->description = "Media type"; + } DTO_FIELD(String, mediaType); - DTO_FIELD_INFO(labels) { info->description = "Labels"; } + DTO_FIELD_INFO(labels) + { + info->description = "Labels"; + } DTO_FIELD(Vector>, labels); }; diff --git a/SilKit/source/dashboard/Dto/ServiceDto.hpp b/SilKit/source/dashboard/Dto/ServiceDto.hpp index 091104492..b70731e9d 100644 --- a/SilKit/source/dashboard/Dto/ServiceDto.hpp +++ b/SilKit/source/dashboard/Dto/ServiceDto.hpp @@ -32,10 +32,16 @@ class ServiceDto : public oatpp::DTO { DTO_INIT(ServiceDto, DTO) - DTO_FIELD_INFO(name) { info->description = "Name of the service"; } + DTO_FIELD_INFO(name) + { + info->description = "Name of the service"; + } DTO_FIELD(String, name); - DTO_FIELD_INFO(networkName) { info->description = "Name of the network"; } + DTO_FIELD_INFO(networkName) + { + info->description = "Name of the network"; + } DTO_FIELD(String, networkName); }; diff --git a/SilKit/source/dashboard/Dto/SimulationConfigurationDto.hpp b/SilKit/source/dashboard/Dto/SimulationConfigurationDto.hpp index 4a89830d5..3b98c4264 100644 --- a/SilKit/source/dashboard/Dto/SimulationConfigurationDto.hpp +++ b/SilKit/source/dashboard/Dto/SimulationConfigurationDto.hpp @@ -32,11 +32,14 @@ class SimulationConfigurationDto : public oatpp::DTO { DTO_INIT(SimulationConfigurationDto, DTO) - DTO_FIELD_INFO(connectUri) { info->description = "Connect URI"; } + DTO_FIELD_INFO(connectUri) + { + info->description = "Connect URI"; + } DTO_FIELD(String, connectUri); }; -} // namespace Dashboard} +} // namespace Dashboard } // namespace SilKit #include OATPP_CODEGEN_END(DTO) \ No newline at end of file diff --git a/SilKit/source/dashboard/Dto/SimulationCreationRequestDto.hpp b/SilKit/source/dashboard/Dto/SimulationCreationRequestDto.hpp index ff9bf7656..590487f39 100644 --- a/SilKit/source/dashboard/Dto/SimulationCreationRequestDto.hpp +++ b/SilKit/source/dashboard/Dto/SimulationCreationRequestDto.hpp @@ -32,10 +32,16 @@ class SimulationCreationRequestDto : public oatpp::DTO { DTO_INIT(SimulationCreationRequestDto, DTO) - DTO_FIELD_INFO(started) { info->description = "Time when simulation started"; } + DTO_FIELD_INFO(started) + { + info->description = "Time when simulation started"; + } DTO_FIELD(UInt64, started); - DTO_FIELD_INFO(configuration) { info->description = "Configuration of the simulation"; } + DTO_FIELD_INFO(configuration) + { + info->description = "Configuration of the simulation"; + } DTO_FIELD(Object, configuration); }; diff --git a/SilKit/source/dashboard/Dto/SimulationCreationResponseDto.hpp b/SilKit/source/dashboard/Dto/SimulationCreationResponseDto.hpp index fd94bc143..d83a5f6b1 100644 --- a/SilKit/source/dashboard/Dto/SimulationCreationResponseDto.hpp +++ b/SilKit/source/dashboard/Dto/SimulationCreationResponseDto.hpp @@ -32,11 +32,14 @@ class SimulationCreationResponseDto : public oatpp::DTO { DTO_INIT(SimulationCreationResponseDto, DTO) - DTO_FIELD_INFO(id) { info->description = "Id"; } + DTO_FIELD_INFO(id) + { + info->description = "Id"; + } DTO_FIELD(UInt64, id); }; -} // namespace Dashboard} +} // namespace Dashboard } // namespace SilKit #include OATPP_CODEGEN_END(DTO) \ No newline at end of file diff --git a/SilKit/source/dashboard/Dto/SimulationEndDto.hpp b/SilKit/source/dashboard/Dto/SimulationEndDto.hpp index fa64a301a..15b525371 100644 --- a/SilKit/source/dashboard/Dto/SimulationEndDto.hpp +++ b/SilKit/source/dashboard/Dto/SimulationEndDto.hpp @@ -32,7 +32,10 @@ class SimulationEndDto : public oatpp::DTO { DTO_INIT(SimulationEndDto, DTO) - DTO_FIELD_INFO(stopped) { info->description = "Time when simulation ended"; } + DTO_FIELD_INFO(stopped) + { + info->description = "Time when simulation ended"; + } DTO_FIELD(UInt64, stopped); }; diff --git a/SilKit/source/dashboard/Dto/SystemStatusDto.hpp b/SilKit/source/dashboard/Dto/SystemStatusDto.hpp index bab65eb7f..a1ae3f602 100644 --- a/SilKit/source/dashboard/Dto/SystemStatusDto.hpp +++ b/SilKit/source/dashboard/Dto/SystemStatusDto.hpp @@ -48,7 +48,10 @@ class SystemStatusDto : public oatpp::DTO { DTO_INIT(SystemStatusDto, DTO) - DTO_FIELD_INFO(state) { info->description = "Name of the state"; } + DTO_FIELD_INFO(state) + { + info->description = "Name of the state"; + } DTO_FIELD(Enum::AsString, state); }; diff --git a/SilKit/source/dashboard/IntegrationTests/ClientServerTestRunner.hpp b/SilKit/source/dashboard/IntegrationTests/ClientServerTestRunner.hpp index 24e75f4cd..426ca6660 100644 --- a/SilKit/source/dashboard/IntegrationTests/ClientServerTestRunner.hpp +++ b/SilKit/source/dashboard/IntegrationTests/ClientServerTestRunner.hpp @@ -51,7 +51,10 @@ class ClientServerTestRunner OATPP_COMPONENT(std::shared_ptr, m_connectionHandler); public: - std::shared_ptr getRouter() { return m_router; } + std::shared_ptr getRouter() + { + return m_router; + } /** * Add controller's endpoints to router @@ -63,7 +66,10 @@ class ClientServerTestRunner m_controllers.push_back(controller); } - std::shared_ptr getServer() { return m_server; } + std::shared_ptr getServer() + { + return m_server; + } /** * Start server, execute code block passed as lambda, stop server. @@ -87,9 +93,7 @@ class ClientServerTestRunner "\033[1;34mRunning server on port %s. Timeout %lld(micro)\033[0m", m_connectionProvider->getProperty("port").toString()->c_str(), timeout.count()); - std::function condition = [&runConditionForLambda]() { - return runConditionForLambda.load(); - }; + std::function condition = [&runConditionForLambda]() { return runConditionForLambda.load(); }; std::thread serverThread([&condition, this] { m_server->run(condition); diff --git a/SilKit/source/dashboard/IntegrationTests/DashboardSystemApiController.hpp b/SilKit/source/dashboard/IntegrationTests/DashboardSystemApiController.hpp index b55422573..9fc974b82 100644 --- a/SilKit/source/dashboard/IntegrationTests/DashboardSystemApiController.hpp +++ b/SilKit/source/dashboard/IntegrationTests/DashboardSystemApiController.hpp @@ -91,7 +91,10 @@ class DashboardSystemApiController : public oatpp::web::server::api::ApiControll updateTimeout, objectMapper); } - std::map GetData() { return _data; } + std::map GetData() + { + return _data; + } ENDPOINT("POST", "system-service/v1.0/simulations", createSimulation, BODY_DTO(Object, simulation)) @@ -390,9 +393,15 @@ class DashboardSystemApiController : public oatpp::web::server::api::ApiControll return finishedSimulationsCount; } - void WaitSimulationsFinished() { _allSimulationsFinishedStatus = _allSimulationsFinishedFuture.wait_for(5s); } + void WaitSimulationsFinished() + { + _allSimulationsFinishedStatus = _allSimulationsFinishedFuture.wait_for(5s); + } - bool AllSimulationsFinished() { return _allSimulationsFinishedStatus == std::future_status::ready; } + bool AllSimulationsFinished() + { + return _allSimulationsFinishedStatus == std::future_status::ready; + } private: std::vector GetLabels(oatpp::Vector> labels) diff --git a/SilKit/source/dashboard/IntegrationTests/DashboardTestComponents.hpp b/SilKit/source/dashboard/IntegrationTests/DashboardTestComponents.hpp index 0a3ba2648..96f3133ee 100644 --- a/SilKit/source/dashboard/IntegrationTests/DashboardTestComponents.hpp +++ b/SilKit/source/dashboard/IntegrationTests/DashboardTestComponents.hpp @@ -40,7 +40,6 @@ class DashboardTestComponents } public: - OATPP_CREATE_COMPONENT(std::shared_ptr, serverConnectionProvider) ([this] { return std::dynamic_pointer_cast( @@ -48,9 +47,7 @@ class DashboardTestComponents }()); OATPP_CREATE_COMPONENT(std::shared_ptr, httpRouter) - ([] { - return oatpp::web::server::HttpRouter::createShared(); - }()); + ([] { return oatpp::web::server::HttpRouter::createShared(); }()); OATPP_CREATE_COMPONENT(std::shared_ptr, serverConnectionHandler) ([] { @@ -65,9 +62,7 @@ class DashboardTestComponents }()); OATPP_CREATE_COMPONENT(std::shared_ptr, apiObjectMapper) - ([] { - return oatpp::parser::json::mapping::ObjectMapper::createShared(); - }()); + ([] { return oatpp::parser::json::mapping::ObjectMapper::createShared(); }()); }; } // namespace Dashboard diff --git a/SilKit/source/dashboard/OatppContext.cpp b/SilKit/source/dashboard/OatppContext.cpp index 3230c6b5a..4c8963a49 100644 --- a/SilKit/source/dashboard/OatppContext.cpp +++ b/SilKit/source/dashboard/OatppContext.cpp @@ -32,7 +32,7 @@ namespace SilKit { namespace Dashboard { OatppContext::OatppContext(std::shared_ptr participantConfig, - const std::string& registryUri, const std::string& dashboardUri) + const std::string& registryUri, const std::string& dashboardUri) { oatpp::base::Environment::init(); auto uri = SilKit::Core::Uri::Parse(dashboardUri); diff --git a/SilKit/source/dashboard/OatppContext.hpp b/SilKit/source/dashboard/OatppContext.hpp index 99af407f5..f1e88a99a 100644 --- a/SilKit/source/dashboard/OatppContext.hpp +++ b/SilKit/source/dashboard/OatppContext.hpp @@ -44,7 +44,7 @@ class OatppContext : public SilKit::Dashboard::IDashboard { public: OatppContext(std::shared_ptr participantConfig, - const std::string& registryUri, const std::string& dashboardUri); + const std::string& registryUri, const std::string& dashboardUri); ~OatppContext(); private: diff --git a/SilKit/source/dashboard/OatppHeaders.hpp b/SilKit/source/dashboard/OatppHeaders.hpp index 19c804405..a4adcdc22 100644 --- a/SilKit/source/dashboard/OatppHeaders.hpp +++ b/SilKit/source/dashboard/OatppHeaders.hpp @@ -7,9 +7,9 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4121) -#pragma warning(disable:4244) -#pragma warning(disable:4389) +#pragma warning(disable : 4121) +#pragma warning(disable : 4244) +#pragma warning(disable : 4389) #endif #ifdef __GNUC__ diff --git a/SilKit/source/dashboard/Service/CachingSilKitEventHandler.cpp b/SilKit/source/dashboard/Service/CachingSilKitEventHandler.cpp index 771d3253a..6a37850b9 100644 --- a/SilKit/source/dashboard/Service/CachingSilKitEventHandler.cpp +++ b/SilKit/source/dashboard/Service/CachingSilKitEventHandler.cpp @@ -107,7 +107,8 @@ CachingSilKitEventHandler::CachingSilKitEventHandler(const std::string& connectU } simulationId = 0; break; - default: _logger->Error("Dashboard: unexpected SilKitEventType"); + default: + _logger->Error("Dashboard: unexpected SilKitEventType"); } } events.clear(); diff --git a/SilKit/source/dashboard/Service/CachingSilKitEventHandler.hpp b/SilKit/source/dashboard/Service/CachingSilKitEventHandler.hpp index 532531097..7ae7eb9ef 100644 --- a/SilKit/source/dashboard/Service/CachingSilKitEventHandler.hpp +++ b/SilKit/source/dashboard/Service/CachingSilKitEventHandler.hpp @@ -46,7 +46,6 @@ class CachingSilKitEventHandler : public ICachingSilKitEventHandler ~CachingSilKitEventHandler(); public: //methods - void OnLastParticipantDisconnected() override; void OnParticipantConnected( const Services::Orchestration::ParticipantConnectionInformation& participantInformation) override; diff --git a/SilKit/source/dashboard/Service/ISilKitEventQueue.hpp b/SilKit/source/dashboard/Service/ISilKitEventQueue.hpp index 16932d486..310013676 100644 --- a/SilKit/source/dashboard/Service/ISilKitEventQueue.hpp +++ b/SilKit/source/dashboard/Service/ISilKitEventQueue.hpp @@ -29,7 +29,6 @@ namespace Dashboard { class ISilKitEventQueue { - public: virtual ~ISilKitEventQueue() = default; virtual void Enqueue(const SilKitEvent& obj) = 0; diff --git a/SilKit/source/dashboard/Service/ISilKitToOatppMapper.hpp b/SilKit/source/dashboard/Service/ISilKitToOatppMapper.hpp index 5a21db234..abbeb68a5 100644 --- a/SilKit/source/dashboard/Service/ISilKitToOatppMapper.hpp +++ b/SilKit/source/dashboard/Service/ISilKitToOatppMapper.hpp @@ -45,13 +45,16 @@ class ISilKitToOatppMapper { public: virtual ~ISilKitToOatppMapper() = default; - virtual oatpp::Object CreateSimulationCreationRequestDto(const std::string& connectUri, uint64_t start) = 0; + virtual oatpp::Object CreateSimulationCreationRequestDto( + const std::string& connectUri, uint64_t start) = 0; virtual oatpp::Object CreateSystemStatusDto(Services::Orchestration::SystemState systemState) = 0; virtual oatpp::Object CreateParticipantStatusDto( const Services::Orchestration::ParticipantStatus& participantStatus) = 0; virtual oatpp::Object CreateServiceDto(const Core::ServiceDescriptor& serviceDescriptor) = 0; - virtual oatpp::Object CreateDataPublisherDto(const Core::ServiceDescriptor& serviceDescriptor) = 0; - virtual oatpp::Object CreateDataSubscriberDto(const Core::ServiceDescriptor& serviceDescriptor) = 0; + virtual oatpp::Object CreateDataPublisherDto( + const Core::ServiceDescriptor& serviceDescriptor) = 0; + virtual oatpp::Object CreateDataSubscriberDto( + const Core::ServiceDescriptor& serviceDescriptor) = 0; virtual oatpp::Object CreateRpcClientDto(const Core::ServiceDescriptor& serviceDescriptor) = 0; virtual oatpp::Object CreateRpcServerDto(const Core::ServiceDescriptor& serviceDescriptor) = 0; virtual oatpp::Object CreateSimulationEndDto(uint64_t stop) = 0; diff --git a/SilKit/source/dashboard/Service/Mocks/MockSilKitToOatppMapper.hpp b/SilKit/source/dashboard/Service/Mocks/MockSilKitToOatppMapper.hpp index 33cf2a9c9..b00498a3c 100644 --- a/SilKit/source/dashboard/Service/Mocks/MockSilKitToOatppMapper.hpp +++ b/SilKit/source/dashboard/Service/Mocks/MockSilKitToOatppMapper.hpp @@ -29,10 +29,14 @@ namespace Dashboard { class MockSilKitToOatppMapper : public ISilKitToOatppMapper { public: - MOCK_METHOD(oatpp::Object, CreateSimulationCreationRequestDto, (const std::string&, uint64_t), (override)); - MOCK_METHOD(oatpp::Object, CreateSystemStatusDto, (SilKit::Services::Orchestration::SystemState), (override)); - MOCK_METHOD(oatpp::Object, CreateParticipantStatusDto, (const SilKit::Services::Orchestration::ParticipantStatus&), (override)); - MOCK_METHOD(oatpp::Object, CreateServiceDto, (const SilKit::Core::ServiceDescriptor&), (override)); + MOCK_METHOD(oatpp::Object, CreateSimulationCreationRequestDto, + (const std::string&, uint64_t), (override)); + MOCK_METHOD(oatpp::Object, CreateSystemStatusDto, + (SilKit::Services::Orchestration::SystemState), (override)); + MOCK_METHOD(oatpp::Object, CreateParticipantStatusDto, + (const SilKit::Services::Orchestration::ParticipantStatus&), (override)); + MOCK_METHOD(oatpp::Object, CreateServiceDto, + (const SilKit::Core::ServiceDescriptor&), (override)); MOCK_METHOD(oatpp::Object, CreateDataPublisherDto, (const SilKit::Core::ServiceDescriptor&), (override)); MOCK_METHOD(oatpp::Object, CreateDataSubscriberDto, diff --git a/SilKit/source/dashboard/Service/SilKitEvent.hpp b/SilKit/source/dashboard/Service/SilKitEvent.hpp index a4577ca85..411685c76 100644 --- a/SilKit/source/dashboard/Service/SilKitEvent.hpp +++ b/SilKit/source/dashboard/Service/SilKitEvent.hpp @@ -110,12 +110,8 @@ class SilKitEvent : _type{getTypeId()} , _simulationName{std::move(simulationName)} , _data{new T{value}} - , _clone([](void* otherData) -> void* { - return new T(*static_cast(otherData)); - }) - , _destroy([](void* data) { - delete static_cast(data); - }) + , _clone([](void* otherData) -> void* { return new T(*static_cast(otherData)); }) + , _destroy([](void* data) { delete static_cast(data); }) { } @@ -147,11 +143,20 @@ class SilKitEvent return *this; } - auto Type() const -> SilKitEventType { return _type; } + auto Type() const -> SilKitEventType + { + return _type; + } - auto GetSimulationName() const -> const std::string& { return _simulationName; } + auto GetSimulationName() const -> const std::string& + { + return _simulationName; + } - auto GetSimulationStart() const -> const SimulationStart& { return Get(); } + auto GetSimulationStart() const -> const SimulationStart& + { + return Get(); + } auto GetParticipantConnectionInformation() const -> const Services::Orchestration::ParticipantConnectionInformation& { @@ -168,9 +173,15 @@ class SilKitEvent return Get(); } - auto GetServiceData() const -> const ServiceData& { return Get(); } + auto GetServiceData() const -> const ServiceData& + { + return Get(); + } - auto GetSimulationEnd() const -> const SimulationEnd& { return Get(); } + auto GetSimulationEnd() const -> const SimulationEnd& + { + return Get(); + } private: template diff --git a/SilKit/source/dashboard/Service/SilKitEventHandler.cpp b/SilKit/source/dashboard/Service/SilKitEventHandler.cpp index 4e34ad370..3a798c120 100644 --- a/SilKit/source/dashboard/Service/SilKitEventHandler.cpp +++ b/SilKit/source/dashboard/Service/SilKitEventHandler.cpp @@ -38,9 +38,7 @@ SilKitEventHandler::SilKitEventHandler(Services::Logging::ILogger* logger, { } -SilKitEventHandler::~SilKitEventHandler() -{ -} +SilKitEventHandler::~SilKitEventHandler() {} uint64_t SilKitEventHandler::OnSimulationStart(const std::string& connectUri, uint64_t time) { @@ -96,9 +94,14 @@ void SilKitEventHandler::OnServiceDiscoveryEvent(uint64_t simulationId, SILKIT_UNUSED_ARG(discoveryType); switch (serviceDescriptor.GetServiceType()) { - case Core::ServiceType::Controller: OnControllerCreated(simulationId, serviceDescriptor); break; - case Core::ServiceType::Link: OnLinkCreated(simulationId, serviceDescriptor); break; - default: break; + case Core::ServiceType::Controller: + OnControllerCreated(simulationId, serviceDescriptor); + break; + case Core::ServiceType::Link: + OnLinkCreated(simulationId, serviceDescriptor); + break; + default: + break; } } @@ -208,7 +211,8 @@ void SilKitEventHandler::OnLinkCreated(uint64_t simulationId, const Core::Servic case Config::NetworkType::LIN: _dashboardSystemServiceClient->AddLinNetworkToSimulation(simulationId, participantName, networkName); break; - default: return; + default: + return; } } diff --git a/SilKit/source/dashboard/Service/SilKitEventQueue.cpp b/SilKit/source/dashboard/Service/SilKitEventQueue.cpp index a7da33449..1847622a7 100644 --- a/SilKit/source/dashboard/Service/SilKitEventQueue.cpp +++ b/SilKit/source/dashboard/Service/SilKitEventQueue.cpp @@ -25,13 +25,9 @@ namespace SilKit { namespace Dashboard { -SilKitEventQueue::SilKitEventQueue() -{ -} +SilKitEventQueue::SilKitEventQueue() {} -SilKitEventQueue::~SilKitEventQueue() -{ -} +SilKitEventQueue::~SilKitEventQueue() {} void SilKitEventQueue::Enqueue(const SilKitEvent& obj) { @@ -48,9 +44,7 @@ void SilKitEventQueue::Enqueue(const SilKitEvent& obj) bool SilKitEventQueue::DequeueAllInto(std::vector& events) { std::unique_lock lock{_mutex}; - _cv.wait(lock, [this] { - return !_queue.empty() || _stop; - }); + _cv.wait(lock, [this] { return !_queue.empty() || _stop; }); std::move(_queue.begin(), _queue.end(), std::back_inserter(events)); _queue.clear(); return !events.empty(); diff --git a/SilKit/source/dashboard/Service/SilKitToOatppMapper.cpp b/SilKit/source/dashboard/Service/SilKitToOatppMapper.cpp index b83ab271a..7f2242c9d 100644 --- a/SilKit/source/dashboard/Service/SilKitToOatppMapper.cpp +++ b/SilKit/source/dashboard/Service/SilKitToOatppMapper.cpp @@ -48,20 +48,34 @@ SystemState MapSystemState(Services::Orchestration::SystemState systemState) { switch (systemState) { - case Services::Orchestration::SystemState::Invalid: return SystemState::Invalid; - case Services::Orchestration::SystemState::ServicesCreated: return SystemState::ServicesCreated; - case Services::Orchestration::SystemState::CommunicationInitializing: return SystemState::CommunicationInitializing; - case Services::Orchestration::SystemState::CommunicationInitialized: return SystemState::CommunicationInitialized; - case Services::Orchestration::SystemState::ReadyToRun: return SystemState::ReadyToRun; - case Services::Orchestration::SystemState::Running: return SystemState::Running; - case Services::Orchestration::SystemState::Paused: return SystemState::Paused; - case Services::Orchestration::SystemState::Stopping: return SystemState::Stopping; - case Services::Orchestration::SystemState::Stopped: return SystemState::Stopped; - case Services::Orchestration::SystemState::Error: return SystemState::Error; - case Services::Orchestration::SystemState::ShuttingDown: return SystemState::ShuttingDown; - case Services::Orchestration::SystemState::Shutdown: return SystemState::Shutdown; - case Services::Orchestration::SystemState::Aborting: return SystemState::Aborting; - default: throw SilKitError{"Incomplete system state mapping"}; + case Services::Orchestration::SystemState::Invalid: + return SystemState::Invalid; + case Services::Orchestration::SystemState::ServicesCreated: + return SystemState::ServicesCreated; + case Services::Orchestration::SystemState::CommunicationInitializing: + return SystemState::CommunicationInitializing; + case Services::Orchestration::SystemState::CommunicationInitialized: + return SystemState::CommunicationInitialized; + case Services::Orchestration::SystemState::ReadyToRun: + return SystemState::ReadyToRun; + case Services::Orchestration::SystemState::Running: + return SystemState::Running; + case Services::Orchestration::SystemState::Paused: + return SystemState::Paused; + case Services::Orchestration::SystemState::Stopping: + return SystemState::Stopping; + case Services::Orchestration::SystemState::Stopped: + return SystemState::Stopped; + case Services::Orchestration::SystemState::Error: + return SystemState::Error; + case Services::Orchestration::SystemState::ShuttingDown: + return SystemState::ShuttingDown; + case Services::Orchestration::SystemState::Shutdown: + return SystemState::Shutdown; + case Services::Orchestration::SystemState::Aborting: + return SystemState::Aborting; + default: + throw SilKitError{"Incomplete system state mapping"}; } } @@ -77,22 +91,34 @@ ParticipantState MapParticipantState(Services::Orchestration::ParticipantState s { switch (state) { - case Services::Orchestration::ParticipantState::Invalid: return ParticipantState::Invalid; - case Services::Orchestration::ParticipantState::ServicesCreated: return ParticipantState::ServicesCreated; + case Services::Orchestration::ParticipantState::Invalid: + return ParticipantState::Invalid; + case Services::Orchestration::ParticipantState::ServicesCreated: + return ParticipantState::ServicesCreated; case Services::Orchestration::ParticipantState::CommunicationInitializing: return ParticipantState::CommunicationInitializing; case Services::Orchestration::ParticipantState::CommunicationInitialized: return ParticipantState::CommunicationInitialized; - case Services::Orchestration::ParticipantState::ReadyToRun: return ParticipantState::ReadyToRun; - case Services::Orchestration::ParticipantState::Running: return ParticipantState::Running; - case Services::Orchestration::ParticipantState::Paused: return ParticipantState::Paused; - case Services::Orchestration::ParticipantState::Stopping: return ParticipantState::Stopping; - case Services::Orchestration::ParticipantState::Stopped: return ParticipantState::Stopped; - case Services::Orchestration::ParticipantState::Error: return ParticipantState::Error; - case Services::Orchestration::ParticipantState::ShuttingDown: return ParticipantState::ShuttingDown; - case Services::Orchestration::ParticipantState::Shutdown: return ParticipantState::Shutdown; - case Services::Orchestration::ParticipantState::Aborting: return ParticipantState::Aborting; - default: throw SilKitError{"Incomplete participant state mapping"}; + case Services::Orchestration::ParticipantState::ReadyToRun: + return ParticipantState::ReadyToRun; + case Services::Orchestration::ParticipantState::Running: + return ParticipantState::Running; + case Services::Orchestration::ParticipantState::Paused: + return ParticipantState::Paused; + case Services::Orchestration::ParticipantState::Stopping: + return ParticipantState::Stopping; + case Services::Orchestration::ParticipantState::Stopped: + return ParticipantState::Stopped; + case Services::Orchestration::ParticipantState::Error: + return ParticipantState::Error; + case Services::Orchestration::ParticipantState::ShuttingDown: + return ParticipantState::ShuttingDown; + case Services::Orchestration::ParticipantState::Shutdown: + return ParticipantState::Shutdown; + case Services::Orchestration::ParticipantState::Aborting: + return ParticipantState::Aborting; + default: + throw SilKitError{"Incomplete participant state mapping"}; } } @@ -111,9 +137,12 @@ LabelKind MapLabelKind(Services::MatchingLabel::Kind labelKind) { switch (labelKind) { - case Services::MatchingLabel::Kind::Optional: return LabelKind::Optional; - case Services::MatchingLabel::Kind::Mandatory: return LabelKind::Mandatory; - default: throw SilKitError{"Incomplete mapping"}; + case Services::MatchingLabel::Kind::Optional: + return LabelKind::Optional; + case Services::MatchingLabel::Kind::Mandatory: + return LabelKind::Mandatory; + default: + throw SilKitError{"Incomplete mapping"}; } } diff --git a/SilKit/source/dashboard/Service/SilKitToOatppMapper.hpp b/SilKit/source/dashboard/Service/SilKitToOatppMapper.hpp index d49710635..705e9c086 100644 --- a/SilKit/source/dashboard/Service/SilKitToOatppMapper.hpp +++ b/SilKit/source/dashboard/Service/SilKitToOatppMapper.hpp @@ -29,7 +29,8 @@ namespace Dashboard { class SilKitToOatppMapper : public ISilKitToOatppMapper { public: - oatpp::Object CreateSimulationCreationRequestDto(const std::string& connectUri, uint64_t start) override; + oatpp::Object CreateSimulationCreationRequestDto(const std::string& connectUri, + uint64_t start) override; oatpp::Object CreateSystemStatusDto(Services::Orchestration::SystemState systemState) override; oatpp::Object CreateParticipantStatusDto( const Services::Orchestration::ParticipantStatus& participantStatus) override; diff --git a/SilKit/source/dashboard/Service/Test_DashboardCachingSilKitEventHandler.cpp b/SilKit/source/dashboard/Service/Test_DashboardCachingSilKitEventHandler.cpp index b70788ce0..a51e61bb1 100644 --- a/SilKit/source/dashboard/Service/Test_DashboardCachingSilKitEventHandler.cpp +++ b/SilKit/source/dashboard/Service/Test_DashboardCachingSilKitEventHandler.cpp @@ -60,11 +60,20 @@ class Test_DashboardCachingSilKitEventHandler : public Test _mockEventQueue); } - void CheckConnectUri(const std::string& actual) { ASSERT_EQ(actual, _connectUri) << "Wrong connectUri!"; } + void CheckConnectUri(const std::string& actual) + { + ASSERT_EQ(actual, _connectUri) << "Wrong connectUri!"; + } - void CheckTime(uint64_t actual) { ASSERT_TRUE(actual > 0) << "Wrong time!"; } + void CheckTime(uint64_t actual) + { + ASSERT_TRUE(actual > 0) << "Wrong time!"; + } - void CheckSimulationId(uint64_t actual) { ASSERT_EQ(actual, _simulationId) << "Wrong simulationId!"; } + void CheckSimulationId(uint64_t actual) + { + ASSERT_EQ(actual, _simulationId) << "Wrong simulationId!"; + } Core::Tests::MockLogger _dummyLogger; std::shared_ptr> _mockEventHandler; @@ -78,10 +87,7 @@ TEST_F(Test_DashboardCachingSilKitEventHandler, NoEvents) { // Arrange EXPECT_CALL(*_mockEventQueue, DequeueAllInto) - .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { - evts.clear(); - }), - Return(false))); + .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { evts.clear(); }), Return(false))); EXPECT_CALL(*_mockEventQueue, Stop); // Act @@ -100,33 +106,35 @@ TEST_F(Test_DashboardCachingSilKitEventHandler, OnParticipantConnected_CreateSim EXPECT_CALL(*_mockEventQueue, Enqueue).WillRepeatedly(WithArgs<0>([&](const auto& evt) { switch (evt.Type()) { - case SilKitEventType::OnSimulationStart: simulationStartFound = true; break; - case SilKitEventType::OnParticipantConnected: participantConnectionInformationFound = true; break; - default: /* do nothing */ break; + case SilKitEventType::OnSimulationStart: + simulationStartFound = true; + break; + case SilKitEventType::OnParticipantConnected: + participantConnectionInformationFound = true; + break; + default: /* do nothing */ + break; } })); Services::Orchestration::ParticipantConnectionInformation participantConnectionInformation; EXPECT_CALL(*_mockEventQueue, DequeueAllInto) .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { - SimulationStart simulationStart{"silkit://localhost:8500", 123456}; - std::vector events; - events.emplace_back("", simulationStart); - events.emplace_back("", participantConnectionInformation); - evts.swap(events); - }), + SimulationStart simulationStart{"silkit://localhost:8500", 123456}; + std::vector events; + events.emplace_back("", simulationStart); + events.emplace_back("", participantConnectionInformation); + evts.swap(events); + }), Return(true))) - .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { - evts.clear(); - }), - Return(false))); + .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { evts.clear(); }), Return(false))); std::string actualConnectUri; uint64_t actualTime = 0; EXPECT_CALL(*_mockEventHandler, OnSimulationStart) .WillOnce(DoAll(WithArgs<0, 1>([&](auto connectUri, auto time) { - actualConnectUri = connectUri; - actualTime = time; - }), + actualConnectUri = connectUri; + actualTime = time; + }), Return(_invalidSimulationId))); EXPECT_CALL(*_mockEventQueue, Stop); @@ -151,32 +159,34 @@ TEST_F(Test_DashboardCachingSilKitEventHandler, OnParticipantConnected_CreateSim EXPECT_CALL(*_mockEventQueue, Enqueue).WillRepeatedly(WithArgs<0>([&](const auto& evt) { switch (evt.Type()) { - case SilKitEventType::OnSimulationStart: simulationStartFound = true; break; - case SilKitEventType::OnParticipantConnected: participantConnectionInformationFound = true; break; - default: /* do nothing */ break; + case SilKitEventType::OnSimulationStart: + simulationStartFound = true; + break; + case SilKitEventType::OnParticipantConnected: + participantConnectionInformationFound = true; + break; + default: /* do nothing */ + break; } })); Services::Orchestration::ParticipantConnectionInformation participantConnectionInformation; EXPECT_CALL(*_mockEventQueue, DequeueAllInto) .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { - SimulationStart simulationStart{"silkit://localhost:8500", 123456}; - std::vector events; - events.emplace_back("", simulationStart); - events.emplace_back("", participantConnectionInformation); - evts.swap(events); - }), + SimulationStart simulationStart{"silkit://localhost:8500", 123456}; + std::vector events; + events.emplace_back("", simulationStart); + events.emplace_back("", participantConnectionInformation); + evts.swap(events); + }), Return(true))) - .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { - evts.clear(); - }), - Return(false))); + .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { evts.clear(); }), Return(false))); std::string actualConnectUri; uint64_t actualTime = 0; EXPECT_CALL(*_mockEventHandler, OnSimulationStart) .WillOnce(DoAll(WithArgs<0, 1>([&](auto connectUri, auto time) { - actualConnectUri = connectUri; - actualTime = time; - }), + actualConnectUri = connectUri; + actualTime = time; + }), Return(_simulationId))); uint64_t actualSimulationId = 0; Services::Orchestration::ParticipantConnectionInformation actualInfo; @@ -205,10 +215,7 @@ TEST_F(Test_DashboardCachingSilKitEventHandler, OnLastParticipantDisconnected_Si { // Arrange EXPECT_CALL(*_mockEventQueue, DequeueAllInto) - .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { - evts.clear(); - }), - Return(false))); + .WillOnce(DoAll(WithArgs<0>([&](auto& evts) { evts.clear(); }), Return(false))); EXPECT_CALL(*_mockEventQueue, Stop); // Act diff --git a/SilKit/source/dashboard/Service/Test_DashboardSilKitEventHandler.cpp b/SilKit/source/dashboard/Service/Test_DashboardSilKitEventHandler.cpp index 8c9c952a1..1297136a9 100644 --- a/SilKit/source/dashboard/Service/Test_DashboardSilKitEventHandler.cpp +++ b/SilKit/source/dashboard/Service/Test_DashboardSilKitEventHandler.cpp @@ -127,9 +127,9 @@ TEST_F(Test_DashboardSilKitEventHandler, OnParticipantConnected_AddParticipantRe oatpp::String actualParticipantName; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddParticipantToSimulation) .WillOnce(WithArgs<0, 1>([&](auto simulationId, auto participantName) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + })); // Act const connectionInfo info{"my Participant"}; @@ -154,9 +154,9 @@ TEST_F(Test_DashboardSilKitEventHandler, OnSystemStateChanged_UpdateSystemStatus SilKit::Dashboard::SystemState actualSystemState; EXPECT_CALL(*_mockDashboardSystemServiceClient, UpdateSystemStatusForSimulation) .WillOnce(WithArgs<0, 1>([&](auto simulationId, auto systemStatus) { - actualSimulationId = simulationId; - actualSystemState = systemStatus->state; - })); + actualSimulationId = simulationId; + actualSystemState = systemStatus->state; + })); // Act service->OnSystemStateChanged(expectedSimulationId, Services::Orchestration::SystemState::Running); @@ -184,10 +184,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnParticipantStatusChanged_AddParticipa SilKit::Dashboard::ParticipantState actualParticipantState; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddParticipantStatusForSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto participantStatus) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualParticipantState = participantStatus->state; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualParticipantState = participantStatus->state; + })); // Act participantStatus status; @@ -227,10 +227,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnServiceDiscoveryEvent_CanControllerCr oatpp::UInt64 actualServiceId; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddCanControllerForParticipantOfSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -259,10 +259,10 @@ TEST_F(Test_DashboardSilKitEventHandler, oatpp::UInt64 actualServiceId; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddEthernetControllerForParticipantOfSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -291,10 +291,10 @@ TEST_F(Test_DashboardSilKitEventHandler, oatpp::UInt64 actualServiceId; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddFlexrayControllerForParticipantOfSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -322,10 +322,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnServiceDiscoveryEvent_LinControllerCr oatpp::UInt64 actualServiceId; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddLinControllerForParticipantOfSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -355,10 +355,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnServiceDiscoveryEvent_DataPublisherCr oatpp::UInt64 actualServiceId; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddDataPublisherForParticipantOfSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -388,10 +388,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnServiceDiscoveryEvent_DataSubscriberC oatpp::UInt64 actualServiceId; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddDataSubscriberForParticipantOfSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -427,11 +427,11 @@ TEST_F(Test_DashboardSilKitEventHandler, EXPECT_CALL(*_mockDashboardSystemServiceClient, AddDataSubscriberInternalForParticipantOfSimulation) .WillOnce( WithArgs<0, 1, 2, 3>([&](auto simulationId, auto participantName, auto parentServiceId, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualParentServiceId = parentServiceId; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualParentServiceId = parentServiceId; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -461,10 +461,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnServiceDiscoveryEvent_RpcClientCreate oatpp::UInt64 actualServiceId; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddRpcClientForParticipantOfSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -493,10 +493,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnServiceDiscoveryEvent_RpcServerCreate oatpp::UInt64 actualServiceId; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddRpcServerForParticipantOfSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -532,11 +532,11 @@ TEST_F(Test_DashboardSilKitEventHandler, EXPECT_CALL(*_mockDashboardSystemServiceClient, AddRpcServerInternalForParticipantOfSimulation) .WillOnce( WithArgs<0, 1, 2, 3>([&](auto simulationId, auto participantName, auto parentServiceId, auto serviceId) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualParentServiceId = parentServiceId; - actualServiceId = serviceId; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualParentServiceId = parentServiceId; + actualServiceId = serviceId; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -566,10 +566,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnServiceDiscoveryEvent_CanLinkCreated_ oatpp::String actualNetworkName; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddCanNetworkToSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto networkName) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualNetworkName = networkName; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualNetworkName = networkName; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -599,10 +599,10 @@ TEST_F(Test_DashboardSilKitEventHandler, oatpp::String actualNetworkName; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddEthernetNetworkToSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto networkName) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualNetworkName = networkName; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualNetworkName = networkName; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -632,10 +632,10 @@ TEST_F(Test_DashboardSilKitEventHandler, oatpp::String actualNetworkName; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddFlexrayNetworkToSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto networkName) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualNetworkName = networkName; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualNetworkName = networkName; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, @@ -664,10 +664,10 @@ TEST_F(Test_DashboardSilKitEventHandler, OnServiceDiscoveryEvent_LinLinkCreated_ oatpp::String actualNetworkName; EXPECT_CALL(*_mockDashboardSystemServiceClient, AddLinNetworkToSimulation) .WillOnce(WithArgs<0, 1, 2>([&](auto simulationId, auto participantName, auto networkName) { - actualSimulationId = simulationId; - actualParticipantName = participantName; - actualNetworkName = networkName; - })); + actualSimulationId = simulationId; + actualParticipantName = participantName; + actualNetworkName = networkName; + })); // Act service->OnServiceDiscoveryEvent(expectedSimulationId, Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated, diff --git a/SilKit/source/dashboard/Service/Test_DashboardSilKitEventQueue.cpp b/SilKit/source/dashboard/Service/Test_DashboardSilKitEventQueue.cpp index 508190758..55cdbe9c3 100644 --- a/SilKit/source/dashboard/Service/Test_DashboardSilKitEventQueue.cpp +++ b/SilKit/source/dashboard/Service/Test_DashboardSilKitEventQueue.cpp @@ -35,7 +35,10 @@ namespace Dashboard { class Test_DashboardSilKitEventQueue : public Test { public: - std::shared_ptr CreateService() { return std::make_shared(); } + std::shared_ptr CreateService() + { + return std::make_shared(); + } }; TEST_F(Test_DashboardSilKitEventQueue, ManyProducersAndOneConsumer) diff --git a/SilKit/source/dashboard/Service/Test_DashboardSilKitToOatppMapper.cpp b/SilKit/source/dashboard/Service/Test_DashboardSilKitToOatppMapper.cpp index f0a42b50e..b7944df10 100644 --- a/SilKit/source/dashboard/Service/Test_DashboardSilKitToOatppMapper.cpp +++ b/SilKit/source/dashboard/Service/Test_DashboardSilKitToOatppMapper.cpp @@ -33,9 +33,7 @@ namespace Dashboard { class Test_DashboardSilKitToOatppMapper : public testing::Test { public: - void SetUp() override - { - } + void SetUp() override {} static std::shared_ptr CreateService() { @@ -49,7 +47,7 @@ TEST_F(Test_DashboardSilKitToOatppMapper, CreateSimulationCreationRequestDto_Map const std::string endpoint("silkit://myhost:1234"); const auto now = std::chrono::system_clock::now().time_since_epoch(); const uint64_t expectedStartTime = std::chrono::duration_cast(now).count(); - + // Act const auto dataMapper = CreateService(); const auto dto = dataMapper->CreateSimulationCreationRequestDto(endpoint, expectedStartTime); @@ -89,7 +87,8 @@ TEST_F(Test_DashboardSilKitToOatppMapper, CreateParticipantStatusDto_MapReasonAn // Arrange const std::string expectedReason("myReason"); const auto now = std::chrono::system_clock::now(); - const auto expectedEnterTime = std::chrono::duration_cast(now.time_since_epoch()).count(); + const auto expectedEnterTime = + std::chrono::duration_cast(now.time_since_epoch()).count(); orchestration::ParticipantStatus participant_status; participant_status.participantName = ""; @@ -146,8 +145,7 @@ TEST_F(Test_DashboardSilKitToOatppMapper, CreateDataPublisherDto_MapNameAndNetwo expectedLabel.value = "myValue"; expectedLabel.kind = Services::MatchingLabel::Kind::Mandatory; auto labels = std::vector{expectedLabel}; - descriptor.SetSupplementalDataItem(Core::Discovery::supplKeyDataPublisherPubLabels, - Config::Serialize(labels)); + descriptor.SetSupplementalDataItem(Core::Discovery::supplKeyDataPublisherPubLabels, Config::Serialize(labels)); // Act const auto dataMapper = CreateService(); @@ -198,7 +196,7 @@ TEST_F(Test_DashboardSilKitToOatppMapper, CreateDataSubscriberDto_MapNetworkName TEST_F(Test_DashboardSilKitToOatppMapper, CreateRpcClientDto_MapNetworkNameAndFunctionNameAndMediaTypeAndLabel) { - // Arrange + // Arrange Core::ServiceDescriptor descriptor; const std::string expectedName("myService"); const std::string expectedNetwork("myNetwork"); @@ -216,8 +214,7 @@ TEST_F(Test_DashboardSilKitToOatppMapper, CreateRpcClientDto_MapNetworkNameAndFu expectedLabel.value = "myValue"; expectedLabel.kind = Services::MatchingLabel::Kind::Mandatory; auto labels = std::vector{expectedLabel}; - descriptor.SetSupplementalDataItem(Core::Discovery::supplKeyRpcClientLabels, - Config::Serialize(labels)); + descriptor.SetSupplementalDataItem(Core::Discovery::supplKeyRpcClientLabels, Config::Serialize(labels)); // Act const auto dataMapper = CreateService(); @@ -267,7 +264,7 @@ TEST_F(Test_DashboardSilKitToOatppMapper, CreateRpcServerDto_MapNetworkNameAndFu TEST_F(Test_DashboardSilKitToOatppMapper, CreateSimulationEndDto) { - // Arrange + // Arrange const auto now = std::chrono::system_clock::now().time_since_epoch(); const uint64_t expectedStopTime = std::chrono::duration_cast(now).count(); diff --git a/SilKit/source/dashboard/TestResult.hpp b/SilKit/source/dashboard/TestResult.hpp index 56b90f508..493f28e74 100644 --- a/SilKit/source/dashboard/TestResult.hpp +++ b/SilKit/source/dashboard/TestResult.hpp @@ -52,7 +52,10 @@ struct Link { std::string type; std::string name; - bool operator<(const Link& rhs) const { return type < rhs.type || (type == rhs.type && name < rhs.name); } + bool operator<(const Link& rhs) const + { + return type < rhs.type || (type == rhs.type && name < rhs.name); + } }; struct SimulationData diff --git a/SilKit/source/experimental/CMakeLists.txt b/SilKit/source/experimental/CMakeLists.txt index 601a1a8f0..05634555f 100644 --- a/SilKit/source/experimental/CMakeLists.txt +++ b/SilKit/source/experimental/CMakeLists.txt @@ -19,6 +19,8 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +add_subdirectory(netsim) + add_library(I_SilKit_Experimental INTERFACE) target_include_directories(I_SilKit_Experimental diff --git a/SilKit/source/experimental/netsim/CMakeLists.txt b/SilKit/source/experimental/netsim/CMakeLists.txt new file mode 100644 index 000000000..e482c5c50 --- /dev/null +++ b/SilKit/source/experimental/netsim/CMakeLists.txt @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +# +# SPDX-License-Identifier: MIT + +add_library(I_SilKit_Experimental_NetworkSimulatorInternals INTERFACE) + +target_include_directories(I_SilKit_Experimental_NetworkSimulatorInternals + INTERFACE ${CMAKE_CURRENT_LIST_DIR} + INTERFACE SilKitInterface +) + +target_link_libraries(I_SilKit_Experimental_NetworkSimulatorInternals + INTERFACE I_SilKit_Core_Internal +) + +add_library(O_SilKit_Experimental_NetworkSimulatorInternals OBJECT + INetworkSimulatorInternal.hpp + NetworkSimulatorInternal.cpp + NetworkSimulatorInternal.hpp + SimulatedNetworkInternal.cpp + SimulatedNetworkInternal.hpp + SimulatedNetworkRouter.cpp + SimulatedNetworkRouter.hpp + NetworkSimulatorDatatypesInternal.hpp + eventproducers/CanEventProducer.cpp + eventproducers/CanEventProducer.hpp + eventproducers/FlexRayEventProducer.cpp + eventproducers/FlexRayEventProducer.hpp + eventproducers/LinEventProducer.cpp + eventproducers/LinEventProducer.hpp + eventproducers/EthernetEventProducer.cpp + eventproducers/EthernetEventProducer.hpp +) + +target_link_libraries(O_SilKit_Experimental_NetworkSimulatorInternals + PUBLIC I_SilKit_Experimental_NetworkSimulatorInternals + PRIVATE I_SilKit_Core_Internal +) diff --git a/SilKit/source/experimental/netsim/INetworkSimulatorInternal.hpp b/SilKit/source/experimental/netsim/INetworkSimulatorInternal.hpp new file mode 100644 index 000000000..74156f67b --- /dev/null +++ b/SilKit/source/experimental/netsim/INetworkSimulatorInternal.hpp @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "silkit/experimental/netsim/NetworkSimulatorDatatypes.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +class INetworkSimulatorInternal +{ +public: + // Returns the corresponding serviceDescriptor string to a given controllerDescriptor. + // Returns an empty string and logs a warning if the controllerDescriptor is unknown. + virtual auto GetServiceDescriptorString(ControllerDescriptor controllerDescriptor) -> std::string const = 0; +}; + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/source/experimental/netsim/NetworkSimulatorDatatypesInternal.hpp b/SilKit/source/experimental/netsim/NetworkSimulatorDatatypesInternal.hpp new file mode 100644 index 000000000..9532b13c2 --- /dev/null +++ b/SilKit/source/experimental/netsim/NetworkSimulatorDatatypesInternal.hpp @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "silkit/experimental/netsim/NetworkSimulatorDatatypes.hpp" +#include "Configuration.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +inline auto ConvertNetworkTypeFromConfig(Config::v1::NetworkType configNetworkType) + -> Experimental::NetworkSimulation::SimulatedNetworkType +{ + switch (configNetworkType) + { + case Config::v1::NetworkType::CAN: + return SimulatedNetworkType::CAN; + case Config::v1::NetworkType::LIN: + return SimulatedNetworkType::LIN; + case Config::v1::NetworkType::Ethernet: + return SimulatedNetworkType::Ethernet; + case Config::v1::NetworkType::FlexRay: + return SimulatedNetworkType::FlexRay; + default: + return SimulatedNetworkType::Undefined; + } +} + +inline auto ConvertNetworkTypeToConfig(NetworkSimulation::SimulatedNetworkType networkType) -> Config::v1::NetworkType +{ + switch (networkType) + { + case SimulatedNetworkType::CAN: + return Config::v1::NetworkType::CAN; + case SimulatedNetworkType::LIN: + return Config::v1::NetworkType::LIN; + case SimulatedNetworkType::Ethernet: + return Config::v1::NetworkType::Ethernet; + case SimulatedNetworkType::FlexRay: + return Config::v1::NetworkType::FlexRay; + default: + return Config::v1::NetworkType::Undefined; + } +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/source/experimental/netsim/NetworkSimulatorInternal.cpp b/SilKit/source/experimental/netsim/NetworkSimulatorInternal.cpp new file mode 100644 index 000000000..a166e1ee2 --- /dev/null +++ b/SilKit/source/experimental/netsim/NetworkSimulatorInternal.cpp @@ -0,0 +1,274 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include + +#include "NetworkSimulatorInternal.hpp" +#include "NetworkSimulatorDatatypesInternal.hpp" +#include "silkit/experimental/netsim/string_utils.hpp" + +#include "ILogger.hpp" +#include "procs/IParticipantReplies.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +NetworkSimulatorInternal::NetworkSimulatorInternal(Core::IParticipantInternal* participant) + : _participant{participant} + , _logger{participant->GetLogger()} +{ + _nextControllerDescriptor = 0; + _networkSimulatorStarted = false; +} + +// INetworkSimulator + +void NetworkSimulatorInternal::SimulateNetwork(const std::string& networkName, SimulatedNetworkType networkType, + std::unique_ptr simulatedNetwork) +{ + if (_networkSimulatorStarted) + { + SilKit::Services::Logging::Warn(_logger, "SimulateNetwork() must not be used after Start()."); + return; + } + + _logger->Debug("SimulateNetwork '" + networkName + "' of type " + to_string(networkType)); + CreateSimulatedNetwork(networkName, networkType, std::move(simulatedNetwork)); +} + +void NetworkSimulatorInternal::Start() +{ + if (_networkSimulatorStarted) + { + SilKit::Services::Logging::Warn(_logger, "Start() has already been called."); + return; + } + + _networkSimulatorStarted = true; + + if (_simulatedNetworks.empty()) + { + SilKit::Services::Logging::Warn(_logger, "NetworkSimulator was started without any simulated networks."); + } + + // Register the service discovery AFTER the network simulator has been registered. + // Otherwise, the discovery events cannot be processed by the network simulator + auto disco = _participant->GetServiceDiscovery(); + disco->RegisterServiceDiscoveryHandler([this](Core::Discovery::ServiceDiscoveryEvent::Type discoveryType, + const Core::ServiceDescriptor& serviceDescriptor) { + DiscoveryHandler(discoveryType, serviceDescriptor); + }); + + // Barrier to guarantee catching two network simulators on the same simulated network + std::promise netSimStartBarrier{}; + _participant->GetParticipantRepliesProcedure()->CallAfterAllParticipantsReplied( + [&netSimStartBarrier]() { netSimStartBarrier.set_value(); }); + netSimStartBarrier.get_future().wait(); +} + +// INetworkSimulatorInternal + +auto NetworkSimulatorInternal::GetServiceDescriptorString(ControllerDescriptor controllerDescriptor) + -> std::string const +{ + auto serviceDescriptor_it = _serviceDescriptorByControllerDescriptor.find(controllerDescriptor); + if (serviceDescriptor_it == _serviceDescriptorByControllerDescriptor.end()) + { + SilKit::Services::Logging::Warn(_logger, + "GetServiceDescriptorString queried with an unknown controllerDescriptor."); + return ""; + } + return serviceDescriptor_it->second.to_string(); +} + +// Private + +auto NetworkSimulatorInternal::NextControllerDescriptor() -> uint64_t +{ + // NetworkSimulator maintains the ControllerDescriptors, only accessible via cast to internal + // These are unique per NetworkSimulator and thus per participant (only one NetworkSimulator allowed per participant) + + // Start at 1, as SilKit_Experimental_ControllerDescriptor_Invalid is 0 + return ++_nextControllerDescriptor; +} + +void NetworkSimulatorInternal::CreateSimulatedNetwork(const std::string& networkName, SimulatedNetworkType networkType, + std::unique_ptr userSimulatedNetwork) +{ + auto simulatedNetworkInternal = std::make_unique(_participant, networkName, networkType, + std::move(userSimulatedNetwork)); + + auto networksOfType_it = _simulatedNetworks.find(networkType); + if (networksOfType_it != _simulatedNetworks.end()) + { + auto simulatedNetwork_it = networksOfType_it->second.find(networkName); + if (simulatedNetwork_it != networksOfType_it->second.end()) + { + throw SilKitError("Network already exists."); + } + } + _simulatedNetworks[networkType][networkName] = std::move(simulatedNetworkInternal); +} + + +auto NetworkSimulatorInternal::LookupSimulatedNetwork(const std::string& networkName, + SimulatedNetworkType networkType) -> SimulatedNetworkInternal* +{ + auto it_simulatedNetworksByType = _simulatedNetworks.find(networkType); + if (it_simulatedNetworksByType != _simulatedNetworks.end()) + { + auto it_simulatedNetworkByName = it_simulatedNetworksByType->second.find(networkName); + if (it_simulatedNetworkByName != it_simulatedNetworksByType->second.end()) + { + return it_simulatedNetworkByName->second.get(); + } + } + return nullptr; +} + +void NetworkSimulatorInternal::DiscoveryHandler(SilKit::Core::Discovery::ServiceDiscoveryEvent::Type discoveryType, + const SilKit::Core::ServiceDescriptor& serviceDescriptor) +{ + auto configNetworkType = serviceDescriptor.GetNetworkType(); + auto networkType = ConvertNetworkTypeFromConfig(configNetworkType); + auto networkName = serviceDescriptor.GetNetworkName(); + auto serviceType = serviceDescriptor.GetServiceType(); + auto controllerName = serviceDescriptor.GetServiceName(); + auto fromParticipantName = serviceDescriptor.GetParticipantName(); + auto serviceId = serviceDescriptor.GetServiceId(); + + // We see a ServiceType::Link from someone else, so this is another netsim announcing the network + if (serviceType == SilKit::Core::ServiceType::Link && fromParticipantName != _participant->GetParticipantName()) + { + auto simulatedNetwork = LookupSimulatedNetwork(networkName, networkType); + if (simulatedNetwork) + { + auto errorMsg = "NetworkSimulation: Network '" + networkName + "' is already simulated by '" + + fromParticipantName + "'."; + _logger->Error(errorMsg); + throw SilKitError{errorMsg}; + } + } + if (serviceType != Core::ServiceType::Controller) + { + return; // Only remote controllers + } + if (!AllowedNetworkTypes.count(configNetworkType)) + { + return; // Only allowed network types + } + if (networkType == SimulatedNetworkType::Undefined) + { + throw SilKitError{"NetworkSimulation: Discovered network of undefined type"}; + } + if (networkName.empty()) + { + throw SilKitError{"NetworkSimulation: Empty network name"}; + } + if (controllerName.empty()) + { + throw SilKitError{"NetworkSimulation: Empty controller name"}; + } + + if (discoveryType == SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated) + { + OnNetworkDiscovered(networkName, networkType); + OnControllerDiscovered(serviceDescriptor); + } + else if (discoveryType == SilKit::Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved) + { + OnNetworkRemoved(networkName, networkType); + OnControllerRemoved(fromParticipantName, networkName, networkType, serviceId); + } +} + + +void NetworkSimulatorInternal::OnNetworkDiscovered(const std::string& networkName, + Experimental::NetworkSimulation::SimulatedNetworkType networkType) +{ + // Count all controllers per network to remove the network at some point + _controllerCountPerNetwork[networkName]++; + + if (_discoveredNetworks.count(networkName)) + { + return; // Already known + } + + // Add new network + { + std::unique_lock lock{_discoveredNetworksMutex}; + _discoveredNetworks.insert(networkName); + } + + // If the new network is simulated, hand out an event producer to the user if not already done so + auto simulatedNetwork = LookupSimulatedNetwork(networkName, networkType); + if (simulatedNetwork) + { + if (!simulatedNetwork->HasEventProducer()) + { + simulatedNetwork->CreateAndSetEventProducer(); + } + } +} + +void NetworkSimulatorInternal::OnNetworkRemoved(const std::string& networkName, + Experimental::NetworkSimulation::SimulatedNetworkType /*networkType*/) +{ + _controllerCountPerNetwork[networkName]--; + + if (_controllerCountPerNetwork[networkName] != 0) + { + return; // Still some controllers left on the network + } + + // Remove network + { + std::unique_lock lock{_discoveredNetworksMutex}; + auto it = _discoveredNetworks.find(networkName); + if (it != _discoveredNetworks.end()) + { + _discoveredNetworks.erase(networkName); + } + } +} + +void NetworkSimulatorInternal::OnControllerDiscovered(const SilKit::Core::ServiceDescriptor& serviceDescriptor) +{ + auto configNetworkType = serviceDescriptor.GetNetworkType(); + auto networkType = ConvertNetworkTypeFromConfig(configNetworkType); + auto networkName = serviceDescriptor.GetNetworkName(); + + // Bookkeeping of the relation controllerDescriptor <-> serviceDescriptor + // Increases the controllerDescriptor even if the network is not simulated + auto nextControllerDescriptor = NextControllerDescriptor(); + auto insertResult = _serviceDescriptorByControllerDescriptor.insert({nextControllerDescriptor, serviceDescriptor}); + if (!insertResult.second) + { + throw SilKit::SilKitError{"ControllerDescriptor is already associated with a serviceDescriptor"}; + } + + // Add the controller on a registered SimulatedNetwork + auto simulatedNetwork = LookupSimulatedNetwork(networkName, networkType); + if (simulatedNetwork) + { + simulatedNetwork->AddSimulatedController(serviceDescriptor, nextControllerDescriptor); + } +} + +void NetworkSimulatorInternal::OnControllerRemoved(const std::string& fromParticipantName, + const std::string& networkName, + Experimental::NetworkSimulation::SimulatedNetworkType networkType, + Core::EndpointId serviceId) +{ + auto simulatedNetwork = LookupSimulatedNetwork(networkName, networkType); + if (simulatedNetwork) + { + simulatedNetwork->RemoveSimulatedController(fromParticipantName, serviceId); + } +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/source/experimental/netsim/NetworkSimulatorInternal.hpp b/SilKit/source/experimental/netsim/NetworkSimulatorInternal.hpp new file mode 100644 index 000000000..7f0e4e202 --- /dev/null +++ b/SilKit/source/experimental/netsim/NetworkSimulatorInternal.hpp @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include +#include + +#include "silkit/experimental/netsim/INetworkSimulator.hpp" +#include "INetworkSimulatorInternal.hpp" + +#include "IParticipantInternal.hpp" +#include "IServiceDiscovery.hpp" +#include "ILogger.hpp" + +#include "SimulatedNetworkRouter.hpp" +#include "SimulatedNetworkInternal.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +static const std::set AllowedNetworkTypes{ + SilKit::Config::NetworkType::CAN, + SilKit::Config::NetworkType::LIN, + SilKit::Config::NetworkType::FlexRay, + SilKit::Config::NetworkType::Ethernet, +}; + +class NetworkSimulatorInternal + : public INetworkSimulator + , public INetworkSimulatorInternal +{ +public: + NetworkSimulatorInternal(Core::IParticipantInternal* participant); + + // INetworkSimulator + void SimulateNetwork(const std::string& networkName, SimulatedNetworkType networkType, + std::unique_ptr simulatedNetwork) override; + + void Start() override; + + // INetworkSimulatorInternal + auto GetServiceDescriptorString(ControllerDescriptor controllerDescriptor) -> std::string const override; + + +private: + void CreateSimulatedNetwork(const std::string& networkName, SimulatedNetworkType networkType, + std::unique_ptr userSimulatedNetwork); + + void DiscoveryHandler(Core::Discovery::ServiceDiscoveryEvent::Type type, + const Core::ServiceDescriptor& serviceDescriptor); + + void OnNetworkDiscovered(const std::string& networkName, + const Experimental::NetworkSimulation::SimulatedNetworkType networkType); + void OnNetworkRemoved(const std::string& networkName, + const Experimental::NetworkSimulation::SimulatedNetworkType networkType); + + void OnControllerDiscovered(const SilKit::Core::ServiceDescriptor& serviceDescriptor); + void OnControllerRemoved(const std::string& fromParticipantName, const std::string& networkName, + Experimental::NetworkSimulation::SimulatedNetworkType networkType, + Core::EndpointId serviceId); + + auto LookupSimulatedNetwork(const std::string& networkName, + SimulatedNetworkType networkType) -> SimulatedNetworkInternal*; + + ControllerDescriptor NextControllerDescriptor(); + + Core::IParticipantInternal* _participant = nullptr; + SilKit::Services::Logging::ILogger* _logger; + std::mutex _discoveredNetworksMutex; + std::set _discoveredNetworks; + std::unordered_map _controllerCountPerNetwork; + + using SimulatedNetworksByNetworkName = + std::unordered_map>; + using SimulatedNetworksByTypeAndNetworkName = + std::unordered_map; + SimulatedNetworksByTypeAndNetworkName _simulatedNetworks; + + std::atomic _networkSimulatorStarted; + + std::unordered_map _serviceDescriptorByControllerDescriptor; + std::atomic _nextControllerDescriptor{0}; +}; + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/source/experimental/netsim/SimulatedNetworkInternal.cpp b/SilKit/source/experimental/netsim/SimulatedNetworkInternal.cpp new file mode 100644 index 000000000..afeb8b67d --- /dev/null +++ b/SilKit/source/experimental/netsim/SimulatedNetworkInternal.cpp @@ -0,0 +1,135 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "SimulatedNetworkInternal.hpp" + +#include "eventproducers/CanEventProducer.hpp" +#include "eventproducers/FlexRayEventProducer.hpp" +#include "eventproducers/EthernetEventProducer.hpp" +#include "eventproducers/LinEventProducer.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +SimulatedNetworkInternal::SimulatedNetworkInternal(Core::IParticipantInternal* participant, + const std::string& networkName, SimulatedNetworkType networkType, + std::unique_ptr userSimulatedNetwork) + : _participant{participant} + , _logger{participant->GetLogger()} + , _networkName{networkName} + , _networkType{networkType} + , _userSimulatedNetwork{std::move(userSimulatedNetwork)} +{ + _simulatedNetworkRouter = std::make_unique(_participant, _networkName, _networkType); +} + +void SimulatedNetworkInternal::CreateAndSetEventProducer() +{ + // Create EventProducer and hand over to user + std::unique_ptr eventProducer{}; + + switch (_networkType) + { + case SimulatedNetworkType::CAN: + eventProducer = std::make_unique(_simulatedNetworkRouter.get()); + _eventProducer = eventProducer.get(); + _userSimulatedNetwork->SetEventProducer(std::move(eventProducer)); + break; + case SimulatedNetworkType::FlexRay: + eventProducer = std::make_unique(_simulatedNetworkRouter.get()); + _eventProducer = eventProducer.get(); + _userSimulatedNetwork->SetEventProducer(std::move(eventProducer)); + break; + case SimulatedNetworkType::Ethernet: + eventProducer = std::make_unique(_simulatedNetworkRouter.get()); + _eventProducer = eventProducer.get(); + _userSimulatedNetwork->SetEventProducer(std::move(eventProducer)); + break; + case SimulatedNetworkType::LIN: + eventProducer = std::make_unique(_simulatedNetworkRouter.get()); + _eventProducer = eventProducer.get(); + _userSimulatedNetwork->SetEventProducer(std::move(eventProducer)); + break; + default: + break; + } +} + +void SimulatedNetworkInternal::AddSimulatedController(const SilKit::Core::ServiceDescriptor& serviceDescriptor, + ControllerDescriptor controllerDescriptor) +{ + auto controllerName = serviceDescriptor.GetServiceName(); + auto fromParticipantName = serviceDescriptor.GetParticipantName(); + auto serviceId = serviceDescriptor.GetServiceId(); + auto serviceDescriptorStr = serviceDescriptor.to_string(); + + _controllerDescriptors[fromParticipantName][serviceId] = controllerDescriptor; + + auto userSimulatedController = _userSimulatedNetwork->ProvideSimulatedController(controllerDescriptor); + + if (userSimulatedController) + { + _simulatedNetworkRouter->AddSimulatedController(fromParticipantName, controllerName, serviceId, + controllerDescriptor, userSimulatedController); + } + else + { + SilKit::Services::Logging::Warn( + _logger, "NetworkSimulation: No simulated controller was provided for controller '{}' on participant '{}'", + controllerName, fromParticipantName); + } +} + +auto SimulatedNetworkInternal::LookupControllerDescriptor( + const std::string& fromParticipantName, Core::EndpointId serviceId) -> std::pair +{ + auto it_controllerDescriptorsByParticipant = _controllerDescriptors.find(fromParticipantName); + if (it_controllerDescriptorsByParticipant != _controllerDescriptors.end()) + { + auto it_controllerDescriptorByServiceId = it_controllerDescriptorsByParticipant->second.find(serviceId); + if (it_controllerDescriptorByServiceId != it_controllerDescriptorsByParticipant->second.end()) + { + return {true, it_controllerDescriptorByServiceId->second}; + } + } + SilKit::Services::Logging::Error( + _logger, "NetworkSimulation: Cannot associate participant name + service Id to controller descriptor."); + return {false, {}}; +} + +void SimulatedNetworkInternal::RemoveControllerDescriptor(const std::string& fromParticipantName, + Core::EndpointId serviceId) +{ + auto it_controllerDescriptorsByParticipant = _controllerDescriptors.find(fromParticipantName); + if (it_controllerDescriptorsByParticipant != _controllerDescriptors.end()) + { + auto it_controllerDescriptorByServiceId = it_controllerDescriptorsByParticipant->second.find(serviceId); + if (it_controllerDescriptorByServiceId != it_controllerDescriptorsByParticipant->second.end()) + { + it_controllerDescriptorsByParticipant->second.erase(it_controllerDescriptorByServiceId); + } + if (it_controllerDescriptorsByParticipant->second.empty()) + { + _controllerDescriptors.erase(it_controllerDescriptorsByParticipant); + } + } +} + +void SimulatedNetworkInternal::RemoveSimulatedController(const std::string& fromParticipantName, + Core::EndpointId serviceId) +{ + auto controllerDescriptorLookup = LookupControllerDescriptor(fromParticipantName, serviceId); + if (controllerDescriptorLookup.first) + { + _userSimulatedNetwork->SimulatedControllerRemoved(controllerDescriptorLookup.second); + RemoveControllerDescriptor(fromParticipantName, serviceId); + _simulatedNetworkRouter->RemoveSimulatedController(fromParticipantName, serviceId, + controllerDescriptorLookup.second); + } +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/source/experimental/netsim/SimulatedNetworkInternal.hpp b/SilKit/source/experimental/netsim/SimulatedNetworkInternal.hpp new file mode 100644 index 000000000..3c771fe89 --- /dev/null +++ b/SilKit/source/experimental/netsim/SimulatedNetworkInternal.hpp @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "ILogger.hpp" +#include "SimulatedNetworkRouter.hpp" +#include "silkit/experimental/netsim/all.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +class SimulatedNetworkInternal +{ +public: + SimulatedNetworkInternal(Core::IParticipantInternal* participant, const std::string& networkName, + SimulatedNetworkType networkType, std::unique_ptr userSimulatedNetwork); + + void CreateAndSetEventProducer(); + void AddSimulatedController(const SilKit::Core::ServiceDescriptor& serviceDescriptor, + ControllerDescriptor controllerDescriptor); + void RemoveSimulatedController(const std::string& fromParticipantName, Core::EndpointId serviceId); + + bool HasEventProducer() + { + return _eventProducer != nullptr; + } + +private: + auto LookupControllerDescriptor(const std::string& fromParticipantName, + Core::EndpointId serviceId) -> std::pair; + void RemoveControllerDescriptor(const std::string& fromParticipantName, Core::EndpointId serviceId); + + Core::IParticipantInternal* _participant = nullptr; + SilKit::Services::Logging::ILogger* _logger; + + std::string _networkName; + SimulatedNetworkType _networkType; + + std::unique_ptr _simulatedNetworkRouter; + std::unique_ptr _userSimulatedNetwork; + + IEventProducer* _eventProducer{nullptr}; + + // Bookkeeping to get from participantName + serviceId to controllerDescriptor + using ControllerDescriptorByServiceId = std::unordered_map; + using ControllerDescriptorByParticipantAndServiceId = + std::unordered_map; + ControllerDescriptorByParticipantAndServiceId _controllerDescriptors; +}; + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/source/experimental/netsim/SimulatedNetworkRouter.cpp b/SilKit/source/experimental/netsim/SimulatedNetworkRouter.cpp new file mode 100644 index 000000000..0e45f7b93 --- /dev/null +++ b/SilKit/source/experimental/netsim/SimulatedNetworkRouter.cpp @@ -0,0 +1,474 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "SimulatedNetworkRouter.hpp" +#include "IServiceDiscovery.hpp" +#include "NetworkSimulatorDatatypesInternal.hpp" +#include "Configuration.hpp" +#include "silkit/experimental/netsim/string_utils.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +SimulatedNetworkRouter::SimulatedNetworkRouter(Core::IParticipantInternal* participant, const std::string& networkName, + SimulatedNetworkType networkType) + : _participant{participant} + , _networkName{networkName} + , _networkType{networkType} +{ + // Here we register one ISimulator per actually simulated network to not register for unnecessary bus msg types + // when simulating only one bus type. + _participant->RegisterSimulator(this, _networkName, _networkType); + + _participant->AddAsyncSubscriptionsCompletionHandler([this]() { + SilKit::Services::Logging::Debug(_participant->GetLogger(), "Announce simulation of network '{}' of type {}", + _networkName, to_string(_networkType)); + // Announcing the network via ServiceDiscovery. Controllers on that network switch to simulated mode. + AnnounceNetwork(_networkName, _networkType); + }); +} + +void SimulatedNetworkRouter::AnnounceNetwork(const std::string& networkName, SimulatedNetworkType networkType) +{ + auto configNetworkType = ConvertNetworkTypeToConfig(networkType); + + std::string simulatorName = _participant->GetParticipantName(); + SilKit::Core::ServiceDescriptor linkDescriptor{}; + linkDescriptor.SetParticipantNameAndComputeId(simulatorName); + linkDescriptor.SetNetworkType(configNetworkType); + linkDescriptor.SetNetworkName(networkName); + linkDescriptor.SetServiceName(networkName); + // Controller switch to 'simulated' mode if they discover a ServiceType::Link with their networkName + linkDescriptor.SetServiceType(SilKit::Core::ServiceType::Link); + _participant->GetServiceDiscovery()->NotifyServiceCreated(std::move(linkDescriptor)); +} + +bool SimulatedNetworkRouter::AllowReception(const SilKit::Core::IServiceEndpoint* from) +{ + // Block messages from network simulation + return from->GetServiceDescriptor().GetServiceType() != Core::ServiceType::SimulatedController; +} + +void SimulatedNetworkRouter::AddSimulatedController(const std::string& fromParticipantName, + const std::string& controllerName, Core::EndpointId serviceId, + ControllerDescriptor controllerDescriptor, + ISimulatedController* userSimulatedController) +{ + _simulatedControllers[fromParticipantName].insert({serviceId, userSimulatedController}); + + // Copy serviceDescriptor and overwrite with serviceId of receiving controller + auto targetController = std::make_unique(); + targetController->participantName = fromParticipantName; + auto fromCopy = Core::ServiceDescriptor(this->GetServiceDescriptor()); + fromCopy.SetServiceId(serviceId); + fromCopy.SetServiceType(Core::ServiceType::SimulatedController); + fromCopy.SetServiceName(controllerName); + + targetController->SetServiceDescriptor(std::move(fromCopy)); + _targetControllers.insert({controllerDescriptor, std::move(targetController)}); +} + +void SimulatedNetworkRouter::RemoveSimulatedController(const std::string& fromParticipantName, + Core::EndpointId serviceId, + ControllerDescriptor controllerDescriptor) +{ + // Remove from targetController map + auto it_targetControllerByControllerDescriptor = _targetControllers.find(controllerDescriptor); + if (it_targetControllerByControllerDescriptor != _targetControllers.end()) + { + _targetControllers.erase(controllerDescriptor); + } + + // Remove from lookup by participantName + serviceId + auto it_simulatedControllersByParticipant = _simulatedControllers.find(fromParticipantName); + if (it_simulatedControllersByParticipant != _simulatedControllers.end()) + { + auto it_simulatedControllersByServiceId = it_simulatedControllersByParticipant->second.find(serviceId); + if (it_simulatedControllersByServiceId != it_simulatedControllersByParticipant->second.end()) + { + it_simulatedControllersByParticipant->second.erase(it_simulatedControllersByServiceId); + } + if (it_simulatedControllersByParticipant->second.empty()) + { + _simulatedControllers.erase(it_simulatedControllersByParticipant); + } + } +} + +auto SimulatedNetworkRouter::GetSimulatedControllerFromServiceEndpoint(const SilKit::Core::IServiceEndpoint* from) + -> ISimulatedController* +{ + const auto fromParticipant = from->GetServiceDescriptor().GetParticipantName(); + const auto fromServiceId = from->GetServiceDescriptor().GetServiceId(); + auto it_simulatedControllersByParticipant = _simulatedControllers.find(fromParticipant); + if (it_simulatedControllersByParticipant != _simulatedControllers.end()) + { + auto it_simulatedControllersByServiceId = it_simulatedControllersByParticipant->second.find(fromServiceId); + if (it_simulatedControllersByServiceId != it_simulatedControllersByParticipant->second.end()) + { + return it_simulatedControllersByServiceId->second; + } + } + _participant->GetLogger()->Error( + "NetworkSimulation: No simulated controller was found to route message from participant '" + fromParticipant + + "', serviceId " + std::to_string(fromServiceId)); + return {}; +} + +// -------------------------------- +// Can +// -------------------------------- + +auto SimulatedNetworkRouter::GetSimulatedCanControllerFromServiceEndpoint(const SilKit::Core::IServiceEndpoint* from) + -> Can::ISimulatedCanController* +{ + return static_cast(GetSimulatedControllerFromServiceEndpoint(from)); +} + +void SimulatedNetworkRouter::ReceiveMsg(const SilKit::Core::IServiceEndpoint* from, + const SilKit::Services::Can::WireCanFrameEvent& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Can::CanFrameRequest netsimMsg; + netsimMsg.frame = ToCanFrame(msg.frame); + netsimMsg.userContext = msg.userContext; + + auto controller = GetSimulatedCanControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnFrameRequest(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const SilKit::Core::IServiceEndpoint* from, + const SilKit::Services::Can::CanConfigureBaudrate& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Can::CanConfigureBaudrate netsimMsg; + netsimMsg.baudRate = msg.baudRate; + netsimMsg.fdBaudRate = msg.fdBaudRate; + netsimMsg.xlBaudRate = msg.xlBaudRate; + + auto controller = GetSimulatedCanControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnSetBaudrate(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const SilKit::Core::IServiceEndpoint* from, + const SilKit::Services::Can::CanSetControllerMode& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Can::CanControllerMode netsimMsg{}; + if (msg.flags.resetErrorHandling) + { + netsimMsg.canControllerModeFlags |= SilKit_Experimental_NetSim_CanControllerModeFlags_ResetErrorHandling; + } + if (msg.flags.cancelTransmitRequests) + { + netsimMsg.canControllerModeFlags |= SilKit_Experimental_NetSim_CanControllerModeFlags_CancelTransmitRequests; + } + netsimMsg.state = msg.mode; + + auto controller = GetSimulatedCanControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnSetControllerMode(netsimMsg); + } +} + +// -------------------------------- +// FlexRay +// -------------------------------- + +auto SimulatedNetworkRouter::GetSimulatedFlexRayControllerFromServiceEndpoint( + const SilKit::Core::IServiceEndpoint* from) -> Flexray::ISimulatedFlexRayController* +{ + return static_cast(GetSimulatedControllerFromServiceEndpoint(from)); +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Flexray::FlexrayHostCommand& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Flexray::FlexrayHostCommand netsimMsg; + netsimMsg.command = static_cast(msg.command); + + auto controller = GetSimulatedFlexRayControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnHostCommand(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Flexray::FlexrayControllerConfig& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Flexray::FlexrayControllerConfig netsimMsg; + netsimMsg.bufferConfigs = msg.bufferConfigs; + netsimMsg.clusterParams = msg.clusterParams; + netsimMsg.nodeParams = msg.nodeParams; + + auto controller = GetSimulatedFlexRayControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnControllerConfig(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Flexray::FlexrayTxBufferConfigUpdate& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Flexray::FlexrayTxBufferConfigUpdate netsimMsg; + netsimMsg.txBufferConfig = msg.txBufferConfig; + netsimMsg.txBufferIndex = msg.txBufferIndex; + + auto controller = GetSimulatedFlexRayControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnTxBufferConfigUpdate(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Flexray::WireFlexrayTxBufferUpdate& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Flexray::FlexrayTxBufferUpdate netsimMsg; + netsimMsg.payload = msg.payload.AsSpan(); + netsimMsg.payloadDataValid = msg.payloadDataValid; + netsimMsg.txBufferIndex = msg.txBufferIndex; + + auto controller = GetSimulatedFlexRayControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnTxBufferUpdate(netsimMsg); + } +} + +// -------------------------------- +// Ethernet +// -------------------------------- + +auto SimulatedNetworkRouter::GetSimulatedEthernetControllerFromServiceEndpoint( + const SilKit::Core::IServiceEndpoint* from) -> Ethernet::ISimulatedEthernetController* +{ + return static_cast(GetSimulatedControllerFromServiceEndpoint(from)); +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Ethernet::WireEthernetFrameEvent& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Ethernet::EthernetFrameRequest netsimMsg; + netsimMsg.ethernetFrame = ToEthernetFrame(msg.frame); + netsimMsg.userContext = msg.userContext; + + auto controller = GetSimulatedEthernetControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnFrameRequest(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Ethernet::EthernetSetMode& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Ethernet::EthernetControllerMode netsimMsg; + switch (msg.mode) + { + case SilKit::Services::Ethernet::EthernetMode::Active: + netsimMsg.mode = Ethernet::EthernetMode::Active; + break; + case SilKit::Services::Ethernet::EthernetMode::Inactive: + netsimMsg.mode = Ethernet::EthernetMode::Inactive; + break; + default: + break; + } + + auto controller = GetSimulatedEthernetControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnSetControllerMode(netsimMsg); + } +} + +// -------------------------------- +// Lin +// -------------------------------- + +auto SimulatedNetworkRouter::GetSimulatedLinControllerFromServiceEndpoint(const SilKit::Core::IServiceEndpoint* from) + -> Lin::ISimulatedLinController* +{ + return static_cast(GetSimulatedControllerFromServiceEndpoint(from)); +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinSendFrameRequest& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Lin::LinFrameRequest netsimMsg; + netsimMsg.frame = msg.frame; + netsimMsg.responseType = msg.responseType; + + auto controller = GetSimulatedLinControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnFrameRequest(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinSendFrameHeaderRequest& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Lin::LinFrameHeaderRequest netsimMsg; + netsimMsg.id = msg.id; + + auto controller = GetSimulatedLinControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnFrameHeaderRequest(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinWakeupPulse& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Lin::LinWakeupPulse netsimMsg; + netsimMsg.timestamp = msg.timestamp; + + auto controller = GetSimulatedLinControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnWakeupPulse(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::WireLinControllerConfig& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Lin::LinControllerConfig netsimMsg; + netsimMsg.baudRate = msg.baudRate; + netsimMsg.controllerMode = msg.controllerMode; + netsimMsg.frameResponses = msg.frameResponses; + switch (msg.simulationMode) + { + case SilKit::Services::Lin::WireLinControllerConfig::SimulationMode::Default: + netsimMsg.simulationMode = Lin::LinControllerConfig::SimulationMode::Default; + break; + case SilKit::Services::Lin::WireLinControllerConfig::SimulationMode::Dynamic: + netsimMsg.simulationMode = Lin::LinControllerConfig::SimulationMode::Dynamic; + break; + default: + break; + } + + auto controller = GetSimulatedLinControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnControllerConfig(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinFrameResponseUpdate& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Lin::LinFrameResponseUpdate netsimMsg; + netsimMsg.frameResponses = msg.frameResponses; + + auto controller = GetSimulatedLinControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnFrameResponseUpdate(netsimMsg); + } +} + +void SimulatedNetworkRouter::ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinControllerStatusUpdate& msg) +{ + if (!AllowReception(from)) + { + return; + } + + Lin::LinControllerStatusUpdate netsimMsg; + netsimMsg.status = msg.status; + netsimMsg.timestamp = msg.timestamp; + + auto controller = GetSimulatedLinControllerFromServiceEndpoint(from); + if (controller) + { + controller->OnControllerStatusUpdate(netsimMsg); + } +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/source/experimental/netsim/SimulatedNetworkRouter.hpp b/SilKit/source/experimental/netsim/SimulatedNetworkRouter.hpp new file mode 100644 index 000000000..82b42b59e --- /dev/null +++ b/SilKit/source/experimental/netsim/SimulatedNetworkRouter.hpp @@ -0,0 +1,160 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "IParticipantInternal.hpp" +#include "ISimulator.hpp" +#include "IServiceEndpoint.hpp" + +#include "silkit/experimental/netsim/all.hpp" + +#include "WireCanMessages.hpp" +#include "WireEthernetMessages.hpp" +#include "WireFlexrayMessages.hpp" +#include "WireLinMessages.hpp" + +#include "ILogger.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { + +class SimulatedNetworkRouter : public Core::ISimulator +{ +public: + SimulatedNetworkRouter(Core::IParticipantInternal* participant, const std::string& networkName, + SimulatedNetworkType networkType); + + // ISimulator + + // IMsgForCanSimulator::IReceiver + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Can::WireCanFrameEvent& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Can::CanConfigureBaudrate& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Can::CanSetControllerMode& msg) override; + + // IMsgForFrBusSimulator::IReceiver + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Flexray::FlexrayHostCommand& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Flexray::FlexrayControllerConfig& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Flexray::FlexrayTxBufferConfigUpdate& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Flexray::WireFlexrayTxBufferUpdate& msg) override; + + // IMsgForEthSimulator::IReceiver + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Ethernet::WireEthernetFrameEvent& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Ethernet::EthernetSetMode& msg) override; + + // IMsgForLinSimulator::IReceiver + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinSendFrameRequest& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinSendFrameHeaderRequest& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinWakeupPulse& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::WireLinControllerConfig& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinFrameResponseUpdate& msg) override; + virtual void ReceiveMsg(const Core::IServiceEndpoint* from, + const SilKit::Services::Lin::LinControllerStatusUpdate& msg) override; + + template + void SendMsg(SilKitMessageT&& msg, const SilKit::Util::Span& receivers) + { + for (const auto& receiver : receivers) + { + auto targetController = _targetControllers.find(receiver); + if (targetController != _targetControllers.end()) + { + _participant->SendMsg(targetController->second.get(), targetController->second->participantName, msg); + } + else + { + _participant->GetLogger()->Warn("EventProvider has no receiving controller on network '" + _networkName + + "'"); + } + } + } + + // IServiceEndpoint + inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; + + void AddSimulatedController(const std::string& fromParticipantName, const std::string& controllerName, + Core::EndpointId serviceId, ControllerDescriptor controllerDescriptor, + ISimulatedController* userSimulatedController); + void RemoveSimulatedController(const std::string& fromParticipantName, Core::EndpointId serviceId, + ControllerDescriptor controllerDescriptor); + +private: + void AnnounceNetwork(const std::string& networkName, SimulatedNetworkType networkType); + bool AllowReception(const SilKit::Core::IServiceEndpoint* from); + auto GetSimulatedControllerFromServiceEndpoint(const SilKit::Core::IServiceEndpoint* from) -> ISimulatedController*; + + auto GetSimulatedCanControllerFromServiceEndpoint(const SilKit::Core::IServiceEndpoint* from) + -> Can::ISimulatedCanController*; + auto GetSimulatedFlexRayControllerFromServiceEndpoint(const SilKit::Core::IServiceEndpoint* from) + -> Flexray::ISimulatedFlexRayController*; + auto GetSimulatedEthernetControllerFromServiceEndpoint(const SilKit::Core::IServiceEndpoint* from) + -> Ethernet::ISimulatedEthernetController*; + auto GetSimulatedLinControllerFromServiceEndpoint(const SilKit::Core::IServiceEndpoint* from) + -> Lin::ISimulatedLinController*; + + Core::IParticipantInternal* _participant = nullptr; + std::string _networkName; + SimulatedNetworkType _networkType; + + struct TargetController : Core::IServiceEndpoint + { + std::string participantName; + Core::ServiceDescriptor _serviceDescriptor{}; + void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override + { + _serviceDescriptor = serviceDescriptor; + } + auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override + { + return _serviceDescriptor; + } + }; + std::unordered_map> _targetControllers; + + Core::ServiceDescriptor _serviceDescriptor{}; + + // ServiceId is unique per participant + using SimulatedControllersByServiceId = + std::unordered_map; + using SimulatedControllersByParticipantAndServiceId = + std::unordered_map; + SimulatedControllersByParticipantAndServiceId _simulatedControllers; +}; + +// ------------------------------------------------------------------------ +// Inline Implementation +// ------------------------------------------------------------------------ + +inline void SimulatedNetworkRouter::SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) +{ + _serviceDescriptor = serviceDescriptor; +} + +inline auto SimulatedNetworkRouter::GetServiceDescriptor() const -> const Core::ServiceDescriptor& +{ + return _serviceDescriptor; +} + +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit diff --git a/SilKit/source/experimental/netsim/eventproducers/CanEventProducer.cpp b/SilKit/source/experimental/netsim/eventproducers/CanEventProducer.cpp new file mode 100644 index 000000000..d38ff4c8c --- /dev/null +++ b/SilKit/source/experimental/netsim/eventproducers/CanEventProducer.cpp @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "CanEventProducer.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +namespace Can { + +CanEventProducer::CanEventProducer(SimulatedNetworkRouter* simulatedNetworkRouter) + : _simulatedNetworkRouter{simulatedNetworkRouter} +{ +} + +void CanEventProducer::Produce(const SilKit::Services::Can::CanFrameEvent& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(SilKit::Services::Can::MakeWireCanFrameEvent(msg), receivers); +} + +void CanEventProducer::Produce(const SilKit::Services::Can::CanFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(msg, receivers); +} + +void CanEventProducer::Produce(const SilKit::Services::Can::CanStateChangeEvent& msg, + const SilKit::Util::Span& receivers) +{ + SilKit::Services::Can::CanControllerStatus controllerStatus{}; + + // Transport the last used value that the receiving controller doesn't fire the corresponding handler + controllerStatus.errorState = _errorState; + _controllerState = msg.state; + + controllerStatus.controllerState = msg.state; + controllerStatus.timestamp = msg.timestamp; + _simulatedNetworkRouter->SendMsg(std::move(controllerStatus), receivers); +} + +void CanEventProducer::Produce(const SilKit::Services::Can::CanErrorStateChangeEvent& msg, + const SilKit::Util::Span& receivers) +{ + SilKit::Services::Can::CanControllerStatus controllerStatus{}; + + // Transport the last used value that the receiving controller doesn't fire the corresponding handler + controllerStatus.controllerState = _controllerState; + _errorState = msg.errorState; + + controllerStatus.errorState = msg.errorState; + controllerStatus.timestamp = msg.timestamp; + _simulatedNetworkRouter->SendMsg(std::move(controllerStatus), receivers); +} + +} // namespace Can +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/experimental/netsim/eventproducers/CanEventProducer.hpp b/SilKit/source/experimental/netsim/eventproducers/CanEventProducer.hpp new file mode 100644 index 000000000..577d9ed29 --- /dev/null +++ b/SilKit/source/experimental/netsim/eventproducers/CanEventProducer.hpp @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "silkit/experimental/netsim/INetworkSimulator.hpp" +#include "ISimulator.hpp" +#include "SimulatedNetworkRouter.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +namespace Can { + +class CanEventProducer : public ICanEventProducer +{ +public: + CanEventProducer(SimulatedNetworkRouter* busSimulator); + + // ICanEventProducer + void Produce(const SilKit::Services::Can::CanFrameEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Can::CanFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Can::CanStateChangeEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Can::CanErrorStateChangeEvent& msg, + const SilKit::Util::Span& receivers) override; + +private: + SimulatedNetworkRouter* _simulatedNetworkRouter; + + // Track the controller state and error state because the msg on wire (CanControllerStatus) contains both. + SilKit::Services::Can::CanControllerState _controllerState = SilKit::Services::Can::CanControllerState::Uninit; + SilKit::Services::Can::CanErrorState _errorState = SilKit::Services::Can::CanErrorState::NotAvailable; +}; + +} // namespace Can +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/experimental/netsim/eventproducers/EthernetEventProducer.cpp b/SilKit/source/experimental/netsim/eventproducers/EthernetEventProducer.cpp new file mode 100644 index 000000000..f5544790f --- /dev/null +++ b/SilKit/source/experimental/netsim/eventproducers/EthernetEventProducer.cpp @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "EthernetEventProducer.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +namespace Ethernet { + +EthernetEventProducer::EthernetEventProducer(SimulatedNetworkRouter* simulatedNetworkRouter) + : _simulatedNetworkRouter{simulatedNetworkRouter} +{ +} + +void EthernetEventProducer::Produce(const SilKit::Services::Ethernet::EthernetFrameEvent& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(SilKit::Services::Ethernet::MakeWireEthernetFrameEvent(msg), receivers); +} + +void EthernetEventProducer::Produce(const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(msg, receivers); +} + +void EthernetEventProducer::Produce(const SilKit::Services::Ethernet::EthernetStateChangeEvent& msg, + const SilKit::Util::Span& receivers) +{ + SilKit::Services::Ethernet::EthernetStatus wireMsg{}; + + // Transport the last used value that the receiving controller doesn't fire the corresponding handler + wireMsg.bitrate = _ethernetBitrate; + _ethernetState = msg.state; + + wireMsg.state = msg.state; + wireMsg.timestamp = msg.timestamp; + _simulatedNetworkRouter->SendMsg(std::move(wireMsg), receivers); +} + +void EthernetEventProducer::Produce(const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& msg, + const SilKit::Util::Span& receivers) +{ + SilKit::Services::Ethernet::EthernetStatus wireMsg{}; + + // Transport the last used value that the receiving controller doesn't fire the corresponding handler + wireMsg.state = _ethernetState; + _ethernetBitrate = msg.bitrate; + + wireMsg.bitrate = msg.bitrate; + wireMsg.timestamp = msg.timestamp; + _simulatedNetworkRouter->SendMsg(std::move(wireMsg), receivers); +} + +} // namespace Ethernet +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/experimental/netsim/eventproducers/EthernetEventProducer.hpp b/SilKit/source/experimental/netsim/eventproducers/EthernetEventProducer.hpp new file mode 100644 index 000000000..36c9c48b9 --- /dev/null +++ b/SilKit/source/experimental/netsim/eventproducers/EthernetEventProducer.hpp @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "silkit/experimental/netsim/INetworkSimulator.hpp" +#include "ISimulator.hpp" +#include "SimulatedNetworkRouter.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +namespace Ethernet { + +class EthernetEventProducer : public IEthernetEventProducer +{ +public: + EthernetEventProducer(SimulatedNetworkRouter* busSimulator); + + // IEthernetEventProducer + void Produce(const SilKit::Services::Ethernet::EthernetFrameEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Ethernet::EthernetFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Ethernet::EthernetStateChangeEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Ethernet::EthernetBitrateChangeEvent& msg, + const SilKit::Util::Span& receivers) override; + +private: + SimulatedNetworkRouter* _simulatedNetworkRouter; + + // Track the state and bitrate because the msg on wire (EthernetStatus) contains both. + SilKit::Services::Ethernet::EthernetState _ethernetState = SilKit::Services::Ethernet::EthernetState::Inactive; + SilKit::Services::Ethernet::EthernetBitrate _ethernetBitrate = SilKit::Services::Ethernet::EthernetBitrate{}; +}; + +} // namespace Ethernet +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/experimental/netsim/eventproducers/FlexRayEventProducer.cpp b/SilKit/source/experimental/netsim/eventproducers/FlexRayEventProducer.cpp new file mode 100644 index 000000000..5fae8f47f --- /dev/null +++ b/SilKit/source/experimental/netsim/eventproducers/FlexRayEventProducer.cpp @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "FlexRayEventProducer.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +namespace Flexray { + +FlexRayEventProducer::FlexRayEventProducer(SimulatedNetworkRouter* simulatedNetworkRouter) + : _simulatedNetworkRouter{simulatedNetworkRouter} +{ +} + +void FlexRayEventProducer::Produce(const SilKit::Services::Flexray::FlexrayFrameEvent& msg, + const SilKit::Util::Span& receivers) +{ + auto wireMsg = SilKit::Services::Flexray::MakeWireFlexrayFrameEvent(msg); + _simulatedNetworkRouter->SendMsg(std::move(wireMsg), receivers); +} + +void FlexRayEventProducer::Produce(const SilKit::Services::Flexray::FlexrayFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers) +{ + auto wireMsg = SilKit::Services::Flexray::MakeWireFlexrayFrameTransmitEvent(msg); + _simulatedNetworkRouter->SendMsg(std::move(wireMsg), receivers); +} + +void FlexRayEventProducer::Produce(const SilKit::Services::Flexray::FlexraySymbolEvent& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(msg, receivers); +} + +void FlexRayEventProducer::Produce(const SilKit::Services::Flexray::FlexraySymbolTransmitEvent& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(msg, receivers); +} + +void FlexRayEventProducer::Produce(const SilKit::Services::Flexray::FlexrayCycleStartEvent& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(msg, receivers); +} + +void FlexRayEventProducer::Produce(const SilKit::Services::Flexray::FlexrayPocStatusEvent& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(msg, receivers); +} + +} // namespace Flexray +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/experimental/netsim/eventproducers/FlexRayEventProducer.hpp b/SilKit/source/experimental/netsim/eventproducers/FlexRayEventProducer.hpp new file mode 100644 index 000000000..7b5f9f1a1 --- /dev/null +++ b/SilKit/source/experimental/netsim/eventproducers/FlexRayEventProducer.hpp @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "silkit/experimental/netsim/INetworkSimulator.hpp" +#include "ISimulator.hpp" +#include "SimulatedNetworkRouter.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +namespace Flexray { + +class FlexRayEventProducer : public IFlexRayEventProducer +{ +public: + FlexRayEventProducer(SimulatedNetworkRouter* busSimulator); + + // IFlexRayEventProducer + + void Produce(const SilKit::Services::Flexray::FlexrayFrameEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Flexray::FlexrayFrameTransmitEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Flexray::FlexraySymbolEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Flexray::FlexraySymbolTransmitEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Flexray::FlexrayCycleStartEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Flexray::FlexrayPocStatusEvent& msg, + const SilKit::Util::Span& receivers) override; + +private: + SimulatedNetworkRouter* _simulatedNetworkRouter; +}; + +} // namespace Flexray +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/experimental/netsim/eventproducers/LinEventProducer.cpp b/SilKit/source/experimental/netsim/eventproducers/LinEventProducer.cpp new file mode 100644 index 000000000..f904ab6d6 --- /dev/null +++ b/SilKit/source/experimental/netsim/eventproducers/LinEventProducer.cpp @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "LinEventProducer.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +namespace Lin { + +LinEventProducer::LinEventProducer(SimulatedNetworkRouter* simulatedNetworkRouter) + : _simulatedNetworkRouter{simulatedNetworkRouter} +{ +} + + +void LinEventProducer::Produce(const SilKit::Services::Lin::LinFrameStatusEvent& msg, + const SilKit::Util::Span& receivers) +{ + SilKit::Services::Lin::LinTransmission wireMsg{}; + wireMsg.frame = msg.frame; + wireMsg.status = msg.status; + wireMsg.timestamp = msg.timestamp; + _simulatedNetworkRouter->SendMsg(std::move(wireMsg), receivers); +} + +void LinEventProducer::Produce(const SilKit::Services::Lin::LinSendFrameHeaderRequest& msg, + const SilKit::Util::Span& receivers) +{ + _simulatedNetworkRouter->SendMsg(std::move(msg), receivers); +} + +void LinEventProducer::Produce(const SilKit::Services::Lin::LinWakeupEvent& msg, + const SilKit::Util::Span& receivers) +{ + SilKit::Services::Lin::LinWakeupPulse wireMsg{}; + wireMsg.direction = msg.direction; + wireMsg.timestamp = msg.timestamp; + _simulatedNetworkRouter->SendMsg(std::move(wireMsg), receivers); +} + +} // namespace Lin +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/experimental/netsim/eventproducers/LinEventProducer.hpp b/SilKit/source/experimental/netsim/eventproducers/LinEventProducer.hpp new file mode 100644 index 000000000..22ed1070b --- /dev/null +++ b/SilKit/source/experimental/netsim/eventproducers/LinEventProducer.hpp @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: 2024 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#include "silkit/experimental/netsim/INetworkSimulator.hpp" +#include "ISimulator.hpp" +#include "SimulatedNetworkRouter.hpp" + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +namespace Lin { + +class LinEventProducer : public ILinEventProducer +{ +public: + LinEventProducer(SimulatedNetworkRouter* busSimulator); + + // ILinEventProducer + void Produce(const SilKit::Services::Lin::LinFrameStatusEvent& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Lin::LinSendFrameHeaderRequest& msg, + const SilKit::Util::Span& receivers) override; + + void Produce(const SilKit::Services::Lin::LinWakeupEvent& msg, + const SilKit::Util::Span& receivers) override; + +private: + SimulatedNetworkRouter* _simulatedNetworkRouter; +}; + +} // namespace Lin +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/experimental/participant/ParticipantExtensionsImpl.cpp b/SilKit/source/experimental/participant/ParticipantExtensionsImpl.cpp index bebd7aa52..d65f484c6 100644 --- a/SilKit/source/experimental/participant/ParticipantExtensionsImpl.cpp +++ b/SilKit/source/experimental/participant/ParticipantExtensionsImpl.cpp @@ -42,6 +42,22 @@ auto CreateSystemControllerImpl(IParticipant* participant) return participantInternal->GetSystemController(); } +auto CreateNetworkSimulatorImpl(IParticipant* participant) + -> SilKit::Experimental::NetworkSimulation::INetworkSimulator* +{ + auto participantInternal = dynamic_cast(participant); + if (participantInternal == nullptr) + { + throw SilKitError("participant is not a valid SilKit::IParticipant*"); + } + if (participantInternal->GetIsNetworkSimulatorCreated()) + { + throw SilKitError("You may not create the network simulator more than once."); + } + participantInternal->SetIsNetworkSimulatorCreated(true); + return participantInternal->CreateNetworkSimulator(); +} + } // namespace Participant } // namespace Experimental } // namespace SilKit diff --git a/SilKit/source/experimental/participant/ParticipantExtensionsImpl.hpp b/SilKit/source/experimental/participant/ParticipantExtensionsImpl.hpp index ee3b0f688..bbea1794c 100644 --- a/SilKit/source/experimental/participant/ParticipantExtensionsImpl.hpp +++ b/SilKit/source/experimental/participant/ParticipantExtensionsImpl.hpp @@ -43,6 +43,13 @@ class ISystemController; } // namespace Experimental } // namespace SilKit +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +class INetworkSimulator; +} // namespace NetworkSimulation +} // namespace Experimental +} // namespace SilKit // Function Declarations @@ -53,6 +60,9 @@ namespace Participant { auto CreateSystemControllerImpl(IParticipant* participant) -> SilKit::Experimental::Services::Orchestration::ISystemController*; +auto CreateNetworkSimulatorImpl(IParticipant* participant) + -> SilKit::Experimental::NetworkSimulation::INetworkSimulator*; + } // namespace Participant } // namespace Experimental } // namespace SilKit diff --git a/SilKit/source/experimental/participant/Test_ParticipantExtensionsImpl.cpp b/SilKit/source/experimental/participant/Test_ParticipantExtensionsImpl.cpp index e4a5fcae3..c56b20ef0 100644 --- a/SilKit/source/experimental/participant/Test_ParticipantExtensionsImpl.cpp +++ b/SilKit/source/experimental/participant/Test_ParticipantExtensionsImpl.cpp @@ -60,4 +60,23 @@ TEST_F(Test_ParticipantExtensionsImpl, error_on_create_system_controller_twice) EXPECT_THROW(SilKit::Experimental::Participant::CreateSystemControllerImpl(participant.get()), SilKit::SilKitError); } +TEST_F(Test_ParticipantExtensionsImpl, create_network_simulator_not_null) +{ + auto participant = + CreateNullConnectionParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), "TestParticipant"); + + auto networkSimulator = SilKit::Experimental::Participant::CreateNetworkSimulatorImpl(participant.get()); + EXPECT_NE(networkSimulator, nullptr); +} + +TEST_F(Test_ParticipantExtensionsImpl, error_on_create_network_simulator_twice) +{ + auto participant = + CreateNullConnectionParticipantImpl(SilKit::Config::MakeEmptyParticipantConfigurationImpl(), "TestParticipant"); + + auto networkSimulator = SilKit::Experimental::Participant::CreateNetworkSimulatorImpl(participant.get()); + SILKIT_UNUSED_ARG(networkSimulator); + EXPECT_THROW(SilKit::Experimental::Participant::CreateNetworkSimulatorImpl(participant.get()), SilKit::SilKitError); +} + } // anonymous namespace diff --git a/SilKit/source/experimental/services/lin/LinControllerExtensionsImpl.cpp b/SilKit/source/experimental/services/lin/LinControllerExtensionsImpl.cpp index 2653d7ff5..494a94758 100644 --- a/SilKit/source/experimental/services/lin/LinControllerExtensionsImpl.cpp +++ b/SilKit/source/experimental/services/lin/LinControllerExtensionsImpl.cpp @@ -46,14 +46,14 @@ namespace Services { namespace Lin { auto AddLinSlaveConfigurationHandlerImpl(SilKit::Services::Lin::ILinController* linController, - SilKit::Experimental::Services::Lin::LinSlaveConfigurationHandler handler) + SilKit::Experimental::Services::Lin::LinSlaveConfigurationHandler handler) -> SilKit::Util::HandlerId { return GetLinController(linController)->AddLinSlaveConfigurationHandler(handler); } void RemoveLinSlaveConfigurationHandlerImpl(SilKit::Services::Lin::ILinController* linController, - SilKit::Util::HandlerId handlerId) + SilKit::Util::HandlerId handlerId) { return GetLinController(linController)->RemoveLinSlaveConfigurationHandler(handlerId); } @@ -65,27 +65,27 @@ auto GetSlaveConfigurationImpl(SilKit::Services::Lin::ILinController* linControl } void InitDynamicImpl(SilKit::Services::Lin::ILinController* linController, - const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig) + const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig) { return GetLinController(linController)->InitDynamic(dynamicConfig); } auto AddFrameHeaderHandlerImpl(SilKit::Services::Lin::ILinController* linController, - std::function - handler) -> SilKit::Util::HandlerId + std::function + handler) -> SilKit::Util::HandlerId { return GetLinController(linController)->AddFrameHeaderHandler(handler); } void RemoveFrameHeaderHandlerImpl(SilKit::Services::Lin::ILinController* linController, - SilKit::Util::HandlerId handlerId) + SilKit::Util::HandlerId handlerId) { return GetLinController(linController)->RemoveFrameHeaderHandler(handlerId); } void SendDynamicResponseImpl(SilKit::Services::Lin::ILinController* linController, - const SilKit::Services::Lin::LinFrame& frame) + const SilKit::Services::Lin::LinFrame& frame) { return GetLinController(linController)->SendDynamicResponse(frame); } diff --git a/SilKit/source/extensions/SilKitExtensionApi/ISilKitExtension.hpp b/SilKit/source/extensions/SilKitExtensionApi/ISilKitExtension.hpp index e5066282d..b23db7880 100644 --- a/SilKit/source/extensions/SilKitExtensionApi/ISilKitExtension.hpp +++ b/SilKit/source/extensions/SilKitExtensionApi/ISilKitExtension.hpp @@ -21,7 +21,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once -namespace SilKit { +namespace SilKit { //! \brief The interface for all SIL Kit extensions. @@ -31,9 +31,8 @@ class ISilKitExtension virtual ~ISilKitExtension() = default; virtual const char* GetExtensionName() const = 0; virtual const char* GetVendorName() const = 0; - virtual void GetVersion(uint32_t& major, - uint32_t& minor, uint32_t& patch) const = 0; -}; + virtual void GetVersion(uint32_t& major, uint32_t& minor, uint32_t& patch) const = 0; +}; -}//end namespace SilKit +} //end namespace SilKit diff --git a/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionABI.h b/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionABI.h index ff840ba30..3a440912c 100644 --- a/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionABI.h +++ b/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionABI.h @@ -34,51 +34,53 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ */ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif //__cplusplus #include #include //NULL #if defined(_WIN32) -# define SILEXT_API __declspec(dllexport) -# define SILEXT_CABI __cdecl +#define SILEXT_API __declspec(dllexport) +#define SILEXT_CABI __cdecl #else -# define SILEXT_API __attribute__((visibility ("default"))) -# define SILEXT_CABI +#define SILEXT_API __attribute__((visibility("default"))) +#define SILEXT_CABI #endif -//! \brief The SilKitExtensionDescriptor is a simple C structure that contains -//! interoperability information. -//! This structure is provided by the dynamic library at load time, and the -//! extension mechanism verifies that the extension is compatible with the host -//! SIL Kit system, before accessing the Create/Release routines. + //! \brief The SilKitExtensionDescriptor is a simple C structure that contains + //! interoperability information. + //! This structure is provided by the dynamic library at load time, and the + //! extension mechanism verifies that the extension is compatible with the host + //! SIL Kit system, before accessing the Create/Release routines. -struct SilKitExtensionDescriptor { - uint32_t silkit_version_major; - uint32_t silkit_version_minor; - uint32_t silkit_version_patch; - const char* extension_name; - const char* vendor_name; - const char* system_name; // eg, distribution or operating system name - uint32_t build_infos[5]; // See SilKitExtension.hpp for values -}; -typedef struct SilKitExtensionDescriptor SilKitExtensionDescriptor_t; + struct SilKitExtensionDescriptor + { + uint32_t silkit_version_major; + uint32_t silkit_version_minor; + uint32_t silkit_version_patch; + const char* extension_name; + const char* vendor_name; + const char* system_name; // eg, distribution or operating system name + uint32_t build_infos[5]; // See SilKitExtension.hpp for values + }; + typedef struct SilKitExtensionDescriptor SilKitExtensionDescriptor_t; -//! \brief The silkit_extension_descriptor marks the entry point for an extension -// shared library. -SILEXT_API extern const SilKitExtensionDescriptor_t silkit_extension_descriptor; + //! \brief The silkit_extension_descriptor marks the entry point for an extension + // shared library. + SILEXT_API extern const SilKitExtensionDescriptor_t silkit_extension_descriptor; //! \brief Handle to a C++ instance of an extension #define SILEXT_EXTENSION_HANDLE void* #define SILEXT_INVALID_HANDLE NULL -//! \brief Extension API entry point: Instantiates the extension implementation -// given the descriptor. -SILEXT_API SILEXT_EXTENSION_HANDLE SILEXT_CABI CreateExtension(); + //! \brief Extension API entry point: Instantiates the extension implementation + // given the descriptor. + SILEXT_API SILEXT_EXTENSION_HANDLE SILEXT_CABI CreateExtension(); -//! \brief Extension API entry point: Releases the extension implementation. -SILEXT_API void SILEXT_CABI ReleaseExtension(SILEXT_EXTENSION_HANDLE extension); + //! \brief Extension API entry point: Releases the extension implementation. + SILEXT_API void SILEXT_CABI ReleaseExtension(SILEXT_EXTENSION_HANDLE extension); #ifdef __cplusplus } diff --git a/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionBase.hpp b/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionBase.hpp old mode 100755 new mode 100644 index dfdad8484..6c605d2fd --- a/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionBase.hpp +++ b/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionBase.hpp @@ -30,19 +30,18 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "SilKitExtensionABI.h" #include "ISilKitExtension.hpp" -namespace SilKit { +namespace SilKit { -//! \brief For convenience, implements an extension base with nice +//! \brief For convenience, implements an extension base with nice // accessors to the extension descriptor. class SilKitExtensionBase : public ISilKitExtension { public: - //! \brief The Ctor relies on the externally defined - // silkit_extension_descriptor from the implementation of the + // silkit_extension_descriptor from the implementation of the // extension library. SilKitExtensionBase() - :_descriptor(silkit_extension_descriptor) + : _descriptor(silkit_extension_descriptor) { } @@ -56,8 +55,7 @@ class SilKitExtensionBase : public ISilKitExtension return _descriptor.vendor_name; } - void GetVersion(uint32_t& major, - uint32_t& minor, uint32_t& patch) const + void GetVersion(uint32_t& major, uint32_t& minor, uint32_t& patch) const { major = _descriptor.silkit_version_major; minor = _descriptor.silkit_version_minor; @@ -65,10 +63,8 @@ class SilKitExtensionBase : public ISilKitExtension } private: - - const SilKitExtensionDescriptor_t& _descriptor; + const SilKitExtensionDescriptor_t& _descriptor; }; - -}//end namespace SilKit +} //end namespace SilKit diff --git a/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionMacros.hpp b/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionMacros.hpp old mode 100755 new mode 100644 index ac7f72a2c..4c2010288 --- a/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionMacros.hpp +++ b/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionMacros.hpp @@ -27,42 +27,37 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define STRFY(x) #x //! \brief Return build info array for the current platform -#define SILKIT_MAKE_BUILDINFOS()\ - {\ - SilKit::BuildinfoCPlusPlus(),\ - SilKit::BuildinfoCompiler(),\ - SilKit::BuildinfoMultithread(),\ - SilKit::BuildinfoDebug()\ - } +#define SILKIT_MAKE_BUILDINFOS() \ + {SilKit::BuildinfoCPlusPlus(), SilKit::BuildinfoCompiler(), SilKit::BuildinfoMultithread(), \ + SilKit::BuildinfoDebug()} -//! Declare extern C entry points for a extension and instantiate the +//! Declare extern C entry points for a extension and instantiate the // C++ interface. #define SILKIT_DECLARE_EXTENSION(CLASS_NAME, VENDOR_STR, VMAJOR, VMINOR, VPATCH) \ - extern "C" {\ - const SilKitExtensionDescriptor_t silkit_extension_descriptor{\ - VMAJOR,\ - VMINOR,\ - VPATCH,\ - STRFY(CLASS_NAME),\ - VENDOR_STR,\ - SilKit::BuildinfoSystem(),\ - SILKIT_MAKE_BUILDINFOS()\ - };\ - }\ - SILEXT_API SILEXT_EXTENSION_HANDLE SILEXT_CABI CreateExtension()\ - {\ - try {\ - SilKit::ISilKitExtension* instance = new CLASS_NAME();\ - return instance;\ + extern "C" \ + { \ + const SilKitExtensionDescriptor_t silkit_extension_descriptor{VMAJOR, \ + VMINOR, \ + VPATCH, \ + STRFY(CLASS_NAME), \ + VENDOR_STR, \ + SilKit::BuildinfoSystem(), \ + SILKIT_MAKE_BUILDINFOS()}; \ + } \ + SILEXT_API SILEXT_EXTENSION_HANDLE SILEXT_CABI CreateExtension() \ + { \ + try \ + { \ + SilKit::ISilKitExtension* instance = new CLASS_NAME(); \ + return instance; \ } \ - catch(...) \ + catch (...) \ { \ - return SILEXT_INVALID_HANDLE;\ - }\ - }\ - SILEXT_API void SILEXT_CABI ReleaseExtension(SILEXT_EXTENSION_HANDLE extension)\ - {\ - auto* instance = static_cast(extension);\ - delete instance;\ + return SILEXT_INVALID_HANDLE; \ + } \ + } \ + SILEXT_API void SILEXT_CABI ReleaseExtension(SILEXT_EXTENSION_HANDLE extension) \ + { \ + auto* instance = static_cast(extension); \ + delete instance; \ } - diff --git a/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionUtils.hpp b/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionUtils.hpp old mode 100755 new mode 100644 index 76bd17f36..fa9894b34 --- a/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionUtils.hpp +++ b/SilKit/source/extensions/SilKitExtensionApi/SilKitExtensionUtils.hpp @@ -24,10 +24,10 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #if !defined(SILKIT_EXTENSION_OS) -# error "SILKIT_EXTENSION_OS must be defined for the compiler via CMake for the target platform" +#error "SILKIT_EXTENSION_OS must be defined for the compiler via CMake for the target platform" #endif -namespace SilKit { +namespace SilKit { //! \brief Fields of the BuildInfo array enum class BuildInfoField { @@ -52,7 +52,7 @@ constexpr const char* BuildinfoSystem() } //! \brief Encodes the C++ language standard version. -// This value is used to make sure that the C++ runtime libraries and STL are +// This value is used to make sure that the C++ runtime libraries and STL are // compatible. // Returns an unsigned integer encoding the C++ standard version, e.g. 201402L. constexpr uint32_t BuildinfoCPlusPlus() @@ -66,7 +66,7 @@ constexpr uint32_t BuildinfoCPlusPlus() return _MSVC_LANG; #else //GCC and clang always set __cplusplus to current standard version. - return __cplusplus; + return __cplusplus; #endif } @@ -80,24 +80,26 @@ constexpr uint32_t BuildinfoCPlusPlus() constexpr uint32_t BuildinfoCompiler() { #if defined(_MSC_VER) -# if defined(SILKIT_MSVC_TOOLSET_VERSION) +#if defined(SILKIT_MSVC_TOOLSET_VERSION) // We rely on CMake to provide proper toolset version. return SILKIT_MSVC_TOOLSET_VERSION; -# elif defined(_MSVC_STL_VERSION) +#elif defined(_MSVC_STL_VERSION) // In case newer, future toolset is not recognized by CMake: // On VS2015/17/19 _MSVC_STL_VERSION contains the toolset number, e.g. 141, 142 etc. return _MSVC_STL_VERSION; -# endif +#endif #else -# if defined(_WIN32) && defined(__GNUC__) +#if defined(_WIN32) && defined(__GNUC__) //MinGW return 0; -# elif defined( __GNUC__) +#elif defined(__clang__) + return __clang_major__; +#elif defined(__GNUC__) // the major version of a GNU compiler, the C++ macro _GLIBCXX_RELEASE defaults to this return __GNUC__; -# else - #error Platform has no Extension support -# endif +#else +#error Platform has no Extension support +#endif #endif } @@ -112,7 +114,7 @@ constexpr uint32_t BuildinfoMultithread() #ifdef _MT // MSVC defines _MT. return 1; -#elif defined(_REENTRANT) +#elif defined(_REENTRANT) return 1; #else return 0; @@ -134,4 +136,4 @@ constexpr uint32_t BuildinfoDebug() } -}//end namespace SilKit +} //end namespace SilKit diff --git a/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.cpp b/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.cpp old mode 100755 new mode 100644 index f6a8bd2de..3e366e9ed --- a/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.cpp +++ b/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.cpp @@ -34,25 +34,22 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "SilKitExtensionLoader.hpp" #include "ParticipantConfiguration.hpp" -namespace SilKit { +namespace SilKit { -auto CreateMdf4Tracing(Config::ParticipantConfiguration config, - SilKit::Services::Logging::ILogger* logger, - const std::string& participantName, - const std::string& sinkName) - -> std::unique_ptr +auto CreateMdf4Tracing(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, + const std::string& participantName, + const std::string& sinkName) -> std::unique_ptr { auto& factory = SilKitExtensionLoader(logger, "SilKitExtension_Mdf", config.extensions); return factory.Create(std::move(config), logger, participantName, sinkName); } auto CreateMdf4Replay(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, - const std::string& fileName) - -> std::shared_ptr + const std::string& fileName) -> std::shared_ptr { auto& factory = SilKitExtensionLoader(logger, "SilKitExtension_Mdf", config.extensions); return factory.OpenFile(config, fileName, logger); } -}//end namespace SilKit +} //end namespace SilKit diff --git a/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.hpp b/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.hpp old mode 100755 new mode 100644 index 7dab7eb21..bd2d24e45 --- a/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.hpp +++ b/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.hpp @@ -30,19 +30,18 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ParticipantConfiguration.hpp" -namespace SilKit { +namespace SilKit { -auto CreateMdf4Tracing(Config::ParticipantConfiguration config, - SilKit::Services::Logging::ILogger* logger, const std::string& participantName, const std::string& sinkName) - -> std::unique_ptr; +auto CreateMdf4Tracing(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, + const std::string& participantName, + const std::string& sinkName) -> std::unique_ptr; ////////////////////////////////////////////////////////////////////// // MDF4 Replay ////////////////////////////////////////////////////////////////////// auto CreateMdf4Replay(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, - const std::string& fileName) - -> std::shared_ptr; + const std::string& fileName) -> std::shared_ptr; -}//end namespace SilKit +} //end namespace SilKit diff --git a/SilKit/source/extensions/SilKitExtensionImpl/DllCache.hpp b/SilKit/source/extensions/SilKitExtensionImpl/DllCache.hpp old mode 100755 new mode 100644 index 53a7fc06e..c283c2157 --- a/SilKit/source/extensions/SilKitExtensionImpl/DllCache.hpp +++ b/SilKit/source/extensions/SilKitExtensionImpl/DllCache.hpp @@ -42,8 +42,8 @@ namespace SilKit { class DllCache { public: - auto Get(Services::Logging::ILogger* logger, const std::string& extensionName, const Config::Extensions& config) - -> SilKit::ISilKitExtension& + auto Get(Services::Logging::ILogger* logger, const std::string& extensionName, + const Config::Extensions& config) -> SilKit::ISilKitExtension& { try { diff --git a/SilKit/source/extensions/SilKitExtensionImpl/SilKitExtensionLoader.hpp b/SilKit/source/extensions/SilKitExtensionImpl/SilKitExtensionLoader.hpp old mode 100755 new mode 100644 index 11278864f..951bb3576 --- a/SilKit/source/extensions/SilKitExtensionImpl/SilKitExtensionLoader.hpp +++ b/SilKit/source/extensions/SilKitExtensionImpl/SilKitExtensionLoader.hpp @@ -28,17 +28,15 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "SilKitExtensions.hpp" #include "DllCache.hpp" -namespace SilKit { +namespace SilKit { //! \brief FactorySingleton creates an instance of the given interface. // The underlying extension library is cached using a static DllCache instance, // which keeps the shared library loaded during the lifetime of the calling process. -template -auto SilKitExtensionLoader(Services::Logging::ILogger* logger, - const std::string& extensionName, - const Config::Extensions& config) - -> FactoryT& +template +auto SilKitExtensionLoader(Services::Logging::ILogger* logger, const std::string& extensionName, + const Config::Extensions& config) -> FactoryT& { static DllCache cache; //the dll instance must be kept alive, especially when exceptions are thrown in the factory @@ -51,12 +49,10 @@ auto SilKitExtensionLoader(Services::Logging::ILogger* logger, catch (const std::bad_cast& err) { std::stringstream msg; - msg << "Error loading SILKIT extension '" << extensionName - << "': " << err.what(); + msg << "Error loading SILKIT extension '" << extensionName << "': " << err.what(); logger->Error(msg.str()); throw ExtensionError(msg.str()); } - } -}//end namespace SilKit +} //end namespace SilKit diff --git a/SilKit/source/extensions/SilKitExtensions.cpp b/SilKit/source/extensions/SilKitExtensions.cpp old mode 100755 new mode 100644 index de027f288..69d6cf47e --- a/SilKit/source/extensions/SilKitExtensions.cpp +++ b/SilKit/source/extensions/SilKitExtensions.cpp @@ -20,7 +20,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef WIN32 -# define _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS #endif #include "SilKitExtensions.hpp" @@ -182,8 +182,8 @@ auto LoadExtension(Services::Logging::ILogger* logger, const std::string& name) return LoadExtension(logger, name, Config::Extensions{}); } -auto LoadExtension(Services::Logging::ILogger* logger, const std::string& name, const Config::Extensions& config) - -> std::shared_ptr +auto LoadExtension(Services::Logging::ILogger* logger, const std::string& name, + const Config::Extensions& config) -> std::shared_ptr { using namespace detail; @@ -250,11 +250,11 @@ auto LoadExtension(Services::Logging::ILogger* logger, const std::string& name, auto* extension = static_cast(create_ext()); return {extension, [lib_handle, release_ext](ISilKitExtension* instance) { - //call the cleanup code inside the module - release_ext(instance); - //unload the actual shared library - CloseLibrary(lib_handle); - }}; + //call the cleanup code inside the module + release_ext(instance); + //unload the actual shared library + CloseLibrary(lib_handle); + }}; } diff --git a/SilKit/source/extensions/SilKitExtensions.hpp b/SilKit/source/extensions/SilKitExtensions.hpp old mode 100755 new mode 100644 index 3b577a4fc..d335c5ad8 --- a/SilKit/source/extensions/SilKitExtensions.hpp +++ b/SilKit/source/extensions/SilKitExtensions.hpp @@ -47,7 +47,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ * For implementing an extension in shared module form, refer to the * SilKitExtensionApi/ folder. */ -namespace SilKit { +namespace SilKit { //! \brief Lookup paths to consider when loading dynamic, shared modules using ExtensionPathHints = std::vector; @@ -57,15 +57,14 @@ using ExtensionPathHints = std::vector; // extensions. // The first match is loaded. auto LoadExtension(Services::Logging::ILogger* logger, - const std::string& undecorated_name) -> std::shared_ptr; + const std::string& undecorated_name) -> std::shared_ptr; //! \brief Loads the extension by name and uses the additional search path hints from // the extension configuration. //! NB: a path hint can contain the prefix "ENV:" to refer to an environment //! variable name. -auto LoadExtension(Services::Logging::ILogger* logger, - const std::string& undecorated_name, const Config::Extensions& config) - -> std::shared_ptr; +auto LoadExtension(Services::Logging::ILogger* logger, const std::string& undecorated_name, + const Config::Extensions& config) -> std::shared_ptr; -}//end namespace SilKit +} //end namespace SilKit diff --git a/SilKit/source/extensions/Tests/DummyExtension.cpp b/SilKit/source/extensions/Tests/DummyExtension.cpp old mode 100755 new mode 100644 index 991180c9f..e32cc9fd7 --- a/SilKit/source/extensions/Tests/DummyExtension.cpp +++ b/SilKit/source/extensions/Tests/DummyExtension.cpp @@ -26,10 +26,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Define shared library extension for linking -SILKIT_DECLARE_EXTENSION( - DummyExtension, - "Vector", - SilKit::Version::Major(), - SilKit::Version::Minor(), - SilKit::Version::Patch() -) +SILKIT_DECLARE_EXTENSION(DummyExtension, "Vector", SilKit::Version::Major(), SilKit::Version::Minor(), + SilKit::Version::Patch()) diff --git a/SilKit/source/extensions/Tests/Test_SilKitExtensions.cpp b/SilKit/source/extensions/Tests/Test_SilKitExtensions.cpp old mode 100755 new mode 100644 index 2718fcad8..a7b2a616f --- a/SilKit/source/extensions/Tests/Test_SilKitExtensions.cpp +++ b/SilKit/source/extensions/Tests/Test_SilKitExtensions.cpp @@ -43,8 +43,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using namespace testing; -namespace -{ +namespace { std::string GetCurrentWorkingDir() { return SilKit::Filesystem::current_path().string(); @@ -55,7 +54,7 @@ void SetCurrentWorkingDir(const std::string& cwd) SilKit::Filesystem::current_path(cwd); } -class StdoutLogger: public SilKit::Core::Tests::MockLogger +class StdoutLogger : public SilKit::Core::Tests::MockLogger { public: void Info(const std::string& msg) override @@ -75,7 +74,7 @@ class StdoutLogger: public SilKit::Core::Tests::MockLogger std::cout << "SilKitExtensionTest: Error: " << msg << std::endl; } }; -} +} // namespace class Test_SilKitExtensions : public Test { @@ -87,7 +86,7 @@ class Test_SilKitExtensions : public Test } static void SetUpTestCase() - { + { currentWorkingDir = GetCurrentWorkingDir(); } @@ -108,27 +107,21 @@ TEST_F(Test_SilKitExtensions, load_dummy_lib) { auto otherInstance = SilKit::LoadExtension(&logger, "DummyExtension"); - std::cout <<" created second instance of DummyExtension" << std::endl; + std::cout << " created second instance of DummyExtension" << std::endl; } ASSERT_NE(dummyExtension, nullptr); std::string name{dummyExtension->GetExtensionName()}; - ASSERT_EQ(name, "DummyExtension"); + ASSERT_EQ(name, "DummyExtension"); std::string vendor{dummyExtension->GetVendorName()}; - ASSERT_EQ(vendor, "Vector"); + ASSERT_EQ(vendor, "Vector"); triple version; - triple reference{ - SilKit::Version::Major(), - SilKit::Version::Minor(), - SilKit::Version::Patch() - }; - - dummyExtension->GetVersion(std::get<0>(version), std::get<1>(version), - std::get<2>(version)); - ASSERT_EQ(version, reference); + triple reference{SilKit::Version::Major(), SilKit::Version::Minor(), SilKit::Version::Patch()}; + dummyExtension->GetVersion(std::get<0>(version), std::get<1>(version), std::get<2>(version)); + ASSERT_EQ(version, reference); } //must not crash when going out of scope } @@ -152,25 +145,18 @@ TEST_F(Test_SilKitExtensions, wrong_version_number) { auto extension = SilKit::LoadExtension(&logger, "WrongVersionExtension"); triple version; - triple reference{ - SilKit::Version::Major(), - SilKit::Version::Minor(), - SilKit::Version::Patch() - }; - extension->GetVersion(std::get<0>(version), std::get<1>(version), - std::get<2>(version)); + triple reference{SilKit::Version::Major(), SilKit::Version::Minor(), SilKit::Version::Patch()}; + extension->GetVersion(std::get<0>(version), std::get<1>(version), std::get<2>(version)); ASSERT_EQ(version, reference); } catch (const SilKit::ExtensionError& error) { const std::string msg{error.what()}; - std::cout << "OK: received expected version mismatch error" - << std::endl; + std::cout << "OK: received expected version mismatch error" << std::endl; return; } FAIL() << "expected an ExtensionError when loading a shared library with\ wrong version number"; - } TEST_F(Test_SilKitExtensions, wrong_build_system) @@ -207,6 +193,5 @@ TEST_F(Test_SilKitExtensions, load_from_envvar) auto* mod1 = dynamic_cast(base1.get()); mod1->SetDummyValue(1); EXPECT_EQ(mod1->GetDummyValue(), 1); - } #endif diff --git a/SilKit/source/extensions/Tests/WrongBuildSystem.cpp b/SilKit/source/extensions/Tests/WrongBuildSystem.cpp old mode 100755 new mode 100644 index 0ed86767c..83d7eca6f --- a/SilKit/source/extensions/Tests/WrongBuildSystem.cpp +++ b/SilKit/source/extensions/Tests/WrongBuildSystem.cpp @@ -31,15 +31,9 @@ struct WrongBuildSystem : public SilKit::SilKitExtensionBase }; // Manually declare entry symbol -extern "C" const SilKitExtensionDescriptor_t silkit_extension_descriptor -{ - SilKit::Version::Major(), - SilKit::Version::Minor(), - SilKit::Version::Patch(), - "WrongBuildSystem", - "Vector", - "IncompatibleBuildHost", - SILKIT_MAKE_BUILDINFOS(), +extern "C" const SilKitExtensionDescriptor_t silkit_extension_descriptor{ + SilKit::Version::Major(), SilKit::Version::Minor(), SilKit::Version::Patch(), "WrongBuildSystem", "Vector", + "IncompatibleBuildHost", SILKIT_MAKE_BUILDINFOS(), }; SILEXT_API SILEXT_EXTENSION_HANDLE SILEXT_CABI CreateExtension() @@ -49,6 +43,6 @@ SILEXT_API SILEXT_EXTENSION_HANDLE SILEXT_CABI CreateExtension() SILEXT_API void SILEXT_CABI ReleaseExtension(SILEXT_EXTENSION_HANDLE extension) { - auto* instance = static_cast(extension); + auto* instance = static_cast(extension); delete instance; } diff --git a/SilKit/source/extensions/Tests/WrongVersionExtension.cpp b/SilKit/source/extensions/Tests/WrongVersionExtension.cpp old mode 100755 new mode 100644 index 50226906a..76f1f8fe3 --- a/SilKit/source/extensions/Tests/WrongVersionExtension.cpp +++ b/SilKit/source/extensions/Tests/WrongVersionExtension.cpp @@ -28,11 +28,4 @@ struct WrongVersionExtension : public SilKit::SilKitExtensionBase using SilKitExtensionBase::SilKitExtensionBase; }; -SILKIT_DECLARE_EXTENSION( - WrongVersionExtension, - "Vector", - 1, - 2, - 3 -) - +SILKIT_DECLARE_EXTENSION(WrongVersionExtension, "Vector", 1, 2, 3) diff --git a/SilKit/source/extensions/detail/LoadExtension.hpp b/SilKit/source/extensions/detail/LoadExtension.hpp old mode 100755 new mode 100644 index 393d178b6..048843198 --- a/SilKit/source/extensions/detail/LoadExtension.hpp +++ b/SilKit/source/extensions/detail/LoadExtension.hpp @@ -24,11 +24,12 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #if defined(_WIN32) -# define WIN32_LEAN_AND_MEAN -# include +#define WIN32_LEAN_AND_MEAN +#include #endif -namespace SilKit { namespace detail { +namespace SilKit { +namespace detail { #if defined(_WIN32) diff --git a/SilKit/source/extensions/detail/LoadExtension_posix.cpp b/SilKit/source/extensions/detail/LoadExtension_posix.cpp old mode 100755 new mode 100644 index 3c340dbeb..82803edbf --- a/SilKit/source/extensions/detail/LoadExtension_posix.cpp +++ b/SilKit/source/extensions/detail/LoadExtension_posix.cpp @@ -35,15 +35,16 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "LoadExtension.hpp" -namespace SilKit { namespace detail { +namespace SilKit { +namespace detail { //used by FindLibrary #if defined(__APPLE__) -const std::string lib_file_extension=".dylib"; +const std::string lib_file_extension = ".dylib"; #else -const std::string lib_file_extension=".so"; +const std::string lib_file_extension = ".so"; #endif -const std::string lib_prefix="lib"; +const std::string lib_prefix = "lib"; const std::string path_sep = "/"; bool FileExists(const std::string& path) @@ -54,7 +55,7 @@ bool FileExists(const std::string& path) LibraryHandle OpenLibrary(const std::string& path) { void* tmp = ::dlopen(path.c_str(), RTLD_NOW); - if(tmp == nullptr) + if (tmp == nullptr) { throw ExtensionError("::dlopen() failed: " + std::string{dlerror()}); } @@ -63,12 +64,10 @@ LibraryHandle OpenLibrary(const std::string& path) void* FindSymbol(LibraryHandle& hnd, const std::string& symbol_name) { - void* sym = dlsym(hnd, symbol_name.c_str()); - if(sym == nullptr) + void* sym = dlsym(hnd, symbol_name.c_str()); + if (sym == nullptr) { - throw ExtensionError("Calling dlsym() failed: Could not find \"" - + symbol_name +"\"" + std::string{dlerror()} - ); + throw ExtensionError("Calling dlsym() failed: Could not find \"" + symbol_name + "\"" + std::string{dlerror()}); } return sym; } @@ -90,7 +89,7 @@ std::string GetProcessPath() buf.resize(PATH_MAX); auto proc = std::string("/proc/") + std::to_string(getpid()) + "/exe"; auto nb = readlink(proc.c_str(), buf.data(), buf.size()); - if ( nb < 0) + if (nb < 0) { return "."; } @@ -100,6 +99,6 @@ std::string GetProcessPath() return std::string{processDir}; } -}//detail +} // namespace detail -}//silkit +} // namespace SilKit diff --git a/SilKit/source/extensions/detail/LoadExtension_win.cpp b/SilKit/source/extensions/detail/LoadExtension_win.cpp old mode 100755 new mode 100644 index 86156de39..aa00c7792 --- a/SilKit/source/extensions/detail/LoadExtension_win.cpp +++ b/SilKit/source/extensions/detail/LoadExtension_win.cpp @@ -29,29 +29,23 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "LoadExtension.hpp" -#if !defined( F_OK ) -# define F_OK 00 //not provided by io.h, but used in _access() +#if !defined(F_OK) +#define F_OK 00 //not provided by io.h, but used in _access() #endif -namespace SilKit { namespace detail { +namespace SilKit { +namespace detail { static std::string lastErrorMessage() { std::string rv{}; DWORD e = ::GetLastError(); - if(e != 0) + if (e != 0) { LPSTR buf = nullptr; - size_t size = FormatMessageA( - FORMAT_MESSAGE_ALLOCATE_BUFFER - | FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - e, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&buf, - 0, - nullptr); + size_t size = + FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, nullptr); rv.assign(buf, size); LocalFree(buf); @@ -61,9 +55,9 @@ static std::string lastErrorMessage() //used by FindLibrary -const std::string lib_file_extension=".dll"; -const std::string lib_prefix=""; -const std::string path_sep="\\"; +const std::string lib_file_extension = ".dll"; +const std::string lib_prefix = ""; +const std::string path_sep = "\\"; bool FileExists(const std::string& path) { @@ -73,7 +67,7 @@ bool FileExists(const std::string& path) LibraryHandle OpenLibrary(const std::string& path) { LibraryHandle tmp = ::LoadLibraryA(path.c_str()); - if(tmp == nullptr) + if (tmp == nullptr) { throw ExtensionError("::LoadLibrary() failed: " + lastErrorMessage()); } @@ -83,22 +77,19 @@ LibraryHandle OpenLibrary(const std::string& path) void CloseLibrary(const LibraryHandle& hnd) { BOOL ok = ::FreeLibrary(hnd); - if(!ok) + if (!ok) { - throw ExtensionError( - "Calling FreeLibrary failed: " + lastErrorMessage()); + throw ExtensionError("Calling FreeLibrary failed: " + lastErrorMessage()); } } void* FindSymbol(LibraryHandle& hnd, const std::string& symbol_name) { auto* entry = (void*)::GetProcAddress(hnd, symbol_name.c_str()); - if(entry == nullptr) + if (entry == nullptr) { - throw ExtensionError( - "Calling GetProcAddress() failed: Could not find \"" - + symbol_name +"\"" + lastErrorMessage() - ); + throw ExtensionError("Calling GetProcAddress() failed: Could not find \"" + symbol_name + "\"" + + lastErrorMessage()); } return entry; } @@ -118,6 +109,6 @@ std::string GetProcessPath() return path; } -}//detail +} // namespace detail -}//silkit +} // namespace SilKit diff --git a/SilKit/source/services/can/CanController.cpp b/SilKit/source/services/can/CanController.cpp index 0fa3f671b..671769442 100755 --- a/SilKit/source/services/can/CanController.cpp +++ b/SilKit/source/services/can/CanController.cpp @@ -55,6 +55,11 @@ void CanController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated && IsRelevantNetwork(remoteServiceDescriptor)) { + Logging::Info(_logger, + "Controller '{}' is using the simulated network '{}' and will route all messages to " + "the network simulator '{}'", + _config.name, remoteServiceDescriptor.GetNetworkName(), + remoteServiceDescriptor.GetParticipantName()); SetDetailedBehavior(remoteServiceDescriptor); } } @@ -63,6 +68,10 @@ void CanController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved && IsRelevantNetwork(remoteServiceDescriptor)) { + Logging::Warn(_logger, + "The network simulator for controller '{}' left the simulation. The controller is no " + "longer simulated.", + _config.name); SetTrivialBehavior(); } } @@ -73,12 +82,12 @@ void CanController::SetDetailedBehavior(const Core::ServiceDescriptor& remoteSer { _simulationBehavior.SetDetailedBehavior(remoteServiceDescriptor); } + void CanController::SetTrivialBehavior() { _simulationBehavior.SetTrivialBehavior(); } - auto CanController::GetState() -> CanControllerState { return _controllerState; @@ -156,8 +165,8 @@ void CanController::SendFrame(const CanFrame& frame, void* userContext) { // do not allow user messages from the public API. // ReplaySend will send all frames. - Logging::Debug(_logger, _logOnce, - "CanController: Ignoring SendFrame API call due to Replay config on {}", _config.name); + Logging::Debug(_logger, _logOnce, "CanController: Ignoring SendFrame API call due to Replay config on {}", + _config.name); return; } WireCanFrameEvent wireCanFrameEvent{}; @@ -180,8 +189,8 @@ void CanController::ReceiveMsg(const IServiceEndpoint* from, const WireCanFrameE if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Receive)) { - Logging::Debug(_logger, _logOnce, - "CanController: Ignoring ReceiveMsg API call due to Replay config on {}", _config.name); + Logging::Debug(_logger, _logOnce, "CanController: Ignoring ReceiveMsg API call due to Replay config on {}", + _config.name); return; } @@ -219,12 +228,12 @@ void CanController::ReceiveMsg(const IServiceEndpoint* from, const CanController if (_controllerState != msg.controllerState) { _controllerState = msg.controllerState; - CallHandlers(CanStateChangeEvent{ msg.timestamp, msg.controllerState }); + CallHandlers(CanStateChangeEvent{msg.timestamp, msg.controllerState}); } if (_errorState != msg.errorState) { _errorState = msg.errorState; - CallHandlers(CanErrorStateChangeEvent{ msg.timestamp, msg.errorState }); + CallHandlers(CanErrorStateChangeEvent{msg.timestamp, msg.errorState}); } } @@ -279,7 +288,7 @@ void CanController::ReplayReceive(const IReplayMessage* replayMessage) msg.frame = std::move(frameEvent.frame); msg.direction = TransmitDirection::RX; msg.userContext = nullptr; - + const auto msgEvent = ToCanFrameEvent(msg); _tracer.Trace(msg.direction, msg.timestamp, msgEvent); CallHandlers(msgEvent); diff --git a/SilKit/source/services/can/CanController.hpp b/SilKit/source/services/can/CanController.hpp old mode 100755 new mode 100644 index c67f6837d..01e9df2f9 --- a/SilKit/source/services/can/CanController.hpp +++ b/SilKit/source/services/can/CanController.hpp @@ -62,7 +62,7 @@ class CanController CanController(const CanController&) = delete; CanController(CanController&&) = delete; CanController(Core::IParticipantInternal* participant, SilKit::Config::CanController config, - Services::Orchestration::ITimeProvider* timeProvider); + Services::Orchestration::ITimeProvider* timeProvider); public: // ---------------------------------------- @@ -95,9 +95,8 @@ class CanController HandlerId AddErrorStateChangeHandler(ErrorStateChangeHandler handler) override; void RemoveErrorStateChangeHandler(HandlerId handlerId) override; - HandlerId AddFrameTransmitHandler( - FrameTransmitHandler handler, - CanTransmitStatusMask statusMask = SilKit_CanTransmitStatus_DefaultMask) override; + HandlerId AddFrameTransmitHandler(FrameTransmitHandler handler, + CanTransmitStatusMask statusMask = SilKit_CanTransmitStatus_DefaultMask) override; void RemoveFrameTransmitHandler(HandlerId handlerId) override; // IMsgForCanController @@ -110,10 +109,10 @@ class CanController // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; // IReplayDataController - void ReplayMessage(const SilKit::IReplayMessage *message) override; + void ReplayMessage(const SilKit::IReplayMessage* message) override; public: // ---------------------------------------- @@ -127,7 +126,7 @@ class CanController auto GetState() -> CanControllerState; - auto GetTracer() -> Tracer *; + auto GetTracer() -> Tracer*; private: // ---------------------------------------- @@ -172,8 +171,8 @@ class CanController inline void SendMsg(MsgT&& msg); // IReplayDataProvider Implementation - void ReplaySend(const IReplayMessage * replayMessage); - void ReplayReceive(const IReplayMessage * replayMessage); + void ReplaySend(const IReplayMessage* replayMessage); + void ReplayReceive(const IReplayMessage* replayMessage); private: // ---------------------------------------- @@ -189,17 +188,14 @@ class CanController CanControllerState _controllerState = CanControllerState::Uninit; CanErrorState _errorState = CanErrorState::NotAvailable; - CanConfigureBaudrate _baudRate = { 0, 0, 0 }; + CanConfigureBaudrate _baudRate = {0, 0, 0}; template using FilteredCallbacks = Util::SynchronizedHandlers>; - std::tuple< - FilteredCallbacks, - FilteredCallbacks, - FilteredCallbacks, - FilteredCallbacks - > _callbacks; + std::tuple, FilteredCallbacks, + FilteredCallbacks, FilteredCallbacks> + _callbacks; }; // ================================================================================ @@ -221,7 +217,7 @@ auto CanController::GetServiceDescriptor() const -> const Core::ServiceDescripto return _serviceDescriptor; } -inline auto CanController::GetTracer() -> Tracer * +inline auto CanController::GetTracer() -> Tracer* { return &_tracer; } diff --git a/SilKit/source/services/can/CanDatatypesUtils.cpp b/SilKit/source/services/can/CanDatatypesUtils.cpp index 4453a8931..3efd8ebe8 100644 --- a/SilKit/source/services/can/CanDatatypesUtils.cpp +++ b/SilKit/source/services/can/CanDatatypesUtils.cpp @@ -27,20 +27,13 @@ namespace Can { bool operator==(const CanFrame& lhs, const CanFrame& rhs) { - return lhs.canId == rhs.canId - && lhs.flags == rhs.flags - && lhs.dlc == rhs.dlc - && lhs.sdt == rhs.sdt - && lhs.vcid == rhs.vcid - && lhs.af == rhs.af - && Util::ItemsAreEqual(lhs.dataField, rhs.dataField); + return lhs.canId == rhs.canId && lhs.flags == rhs.flags && lhs.dlc == rhs.dlc && lhs.sdt == rhs.sdt + && lhs.vcid == rhs.vcid && lhs.af == rhs.af && Util::ItemsAreEqual(lhs.dataField, rhs.dataField); } bool operator==(const CanFrameEvent& lhs, const CanFrameEvent& rhs) { - return lhs.timestamp == rhs.timestamp - && lhs.frame == rhs.frame - && lhs.userContext == rhs.userContext; + return lhs.timestamp == rhs.timestamp && lhs.frame == rhs.frame && lhs.userContext == rhs.userContext; ; } @@ -51,30 +44,26 @@ bool operator==(const CanFrameTransmitEvent& lhs, const CanFrameTransmitEvent& r bool operator==(const CanSetControllerMode& lhs, const CanSetControllerMode& rhs) { - return lhs.mode == rhs.mode - && lhs.flags.cancelTransmitRequests == rhs.flags.cancelTransmitRequests - && lhs.flags.resetErrorHandling == rhs.flags.resetErrorHandling; + return lhs.mode == rhs.mode && lhs.flags.cancelTransmitRequests == rhs.flags.cancelTransmitRequests + && lhs.flags.resetErrorHandling == rhs.flags.resetErrorHandling; } bool operator==(const CanConfigureBaudrate& lhs, const CanConfigureBaudrate& rhs) { - return lhs.baudRate == rhs.baudRate - && lhs.fdBaudRate == rhs.fdBaudRate; + return lhs.baudRate == rhs.baudRate && lhs.fdBaudRate == rhs.fdBaudRate; } bool operator==(const CanStateChangeEvent& lhs, const CanStateChangeEvent& rhs) { - return lhs.timestamp == rhs.timestamp - && lhs.state == rhs.state; + return lhs.timestamp == rhs.timestamp && lhs.state == rhs.state; } bool operator==(const CanErrorStateChangeEvent& lhs, const CanErrorStateChangeEvent& rhs) { - return lhs.timestamp == rhs.timestamp - && lhs.errorState == rhs.errorState; + return lhs.timestamp == rhs.timestamp && lhs.errorState == rhs.errorState; } -bool operator==(const WireCanFrameEvent& lhs, const WireCanFrameEvent&rhs) +bool operator==(const WireCanFrameEvent& lhs, const WireCanFrameEvent& rhs) { return ToCanFrameEvent(lhs) == ToCanFrameEvent(rhs); } diff --git a/SilKit/source/services/can/CanDatatypesUtils.hpp b/SilKit/source/services/can/CanDatatypesUtils.hpp index 99a3c0388..d79a1a96f 100644 --- a/SilKit/source/services/can/CanDatatypesUtils.hpp +++ b/SilKit/source/services/can/CanDatatypesUtils.hpp @@ -35,7 +35,7 @@ bool operator==(const CanFrameTransmitEvent& lhs, const CanFrameTransmitEvent& r bool operator==(const CanStateChangeEvent& lhs, const CanStateChangeEvent& rhs); bool operator==(const CanErrorStateChangeEvent& lhs, const CanErrorStateChangeEvent& rhs); -bool operator==(const WireCanFrameEvent& lhs, const WireCanFrameEvent&rhs); +bool operator==(const WireCanFrameEvent& lhs, const WireCanFrameEvent& rhs); bool operator==(const CanSetControllerMode& lhs, const CanSetControllerMode& rhs); bool operator==(const CanConfigureBaudrate& lhs, const CanConfigureBaudrate& rhs); diff --git a/SilKit/source/services/can/CanSerdes.cpp b/SilKit/source/services/can/CanSerdes.cpp index 603a0da55..d5e44802d 100644 --- a/SilKit/source/services/can/CanSerdes.cpp +++ b/SilKit/source/services/can/CanSerdes.cpp @@ -30,100 +30,64 @@ namespace Can { SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const WireCanFrameEvent& msg) { - buffer - << msg.timestamp - << msg.frame.canId - << msg.frame.flags - << msg.frame.dlc - << msg.frame.sdt - << msg.frame.vcid - << msg.frame.af - << msg.frame.dataField - << msg.direction - << msg.userContext - ; + buffer << msg.timestamp << msg.frame.canId << msg.frame.flags << msg.frame.dlc << msg.frame.sdt << msg.frame.vcid + << msg.frame.af << msg.frame.dataField << msg.direction << msg.userContext; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, WireCanFrameEvent& msg) { - buffer - >> msg.timestamp - >> msg.frame.canId - >> msg.frame.flags - >> msg.frame.dlc - >> msg.frame.sdt - >> msg.frame.vcid - >> msg.frame.af - >> msg.frame.dataField - >> msg.direction - >> msg.userContext - ; + buffer >> msg.timestamp >> msg.frame.canId >> msg.frame.flags >> msg.frame.dlc >> msg.frame.sdt >> msg.frame.vcid + >> msg.frame.af >> msg.frame.dataField >> msg.direction >> msg.userContext; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const CanFrameTransmitEvent& ack) { - buffer << ack.canId - << ack.timestamp - << ack.status - << ack.userContext; + buffer << ack.canId << ack.timestamp << ack.status << ack.userContext; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, CanFrameTransmitEvent& ack) { - buffer >> ack.canId - >> ack.timestamp - >> ack.status - >> ack.userContext; + buffer >> ack.canId >> ack.timestamp >> ack.status >> ack.userContext; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const CanControllerStatus& msg) { - buffer << msg.timestamp - << msg.controllerState - << msg.errorState; + buffer << msg.timestamp << msg.controllerState << msg.errorState; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, CanControllerStatus& msg) { - buffer >> msg.timestamp - >> msg.controllerState - >> msg.errorState; + buffer >> msg.timestamp >> msg.controllerState >> msg.errorState; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const CanConfigureBaudrate& msg) { - buffer << msg.baudRate - << msg.fdBaudRate - << msg.xlBaudRate; + buffer << msg.baudRate << msg.fdBaudRate << msg.xlBaudRate; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, CanConfigureBaudrate& msg) { - buffer >> msg.baudRate - >> msg.fdBaudRate - >> msg.xlBaudRate; + buffer >> msg.baudRate >> msg.fdBaudRate >> msg.xlBaudRate; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const CanSetControllerMode& msg) { - buffer << *reinterpret_cast(&msg.flags) - << msg.mode; + buffer << *reinterpret_cast(&msg.flags) << msg.mode; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, CanSetControllerMode& msg) { uint8_t flags; - buffer >> flags - >> msg.mode; + buffer >> flags >> msg.mode; *reinterpret_cast(&msg.flags) = flags; return buffer; } @@ -167,27 +131,27 @@ void Serialize(MessageBuffer& buffer, const Services::Can::CanSetControllerMode& void Deserialize(MessageBuffer& buffer, Services::Can::WireCanFrameEvent& out) { - buffer >> out; + buffer >> out; } void Deserialize(MessageBuffer& buffer, Services::Can::CanFrameTransmitEvent& out) { - buffer >> out; + buffer >> out; } void Deserialize(MessageBuffer& buffer, Services::Can::CanControllerStatus& out) { - buffer >> out; + buffer >> out; } void Deserialize(MessageBuffer& buffer, Services::Can::CanConfigureBaudrate& out) { - buffer >> out; + buffer >> out; } void Deserialize(MessageBuffer& buffer, Services::Can::CanSetControllerMode& out) { - buffer >> out; + buffer >> out; } } // namespace Can diff --git a/SilKit/source/services/can/CanSerdes.hpp b/SilKit/source/services/can/CanSerdes.hpp index eb20e0e51..6d7780ba7 100644 --- a/SilKit/source/services/can/CanSerdes.hpp +++ b/SilKit/source/services/can/CanSerdes.hpp @@ -30,11 +30,11 @@ namespace SilKit { namespace Services { namespace Can { -void Serialize(SilKit::Core::MessageBuffer& buffer,const Services::Can::WireCanFrameEvent& msg); -void Serialize(SilKit::Core::MessageBuffer& buffer,const Services::Can::CanFrameTransmitEvent& msg); -void Serialize(SilKit::Core::MessageBuffer& buffer,const Services::Can::CanControllerStatus& msg); -void Serialize(SilKit::Core::MessageBuffer& buffer,const Services::Can::CanConfigureBaudrate& msg); -void Serialize(SilKit::Core::MessageBuffer& buffer,const Services::Can::CanSetControllerMode& msg); +void Serialize(SilKit::Core::MessageBuffer& buffer, const Services::Can::WireCanFrameEvent& msg); +void Serialize(SilKit::Core::MessageBuffer& buffer, const Services::Can::CanFrameTransmitEvent& msg); +void Serialize(SilKit::Core::MessageBuffer& buffer, const Services::Can::CanControllerStatus& msg); +void Serialize(SilKit::Core::MessageBuffer& buffer, const Services::Can::CanConfigureBaudrate& msg); +void Serialize(SilKit::Core::MessageBuffer& buffer, const Services::Can::CanSetControllerMode& msg); void Deserialize(SilKit::Core::MessageBuffer& buffer, Services::Can::WireCanFrameEvent& out); void Deserialize(SilKit::Core::MessageBuffer& buffer, Services::Can::CanFrameTransmitEvent& out); @@ -42,6 +42,6 @@ void Deserialize(SilKit::Core::MessageBuffer& buffer, Services::Can::CanControll void Deserialize(SilKit::Core::MessageBuffer& buffer, Services::Can::CanConfigureBaudrate& out); void Deserialize(SilKit::Core::MessageBuffer& buffer, Services::Can::CanSetControllerMode& out); -} // namespace Can +} // namespace Can } // namespace Services } // namespace SilKit diff --git a/SilKit/source/services/can/IMsgForCanSimulator.hpp b/SilKit/source/services/can/IMsgForCanSimulator.hpp index f100c74ec..280729e25 100644 --- a/SilKit/source/services/can/IMsgForCanSimulator.hpp +++ b/SilKit/source/services/can/IMsgForCanSimulator.hpp @@ -42,15 +42,6 @@ class IMsgForCanSimulator { public: ~IMsgForCanSimulator() = default; - - /* NB: there is no setter or getter for an EndpointAddress of the bus - * simulator, since a network simulator manages multiple controllers with - * different endpoints. I.e., a network simulator is aware of the endpointIds. - */ - //! \brief Setter and getter for the ParticipantID associated with this CAN network simulator - virtual void SetParticipantId(SilKit::Core::ParticipantId participantId) = 0; - virtual auto GetParticipantId() const -> SilKit::Core::ParticipantId = 0; - }; } // namespace Can diff --git a/SilKit/source/services/can/SimBehavior.cpp b/SilKit/source/services/can/SimBehavior.cpp index fcb00b7db..e90ddd8d0 100644 --- a/SilKit/source/services/can/SimBehavior.cpp +++ b/SilKit/source/services/can/SimBehavior.cpp @@ -29,7 +29,7 @@ namespace Can { class CanController; SimBehavior::SimBehavior(Core::IParticipantInternal* participant, CanController* canController, - Services::Orchestration::ITimeProvider* timeProvider) + Services::Orchestration::ITimeProvider* timeProvider) : _trivial{participant, canController, timeProvider} , _detailed{participant, canController, canController->GetServiceDescriptor()} { diff --git a/SilKit/source/services/can/SimBehavior.hpp b/SilKit/source/services/can/SimBehavior.hpp index 4dcab5683..060c57aa1 100644 --- a/SilKit/source/services/can/SimBehavior.hpp +++ b/SilKit/source/services/can/SimBehavior.hpp @@ -42,7 +42,7 @@ class SimBehavior : public ISimBehavior { public: SimBehavior(Core::IParticipantInternal* participant, CanController* canController, - Services::Orchestration::ITimeProvider* timeProvider); + Services::Orchestration::ITimeProvider* timeProvider); auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; void SendMsg(CanConfigureBaudrate&& msg) override; diff --git a/SilKit/source/services/can/SimBehaviorDetailed.cpp b/SilKit/source/services/can/SimBehaviorDetailed.cpp old mode 100755 new mode 100644 index d16788096..46258ca84 --- a/SilKit/source/services/can/SimBehaviorDetailed.cpp +++ b/SilKit/source/services/can/SimBehaviorDetailed.cpp @@ -27,7 +27,7 @@ namespace Services { namespace Can { SimBehaviorDetailed::SimBehaviorDetailed(Core::IParticipantInternal* participant, CanController* canController, - const Core::ServiceDescriptor& serviceDescriptor) + const Core::ServiceDescriptor& serviceDescriptor) : _participant{participant} , _parentServiceEndpoint{dynamic_cast(canController)} , _parentServiceDescriptor{&serviceDescriptor} @@ -54,7 +54,7 @@ void SimBehaviorDetailed::SendMsg(WireCanFrameEvent&& msg) SendMsgImpl(msg); } -auto SimBehaviorDetailed::AllowReception(const Core::IServiceEndpoint* from) const -> bool +auto SimBehaviorDetailed::AllowReception(const Core::IServiceEndpoint* from) const -> bool { // If simulated, only allow reception from NetSim. // NetSim internally sets the ServiceId of this controller and sends messages with it, diff --git a/SilKit/source/services/can/SimBehaviorDetailed.hpp b/SilKit/source/services/can/SimBehaviorDetailed.hpp index 75b5b7060..80be8d9c6 100644 --- a/SilKit/source/services/can/SimBehaviorDetailed.hpp +++ b/SilKit/source/services/can/SimBehaviorDetailed.hpp @@ -36,12 +36,12 @@ class SimBehaviorDetailed : public ISimBehavior { public: SimBehaviorDetailed(Core::IParticipantInternal* participant, CanController* canController, - const Core::ServiceDescriptor& serviceDescriptor); + const Core::ServiceDescriptor& serviceDescriptor); void SendMsg(CanConfigureBaudrate&& msg) override; void SendMsg(CanSetControllerMode&& msg) override; void SendMsg(WireCanFrameEvent&& msg) override; - + auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; void SetSimulatedLink(const Core::ServiceDescriptor& simulatedLink); diff --git a/SilKit/source/services/can/SimBehaviorTrivial.cpp b/SilKit/source/services/can/SimBehaviorTrivial.cpp index 2a6813502..5defd4951 100644 --- a/SilKit/source/services/can/SimBehaviorTrivial.cpp +++ b/SilKit/source/services/can/SimBehaviorTrivial.cpp @@ -20,20 +20,18 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "CanController.hpp" -#include "SimBehaviorTrivial.hpp" +#include "SimBehaviorTrivial.hpp" #include "Assert.hpp" #include "silkit/services/logging/ILogger.hpp" - - namespace SilKit { namespace Services { namespace Can { SimBehaviorTrivial::SimBehaviorTrivial(Core::IParticipantInternal* participant, CanController* canController, - Services::Orchestration::ITimeProvider* timeProvider) + Services::Orchestration::ITimeProvider* timeProvider) : _participant{participant} , _parentController{canController} , _parentServiceEndpoint{dynamic_cast(canController)} @@ -50,14 +48,12 @@ void SimBehaviorTrivial::ReceiveMsg(const MsgT& msg) receivingController->ReceiveMsg(_parentServiceEndpoint, msg); } -auto SimBehaviorTrivial::AllowReception(const Core::IServiceEndpoint* /*from*/) const -> bool -{ - return true; +auto SimBehaviorTrivial::AllowReception(const Core::IServiceEndpoint* /*from*/) const -> bool +{ + return true; } -void SimBehaviorTrivial::SendMsg(CanConfigureBaudrate&& /*baudRate*/) -{ -} +void SimBehaviorTrivial::SendMsg(CanConfigureBaudrate&& /*baudRate*/) {} void SimBehaviorTrivial::SendMsg(CanSetControllerMode&& mode) { @@ -95,7 +91,8 @@ void SimBehaviorTrivial::SendMsg(WireCanFrameEvent&& canFrameEvent) } else { - _participant->GetLogger()->Warn("ICanController::SendFrame is called although can controller is not in state CanController::Started."); + _participant->GetLogger()->Warn( + "ICanController::SendFrame is called although can controller is not in state CanController::Started."); } } diff --git a/SilKit/source/services/can/SimBehaviorTrivial.hpp b/SilKit/source/services/can/SimBehaviorTrivial.hpp index 20d615a1c..478b60e7b 100644 --- a/SilKit/source/services/can/SimBehaviorTrivial.hpp +++ b/SilKit/source/services/can/SimBehaviorTrivial.hpp @@ -36,9 +36,8 @@ class CanController; class SimBehaviorTrivial : public ISimBehavior { public: - SimBehaviorTrivial(Core::IParticipantInternal* participant, CanController* canController, - Services::Orchestration::ITimeProvider* timeProvider); + Services::Orchestration::ITimeProvider* timeProvider); auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; void SendMsg(CanConfigureBaudrate&& /*baudRate*/) override; diff --git a/SilKit/source/services/can/Test_CanControllerConfig.cpp b/SilKit/source/services/can/Test_CanControllerConfig.cpp index 2550c0f7b..7fbe88502 100644 --- a/SilKit/source/services/can/Test_CanControllerConfig.cpp +++ b/SilKit/source/services/can/Test_CanControllerConfig.cpp @@ -37,7 +37,7 @@ using namespace SilKit::Services::Can; class Test_CanControllerConfig : public testing::Test { public: - Test_CanControllerConfig(){}; + Test_CanControllerConfig() {}; }; auto PrepareParticipantConfiguration() -> std::shared_ptr @@ -89,4 +89,4 @@ TEST(Test_CanControllerConfig, create_controller_configured_with_network) EXPECT_EQ(serviceDescr.GetNetworkName(), expectedNetworkName); } -} // anonymous namespace +} // anonymous namespace diff --git a/SilKit/source/services/can/Test_CanControllerDetailedSim.cpp b/SilKit/source/services/can/Test_CanControllerDetailedSim.cpp index 504426bec..6a6f76790 100644 --- a/SilKit/source/services/can/Test_CanControllerDetailedSim.cpp +++ b/SilKit/source/services/can/Test_CanControllerDetailedSim.cpp @@ -51,32 +51,31 @@ using ::SilKit::Core::Tests::DummyParticipant; class MockParticipant : public DummyParticipant { public: - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const WireCanFrameEvent&)); - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const CanFrameTransmitEvent&)); - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const CanConfigureBaudrate&)); - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const CanSetControllerMode&)); + MOCK_METHOD2(SendMsg, void(const IServiceEndpoint *, const WireCanFrameEvent &)); + MOCK_METHOD2(SendMsg, void(const IServiceEndpoint *, const CanFrameTransmitEvent &)); + MOCK_METHOD2(SendMsg, void(const IServiceEndpoint *, const CanConfigureBaudrate &)); + MOCK_METHOD2(SendMsg, void(const IServiceEndpoint *, const CanSetControllerMode &)); }; class CanControllerCallbacks { public: - MOCK_METHOD2(FrameHandler, void(ICanController*, CanFrameEvent)); - MOCK_METHOD2(StateChangeHandler, void(ICanController*, CanStateChangeEvent)); - MOCK_METHOD2(ErrorStateChangeHandler, void(ICanController*, CanErrorStateChangeEvent)); - MOCK_METHOD2(FrameTransmitHandler, void(ICanController*, CanFrameTransmitEvent)); + MOCK_METHOD2(FrameHandler, void(ICanController *, CanFrameEvent)); + MOCK_METHOD2(StateChangeHandler, void(ICanController *, CanStateChangeEvent)); + MOCK_METHOD2(ErrorStateChangeHandler, void(ICanController *, CanErrorStateChangeEvent)); + MOCK_METHOD2(FrameTransmitHandler, void(ICanController *, CanFrameTransmitEvent)); }; TEST(Test_CanControllerDetailedSim, send_can_message) { MockParticipant mockParticipant; CanController canController(&mockParticipant, {}, mockParticipant.GetTimeProvider()); - canController.SetDetailedBehavior({ "bussim", "n1", "c1", 8 }); - canController.SetServiceDescriptor({ "p1", "n1", "c1", 8 }); + canController.SetDetailedBehavior({"bussim", "n1", "c1", 8}); + canController.SetServiceDescriptor({"p1", "n1", "c1", 8}); WireCanFrameEvent testFrameEvent{}; - EXPECT_CALL(mockParticipant, SendMsg(&canController, testFrameEvent)) - .Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&canController, testFrameEvent)).Times(1); canController.SendFrame(ToCanFrame(testFrameEvent.frame)); } @@ -85,21 +84,20 @@ TEST(Test_CanControllerDetailedSim, receive_can_message) { using namespace std::placeholders; - ServiceDescriptor busSimAddress { "bussim", "n1", "c1", 8 }; + ServiceDescriptor busSimAddress{"bussim", "n1", "c1", 8}; MockParticipant mockParticipant; CanControllerCallbacks callbackProvider; CanController canController(&mockParticipant, {}, mockParticipant.GetTimeProvider()); canController.SetDetailedBehavior(busSimAddress); - canController.SetServiceDescriptor({ "p1", "n1", "c1", 8 }); + canController.SetServiceDescriptor({"p1", "n1", "c1", 8}); canController.AddFrameHandler(std::bind(&CanControllerCallbacks::FrameHandler, &callbackProvider, _1, _2)); WireCanFrameEvent testFrameEvent{}; testFrameEvent.direction = SilKit::Services::TransmitDirection::RX; - EXPECT_CALL(callbackProvider, FrameHandler(&canController, ToCanFrameEvent(testFrameEvent))) - .Times(1); + EXPECT_CALL(callbackProvider, FrameHandler(&canController, ToCanFrameEvent(testFrameEvent))).Times(1); CanController canControllerFrom(&mockParticipant, {}, mockParticipant.GetTimeProvider()); canControllerFrom.SetServiceDescriptor(busSimAddress); @@ -112,22 +110,18 @@ TEST(Test_CanControllerDetailedSim, start_stop_sleep_reset) MockParticipant mockParticipant; CanController canController(&mockParticipant, {}, mockParticipant.GetTimeProvider()); - canController.SetDetailedBehavior({ "bussim", "n1", "c1", 8 }); - canController.SetServiceDescriptor({ "p1", "n1", "c1", 8 }); + canController.SetDetailedBehavior({"bussim", "n1", "c1", 8}); + canController.SetServiceDescriptor({"p1", "n1", "c1", 8}); - CanSetControllerMode startCommand = { {0, 0}, CanControllerState::Started }; - CanSetControllerMode stopCommand = { { 0, 0 }, CanControllerState::Stopped }; - CanSetControllerMode sleepCommand = { { 0, 0 }, CanControllerState::Sleep }; - CanSetControllerMode resetCommand = { { 1, 1 }, CanControllerState::Uninit }; + CanSetControllerMode startCommand = {{0, 0}, CanControllerState::Started}; + CanSetControllerMode stopCommand = {{0, 0}, CanControllerState::Stopped}; + CanSetControllerMode sleepCommand = {{0, 0}, CanControllerState::Sleep}; + CanSetControllerMode resetCommand = {{1, 1}, CanControllerState::Uninit}; - EXPECT_CALL(mockParticipant, SendMsg(&canController, startCommand)) - .Times(1); - EXPECT_CALL(mockParticipant, SendMsg(&canController, stopCommand)) - .Times(1); - EXPECT_CALL(mockParticipant, SendMsg(&canController, sleepCommand)) - .Times(1); - EXPECT_CALL(mockParticipant, SendMsg(&canController, resetCommand)) - .Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&canController, startCommand)).Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&canController, stopCommand)).Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&canController, sleepCommand)).Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&canController, resetCommand)).Times(1); canController.Start(); canController.Stop(); @@ -140,16 +134,14 @@ TEST(Test_CanControllerDetailedSim, set_baudrate) MockParticipant mockParticipant; CanController canController(&mockParticipant, {}, mockParticipant.GetTimeProvider()); - canController.SetDetailedBehavior({ "bussim", "n1", "c1", 8 }); - canController.SetServiceDescriptor({ "p1", "n1", "c1", 8 }); + canController.SetDetailedBehavior({"bussim", "n1", "c1", 8}); + canController.SetServiceDescriptor({"p1", "n1", "c1", 8}); - CanConfigureBaudrate baudrate1 = { 3000, 0, 0 }; - CanConfigureBaudrate baudrate2 = { 3000, 500000, 0 }; + CanConfigureBaudrate baudrate1 = {3000, 0, 0}; + CanConfigureBaudrate baudrate2 = {3000, 500000, 0}; - EXPECT_CALL(mockParticipant, SendMsg(&canController, baudrate1)) - .Times(1); - EXPECT_CALL(mockParticipant, SendMsg(&canController, baudrate2)) - .Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&canController, baudrate1)).Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&canController, baudrate2)).Times(1); canController.SetBaudRate(baudrate1.baudRate, baudrate1.fdBaudRate, baudrate1.xlBaudRate); canController.SetBaudRate(baudrate2.baudRate, baudrate2.fdBaudRate, baudrate2.xlBaudRate); @@ -159,22 +151,26 @@ TEST(Test_CanControllerDetailedSim, receive_new_controller_state) { using namespace std::placeholders; - ServiceDescriptor busSimAddress{ "bussim", "n1", "c1", 8 }; + ServiceDescriptor busSimAddress{"bussim", "n1", "c1", 8}; MockParticipant mockParticipant; CanController canController(&mockParticipant, {}, mockParticipant.GetTimeProvider()); canController.SetDetailedBehavior(busSimAddress); - canController.SetServiceDescriptor({ "p1", "n1", "c1", 8 }); + canController.SetServiceDescriptor({"p1", "n1", "c1", 8}); CanControllerCallbacks callbackProvider; - canController.AddStateChangeHandler(std::bind(&CanControllerCallbacks::StateChangeHandler, &callbackProvider, _1, _2)); - canController.AddErrorStateChangeHandler(std::bind(&CanControllerCallbacks::ErrorStateChangeHandler, &callbackProvider, _1, _2)); + canController.AddStateChangeHandler( + std::bind(&CanControllerCallbacks::StateChangeHandler, &callbackProvider, _1, _2)); + canController.AddErrorStateChangeHandler( + std::bind(&CanControllerCallbacks::ErrorStateChangeHandler, &callbackProvider, _1, _2)); - EXPECT_CALL(callbackProvider, StateChangeHandler(&canController, CanStateChangeEvent{ 0ns, CanControllerState::Started })) + EXPECT_CALL(callbackProvider, + StateChangeHandler(&canController, CanStateChangeEvent{0ns, CanControllerState::Started})) .Times(1); - EXPECT_CALL(callbackProvider, ErrorStateChangeHandler(&canController, CanErrorStateChangeEvent{ 0ns, CanErrorState::ErrorActive })) + EXPECT_CALL(callbackProvider, + ErrorStateChangeHandler(&canController, CanErrorStateChangeEvent{0ns, CanErrorState::ErrorActive})) .Times(1); CanControllerStatus controllerStatus{}; @@ -201,26 +197,25 @@ TEST(Test_CanControllerDetailedSim, receive_new_controller_state) TEST(Test_CanControllerDetailedSim, receive_ack) { using namespace std::placeholders; - ServiceDescriptor busSimAddress{ "bussim", "n1", "c1", 8 }; + ServiceDescriptor busSimAddress{"bussim", "n1", "c1", 8}; MockParticipant mockParticipant; CanController canController(&mockParticipant, {}, mockParticipant.GetTimeProvider()); canController.SetDetailedBehavior(busSimAddress); - canController.SetServiceDescriptor({ "p1", "n1", "c1", 8 }); + canController.SetServiceDescriptor({"p1", "n1", "c1", 8}); CanControllerCallbacks callbackProvider; - canController.AddFrameTransmitHandler(std::bind(&CanControllerCallbacks::FrameTransmitHandler, &callbackProvider, _1, _2)); + canController.AddFrameTransmitHandler( + std::bind(&CanControllerCallbacks::FrameTransmitHandler, &callbackProvider, _1, _2)); CanFrame msg{}; CanFrameTransmitEvent ack1{msg.canId, 0ns, CanTransmitStatus::Transmitted, (void *)1}; CanFrameTransmitEvent ack2{msg.canId, 0ns, CanTransmitStatus::Transmitted, (void *)2}; - EXPECT_CALL(callbackProvider, FrameTransmitHandler(&canController, ack1)) - .Times(1); - EXPECT_CALL(callbackProvider, FrameTransmitHandler(&canController, ack2)) - .Times(1); + EXPECT_CALL(callbackProvider, FrameTransmitHandler(&canController, ack1)).Times(1); + EXPECT_CALL(callbackProvider, FrameTransmitHandler(&canController, ack2)).Times(1); CanController canControllerFrom(&mockParticipant, {}, mockParticipant.GetTimeProvider()); canControllerFrom.SetServiceDescriptor(busSimAddress); @@ -239,8 +234,8 @@ TEST(Test_CanControllerDetailedSim, must_not_generate_ack) { using namespace std::placeholders; - ServiceDescriptor controllerAddress{ "P1", "N1", "C1",8 }; - ServiceDescriptor busSimAddress{ "P2", "N1", "C1", 8 }; + ServiceDescriptor controllerAddress{"P1", "N1", "C1", 8}; + ServiceDescriptor busSimAddress{"P2", "N1", "C1", 8}; MockParticipant mockParticipant; CanControllerCallbacks callbackProvider; @@ -250,8 +245,7 @@ TEST(Test_CanControllerDetailedSim, must_not_generate_ack) canController.SetServiceDescriptor(controllerAddress); WireCanFrameEvent msg{}; - EXPECT_CALL(mockParticipant, SendMsg(An(), A())) - .Times(0); + EXPECT_CALL(mockParticipant, SendMsg(An(), A())).Times(0); CanController canControllerFrom(&mockParticipant, {}, mockParticipant.GetTimeProvider()); canControllerFrom.SetServiceDescriptor(busSimAddress); diff --git a/SilKit/source/services/can/Test_CanControllerTrivialSim.cpp b/SilKit/source/services/can/Test_CanControllerTrivialSim.cpp old mode 100755 new mode 100644 index 9c92f7859..8b604c7b4 --- a/SilKit/source/services/can/Test_CanControllerTrivialSim.cpp +++ b/SilKit/source/services/can/Test_CanControllerTrivialSim.cpp @@ -52,7 +52,8 @@ using SilKit::Util::HandlerId; using SilKit::Core::Tests::DummyParticipant; -MATCHER_P(CanTransmitAckWithouthTransmitIdMatcher, truthAck, "") { +MATCHER_P(CanTransmitAckWithouthTransmitIdMatcher, truthAck, "") +{ *result_listener << "matches CanTransmitAcks without checking the transmit id"; auto frame1 = truthAck; auto frame2 = arg; @@ -110,10 +111,8 @@ TEST(Test_CanControllerTrivialSim, send_can_frame) testFrameEvent.timestamp = 0ns; testFrameEvent.userContext = 0; - EXPECT_CALL(mockParticipant, SendMsg(&canController, testFrameEvent)) - .Times(1); - EXPECT_CALL(mockParticipant.mockTimeProvider, Now()) - .Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&canController, testFrameEvent)).Times(1); + EXPECT_CALL(mockParticipant.mockTimeProvider, Now()).Times(1); canController.SendFrame(ToCanFrame(testFrameEvent.frame)); } @@ -142,8 +141,7 @@ TEST(Test_CanControllerTrivialSim, receive_can_message) auto canFrameEvent = ToCanFrameEvent(testFrameEvent); canFrameEvent.userContext = 0; - EXPECT_CALL(callbackProvider, FrameHandler(&canController, canFrameEvent)) - .Times(1); + EXPECT_CALL(callbackProvider, FrameHandler(&canController, canFrameEvent)).Times(1); CanController canControllerPlaceholder(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); canControllerPlaceholder.SetServiceDescriptor(senderDescriptor); @@ -203,8 +201,7 @@ TEST(Test_CanControllerTrivialSim, receive_can_message_rx_filter2) testFrameEvent.frame.canId = 16; testFrameEvent.direction = SilKit::Services::TransmitDirection::RX; - EXPECT_CALL(callbackProvider, FrameHandler(&canController, ToCanFrameEvent(testFrameEvent))) - .Times(0); + EXPECT_CALL(callbackProvider, FrameHandler(&canController, ToCanFrameEvent(testFrameEvent))).Times(0); CanController canControllerPlaceholder(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); canControllerPlaceholder.SetServiceDescriptor(senderDescriptor); @@ -230,8 +227,7 @@ TEST(Test_CanControllerTrivialSim, receive_can_message_tx_filter1) testFrameEvent.frame.canId = 16; testFrameEvent.direction = SilKit::Services::TransmitDirection::TX; - EXPECT_CALL(callbackProvider, FrameHandler(&canController, ToCanFrameEvent(testFrameEvent))) - .Times(1); + EXPECT_CALL(callbackProvider, FrameHandler(&canController, ToCanFrameEvent(testFrameEvent))).Times(1); EXPECT_CALL(mockParticipant.mockTimeProvider, Now()).Times(1); CanController canControllerPlaceholder(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); @@ -251,15 +247,15 @@ TEST(Test_CanControllerTrivialSim, receive_can_message_tx_filter2) SilKit::Config::CanController cfg; CanController canController(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); - canController.AddFrameHandler(std::bind(&CanControllerCallbacks::FrameHandler, &callbackProvider, _1, _2), (SilKit::Services::DirectionMask)SilKit::Services::TransmitDirection::RX); + canController.AddFrameHandler(std::bind(&CanControllerCallbacks::FrameHandler, &callbackProvider, _1, _2), + (SilKit::Services::DirectionMask)SilKit::Services::TransmitDirection::RX); canController.Start(); CanFrameEvent testFrameEvent{}; testFrameEvent.frame.canId = 16; testFrameEvent.direction = SilKit::Services::TransmitDirection::TX; - EXPECT_CALL(callbackProvider, FrameHandler(&canController, testFrameEvent)) - .Times(0); + EXPECT_CALL(callbackProvider, FrameHandler(&canController, testFrameEvent)).Times(0); EXPECT_CALL(mockParticipant.mockTimeProvider, Now()).Times(1); CanController canControllerPlaceholder(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); @@ -281,8 +277,7 @@ TEST(Test_CanControllerTrivialSim, start_stop_sleep_reset) CanController canController(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); - EXPECT_CALL(mockParticipant, SendMsg(A(), A())) - .Times(0); + EXPECT_CALL(mockParticipant, SendMsg(A(), A())).Times(0); canController.Start(); canController.Stop(); @@ -303,8 +298,7 @@ TEST(Test_CanControllerTrivialSim, set_baudrate) CanController canController(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); - EXPECT_CALL(mockParticipant, SendMsg(An(), A())) - .Times(0); + EXPECT_CALL(mockParticipant, SendMsg(An(), A())).Times(0); canController.SetBaudRate(3000, 500000, 1000000); } @@ -319,13 +313,15 @@ TEST(Test_CanControllerTrivialSim, receive_ack) CanController canController(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); canController.SetServiceDescriptor({"p1", "n1", "c1", 8}); - canController.AddFrameTransmitHandler(std::bind(&CanControllerCallbacks::FrameTransmitHandler, &callbackProvider, _1, _2)); + canController.AddFrameTransmitHandler( + std::bind(&CanControllerCallbacks::FrameTransmitHandler, &callbackProvider, _1, _2)); canController.Start(); CanFrame msg{}; - CanFrameTransmitEvent expectedAck{ msg.canId, 0ns, CanTransmitStatus::Transmitted, nullptr }; + CanFrameTransmitEvent expectedAck{msg.canId, 0ns, CanTransmitStatus::Transmitted, nullptr}; - EXPECT_CALL(callbackProvider, FrameTransmitHandler(&canController, CanTransmitAckWithouthTransmitIdMatcher(expectedAck))) + EXPECT_CALL(callbackProvider, + FrameTransmitHandler(&canController, CanTransmitAckWithouthTransmitIdMatcher(expectedAck))) .Times(2); canController.SendFrame(msg); canController.SendFrame(msg); @@ -348,11 +344,12 @@ TEST(Test_CanControllerTrivialSim, add_remove_handler) handlerIds.push_back(canController.AddFrameTransmitHandler( std::bind(&CanControllerCallbacks::FrameTransmitHandler, &callbackProvider, _1, _2))); } - + CanFrame msg{}; CanFrameTransmitEvent expectedAck{msg.canId, 0ns, CanTransmitStatus::Transmitted, nullptr}; - EXPECT_CALL(callbackProvider, FrameTransmitHandler(&canController, CanTransmitAckWithouthTransmitIdMatcher(expectedAck))) + EXPECT_CALL(callbackProvider, + FrameTransmitHandler(&canController, CanTransmitAckWithouthTransmitIdMatcher(expectedAck))) .Times(numHandlers); canController.SendFrame(msg); @@ -360,7 +357,7 @@ TEST(Test_CanControllerTrivialSim, add_remove_handler) { canController.RemoveFrameTransmitHandler(handlerId); } - + // All handlers removed, no further calls should appear. canController.SendFrame(msg); } @@ -372,12 +369,11 @@ TEST(Test_CanControllerTrivialSim, cancontroller_uses_tracing) SilKit::Config::CanController cfg; const std::chrono::nanoseconds now = 1337ns; - ON_CALL(participant.mockTimeProvider, Now()) - .WillByDefault(testing::Return(now)); + ON_CALL(participant.mockTimeProvider, Now()).WillByDefault(testing::Return(now)); CanController controller(&participant, cfg, participant.GetTimeProvider()); controller.SetServiceDescriptor({"p1", "n1", "c1", 2}); - const auto controllerDescriptor = controller.GetServiceDescriptor(); + const auto controllerDescriptor = controller.GetServiceDescriptor(); controller.AddSink(&traceSink, SilKit::Config::NetworkType::CAN); controller.Start(); @@ -388,10 +384,9 @@ TEST(Test_CanControllerTrivialSim, cancontroller_uses_tracing) wireCanFrameEvent.direction = SilKit::Services::TransmitDirection::RX; //Send direction - EXPECT_CALL(participant.mockTimeProvider, Now()) - .Times(1); - EXPECT_CALL(traceSink, - Trace(SilKit::Services::TransmitDirection::TX, controllerDescriptor , now, ToCanFrameEvent(wireCanFrameEvent))) + EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); + EXPECT_CALL(traceSink, Trace(SilKit::Services::TransmitDirection::TX, controllerDescriptor, now, + ToCanFrameEvent(wireCanFrameEvent))) .Times(1); controller.SendFrame(ToCanFrame(canFrame)); @@ -399,8 +394,8 @@ TEST(Test_CanControllerTrivialSim, cancontroller_uses_tracing) otherController.SetServiceDescriptor({"p2", "n1", "c1", 2}); // Receive direction - EXPECT_CALL(traceSink, - Trace(SilKit::Services::TransmitDirection::RX, controllerDescriptor , now, ToCanFrameEvent(wireCanFrameEvent))) + EXPECT_CALL(traceSink, Trace(SilKit::Services::TransmitDirection::RX, controllerDescriptor, now, + ToCanFrameEvent(wireCanFrameEvent))) .Times(1); controller.ReceiveMsg(&otherController, wireCanFrameEvent); @@ -440,11 +435,12 @@ TEST(Test_CanControllerTrivialSim, sendmsg_distributes_before_txreceive) CanController canController(&mockParticipant, cfg, mockParticipant.GetTimeProvider()); canController.SetServiceDescriptor({"p1", "n1", "c1", 8}); canController.AddFrameHandler(std::bind(&CanControllerCallbacks::FrameHandler, &callbackProvider, _1, _2)); - canController.AddFrameTransmitHandler(std::bind(&CanControllerCallbacks::FrameTransmitHandler, &callbackProvider, _1, _2)); + canController.AddFrameTransmitHandler( + std::bind(&CanControllerCallbacks::FrameTransmitHandler, &callbackProvider, _1, _2)); canController.Start(); CanFrame msg{}; - CanFrameTransmitEvent expectedAck{ msg.canId, 0ns, CanTransmitStatus::Transmitted, nullptr }; + CanFrameTransmitEvent expectedAck{msg.canId, 0ns, CanTransmitStatus::Transmitted, nullptr}; testing::Sequence sequenceRxTx; testing::Sequence sequenceRxAck; @@ -465,4 +461,4 @@ TEST(Test_CanControllerTrivialSim, sendmsg_distributes_before_txreceive) canController.SendFrame(msg); } -} // anonymous namespace +} // anonymous namespace diff --git a/SilKit/source/services/can/Test_CanSerdes.cpp b/SilKit/source/services/can/Test_CanSerdes.cpp index 282ca581f..2662edd89 100644 --- a/SilKit/source/services/can/Test_CanSerdes.cpp +++ b/SilKit/source/services/can/Test_CanSerdes.cpp @@ -72,7 +72,7 @@ TEST(Test_CanSerdes, SimCan_CanTransmitAcknowledge) in.timestamp = 13ns; in.status = CanTransmitStatus::Transmitted; - in.userContext = (void*)((size_t) 0xcafecafe ); + in.userContext = (void*)((size_t)0xcafecafe); Serialize(buffer, in); Deserialize(buffer, out); diff --git a/SilKit/source/services/ethernet/EthController.cpp b/SilKit/source/services/ethernet/EthController.cpp old mode 100755 new mode 100644 index 251942333..d7a58cbca --- a/SilKit/source/services/ethernet/EthController.cpp +++ b/SilKit/source/services/ethernet/EthController.cpp @@ -32,7 +32,7 @@ namespace Services { namespace Ethernet { EthController::EthController(Core::IParticipantInternal* participant, Config::EthernetController config, - Services::Orchestration::ITimeProvider* timeProvider) + Services::Orchestration::ITimeProvider* timeProvider) : _participant(participant) , _config{std::move(config)} , _simulationBehavior{participant, this, timeProvider} @@ -49,33 +49,42 @@ EthController::EthController(Core::IParticipantInternal* participant, Config::Et void EthController::RegisterServiceDiscovery() { Core::Discovery::IServiceDiscovery* disc = _participant->GetServiceDiscovery(); - disc->RegisterServiceDiscoveryHandler( - [this](Core::Discovery::ServiceDiscoveryEvent::Type discoveryType, - const Core::ServiceDescriptor& remoteServiceDescriptor) { - if (_simulationBehavior.IsTrivial()) + disc->RegisterServiceDiscoveryHandler([this](Core::Discovery::ServiceDiscoveryEvent::Type discoveryType, + const Core::ServiceDescriptor& remoteServiceDescriptor) { + if (_simulationBehavior.IsTrivial()) + { + // Check if received descriptor has a matching simulated link + if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated + && IsRelevantNetwork(remoteServiceDescriptor)) { - // Check if received descriptor has a matching simulated link - if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated - && IsRelevantNetwork(remoteServiceDescriptor)) - { - SetDetailedBehavior(remoteServiceDescriptor); - } + Logging::Info(_logger, + "Controller '{}' is using the simulated network '{}' and will route all messages to " + "the network simulator '{}'", + _config.name, remoteServiceDescriptor.GetNetworkName(), + remoteServiceDescriptor.GetParticipantName()); + SetDetailedBehavior(remoteServiceDescriptor); } - else + } + else + { + if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved + && IsRelevantNetwork(remoteServiceDescriptor)) { - if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved - && IsRelevantNetwork(remoteServiceDescriptor)) - { - SetTrivialBehavior(); - } + Logging::Warn(_logger, + "The network simulator for controller '{}' left the simulation. The controller is no " + "longer simulated.", + _config.name); + SetTrivialBehavior(); } - }); + } + }); } void EthController::SetDetailedBehavior(const Core::ServiceDescriptor& remoteServiceDescriptor) { _simulationBehavior.SetDetailedBehavior(remoteServiceDescriptor); } + void EthController::SetTrivialBehavior() { _simulationBehavior.SetTrivialBehavior(); @@ -114,7 +123,7 @@ void EthController::Activate() if (_ethState != EthernetState::Inactive) return; - EthernetSetMode msg { EthernetMode::Active }; + EthernetSetMode msg{EthernetMode::Active}; SendMsg(msg); } @@ -124,7 +133,7 @@ void EthController::Deactivate() if (_ethState == EthernetState::Inactive) return; - EthernetSetMode msg{ EthernetMode::Inactive }; + EthernetSetMode msg{EthernetMode::Inactive}; SendMsg(msg); } @@ -132,8 +141,8 @@ void EthController::SendFrame(EthernetFrame frame, void* userContext) { if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Send)) { - Logging::Debug(_logger, _logOnce, - "EthController: Ignoring SendFrame API call due to Replay config on {}", _config.name); + Logging::Debug(_logger, _logOnce, "EthController: Ignoring SendFrame API call due to Replay config on {}", + _config.name); return; } return SendFrameInternal(frame, userContext); @@ -145,7 +154,7 @@ void EthController::SendFrameInternal(EthernetFrame frame, void* userContext) msg.userContext = userContext; msg.timestamp = _timeProvider->Now(); - _tracer.Trace(Services::TransmitDirection::TX,msg.timestamp, frame); + _tracer.Trace(Services::TransmitDirection::TX, msg.timestamp, frame); SendMsg(std::move(msg)); } @@ -161,8 +170,8 @@ void EthController::ReceiveMsg(const IServiceEndpoint* from, const WireEthernetF } if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Receive)) { - Logging::Debug(_logger, _logOnce, - "EthController: Ignoring ReceiveMsg API call due to Replay config on {}", _config.name); + Logging::Debug(_logger, _logOnce, "EthController: Ignoring ReceiveMsg API call due to Replay config on {}", + _config.name); return; } return ReceiveMsgInternal(from, msg); @@ -233,13 +242,13 @@ void EthController::ReceiveMsg(const IServiceEndpoint* from, const EthernetStatu if (msg.bitrate != _ethBitRate) { _ethBitRate = msg.bitrate; - CallHandlers(EthernetBitrateChangeEvent{ msg.timestamp, msg.bitrate }); + CallHandlers(EthernetBitrateChangeEvent{msg.timestamp, msg.bitrate}); } if (msg.state != _ethState) { _ethState = msg.state; - CallHandlers(EthernetStateChangeEvent{ msg.timestamp, msg.state }); + CallHandlers(EthernetStateChangeEvent{msg.timestamp, msg.state}); } } @@ -307,16 +316,17 @@ void EthController::RemoveFrameHandler(HandlerId handlerId) } } -HandlerId EthController::AddFrameTransmitHandler(FrameTransmitHandler handler, EthernetTransmitStatusMask transmitStatusMask) +HandlerId EthController::AddFrameTransmitHandler(FrameTransmitHandler handler, + EthernetTransmitStatusMask transmitStatusMask) { return AddHandler(FrameTransmitHandler{ [handler = std::move(handler), transmitStatusMask]( IEthernetController* controller, const EthernetFrameTransmitEvent& ethernetFrameTransmitEvent) { - if (static_cast(ethernetFrameTransmitEvent.status) & transmitStatusMask) - { - handler(controller, ethernetFrameTransmitEvent); - } - }}); + if (static_cast(ethernetFrameTransmitEvent.status) & transmitStatusMask) + { + handler(controller, ethernetFrameTransmitEvent); + } + }}); } void EthController::RemoveFrameTransmitHandler(HandlerId handlerId) diff --git a/SilKit/source/services/ethernet/EthController.hpp b/SilKit/source/services/ethernet/EthController.hpp old mode 100755 new mode 100644 index 5113ef3a8..57c220cb8 --- a/SilKit/source/services/ethernet/EthController.hpp +++ b/SilKit/source/services/ethernet/EthController.hpp @@ -59,7 +59,7 @@ class EthController EthController(const EthController&) = delete; EthController(EthController&&) = delete; EthController(Core::IParticipantInternal* participant, Config::EthernetController config, - Services::Orchestration::ITimeProvider* timeProvider); + Services::Orchestration::ITimeProvider* timeProvider); public: // ---------------------------------------- @@ -78,7 +78,8 @@ class EthController void SendFrame(EthernetFrame frame, void* userContext = nullptr) override; HandlerId AddFrameHandler(FrameHandler handler, DirectionMask directionMask = 0xFF) override; - HandlerId AddFrameTransmitHandler(FrameTransmitHandler handler, EthernetTransmitStatusMask transmitStatusMask = 0xFFFF'FFFF) override; + HandlerId AddFrameTransmitHandler(FrameTransmitHandler handler, + EthernetTransmitStatusMask transmitStatusMask = 0xFFFF'FFFF) override; HandlerId AddStateChangeHandler(StateChangeHandler handler) override; HandlerId AddBitrateChangeHandler(BitrateChangeHandler handler) override; @@ -97,7 +98,7 @@ class EthController // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; // IReplayDataProvider void ReplayMessage(const IReplayMessage* message) override; @@ -115,6 +116,7 @@ class EthController EthernetState GetState(); inline auto GetTracer() -> Tracer*; + private: // ---------------------------------------- // private methods @@ -139,18 +141,18 @@ class EthController void ReplayReceive(const IReplayMessage* replayMessage); void SendFrameInternal(EthernetFrame frame, void* userContext); void ReceiveMsgInternal(const IServiceEndpoint* from, const WireEthernetFrameEvent& msg); - + private: // ---------------------------------------- // private members - Core::IParticipantInternal* _participant{ nullptr }; + Core::IParticipantInternal* _participant{nullptr}; Config::EthernetController _config; ::SilKit::Core::ServiceDescriptor _serviceDescriptor; SimBehavior _simulationBehavior; - EthernetState _ethState{ EthernetState::Inactive }; - uint32_t _ethBitRate{ 0 }; - Orchestration::ITimeProvider* _timeProvider{ nullptr }; + EthernetState _ethState{EthernetState::Inactive}; + uint32_t _ethBitRate{0}; + Orchestration::ITimeProvider* _timeProvider{nullptr}; Tracer _tracer; bool _replayActive{false}; Services::Logging::ILogger* _logger; @@ -159,12 +161,9 @@ class EthController template using CallbacksT = Util::SynchronizedHandlers>; - std::tuple< - CallbacksT, - CallbacksT, - CallbacksT, - CallbacksT - > _callbacks; + std::tuple, CallbacksT, + CallbacksT, CallbacksT> + _callbacks; }; // ================================================================================ diff --git a/SilKit/source/services/ethernet/EthDatatypeUtils.hpp b/SilKit/source/services/ethernet/EthDatatypeUtils.hpp old mode 100755 new mode 100644 index ceaed392c..785272463 --- a/SilKit/source/services/ethernet/EthDatatypeUtils.hpp +++ b/SilKit/source/services/ethernet/EthDatatypeUtils.hpp @@ -40,14 +40,12 @@ inline bool operator==(const EthernetFrame& lhs, const EthernetFrame& rhs) inline bool operator==(const EthernetFrameEvent& lhs, const EthernetFrameEvent& rhs) { - return lhs.timestamp == rhs.timestamp - && lhs.frame == rhs.frame; + return lhs.timestamp == rhs.timestamp && lhs.frame == rhs.frame; } inline bool operator==(const EthernetFrameTransmitEvent& lhs, const EthernetFrameTransmitEvent& rhs) { - return lhs.timestamp == rhs.timestamp - && lhs.status == rhs.status; + return lhs.timestamp == rhs.timestamp && lhs.status == rhs.status; } inline bool operator==(const EthernetSetMode& lhs, const EthernetSetMode& rhs) @@ -89,10 +87,9 @@ const size_t EthernetFrameHeaderSize = 2 * sizeof(EthernetMac) + sizeof(Ethernet //! \brief Build an Ethernet level 2 frame without VLAN tag inline auto CreateEthernetFrame(const SilKit::Services::Ethernet::EthernetMac& destinationMac, - const SilKit::Services::Ethernet::EthernetMac& sourceMac, - const SilKit::Services::Ethernet::EthernetEtherType& etherType, - const std::string& payload) - -> SilKit::Services::Ethernet::WireEthernetFrame + const SilKit::Services::Ethernet::EthernetMac& sourceMac, + const SilKit::Services::Ethernet::EthernetEtherType& etherType, + const std::string& payload) -> SilKit::Services::Ethernet::WireEthernetFrame { std::vector raw; @@ -100,7 +97,7 @@ inline auto CreateEthernetFrame(const SilKit::Services::Ethernet::EthernetMac& d std::copy(destinationMac.begin(), destinationMac.end(), std::back_inserter(raw)); std::copy(sourceMac.begin(), sourceMac.end(), std::back_inserter(raw)); auto etherTypeBytes = reinterpret_cast(ðerType); - raw.push_back(etherTypeBytes[1]); // We assume our platform to be little-endian + raw.push_back(etherTypeBytes[1]); // We assume our platform to be little-endian raw.push_back(etherTypeBytes[0]); std::copy(payload.begin(), payload.end(), std::back_inserter(raw)); @@ -109,10 +106,9 @@ inline auto CreateEthernetFrame(const SilKit::Services::Ethernet::EthernetMac& d //! \brief Build an Ethernet level 2 frame with VLAN tag inline auto CreateEthernetFrameWithVlanTag(const SilKit::Services::Ethernet::EthernetMac& destinationMac, - const SilKit::Services::Ethernet::EthernetMac& sourceMac, - const SilKit::Services::Ethernet::EthernetEtherType& etherType, - const std::string& payload, - const EthernetVlanTagControlIdentifier& tci) + const SilKit::Services::Ethernet::EthernetMac& sourceMac, + const SilKit::Services::Ethernet::EthernetEtherType& etherType, + const std::string& payload, const EthernetVlanTagControlIdentifier& tci) -> SilKit::Services::Ethernet::WireEthernetFrame { std::vector raw; @@ -121,13 +117,13 @@ inline auto CreateEthernetFrameWithVlanTag(const SilKit::Services::Ethernet::Eth std::copy(destinationMac.begin(), destinationMac.end(), std::back_inserter(raw)); std::copy(sourceMac.begin(), sourceMac.end(), std::back_inserter(raw)); auto etherTypeVlanTagBytes = reinterpret_cast(&EthernetEtherTypeVlanTag); - raw.push_back(etherTypeVlanTagBytes[1]); // We assume our platform to be little-endian + raw.push_back(etherTypeVlanTagBytes[1]); // We assume our platform to be little-endian raw.push_back(etherTypeVlanTagBytes[0]); auto tciBytes = reinterpret_cast(&tci); - raw.push_back(tciBytes[1]); // We assume our platform to be little-endian + raw.push_back(tciBytes[1]); // We assume our platform to be little-endian raw.push_back(tciBytes[0]); auto etherTypeBytes = reinterpret_cast(ðerType); - raw.push_back(etherTypeBytes[1]); // We assume our platform to be little-endian + raw.push_back(etherTypeBytes[1]); // We assume our platform to be little-endian raw.push_back(etherTypeBytes[0]); std::copy(payload.begin(), payload.end(), std::back_inserter(raw)); @@ -157,6 +153,6 @@ inline void SetSourceMac(std::vector& raw, const EthernetMac& source) std::copy(source.begin(), source.end(), raw.begin() + SourceMacStart); } -} // namespace SilKit -} // namespace Services } // namespace Ethernet +} // namespace Services +} // namespace SilKit diff --git a/SilKit/source/services/ethernet/EthernetSerdes.cpp b/SilKit/source/services/ethernet/EthernetSerdes.cpp old mode 100755 new mode 100644 index 665bb01b5..da821d9ee --- a/SilKit/source/services/ethernet/EthernetSerdes.cpp +++ b/SilKit/source/services/ethernet/EthernetSerdes.cpp @@ -41,61 +41,40 @@ inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buff inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const WireEthernetFrameEvent& msg) { - buffer - << msg.timestamp - << msg.frame - << msg.direction - << msg.userContext - ; + buffer << msg.timestamp << msg.frame << msg.direction << msg.userContext; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, WireEthernetFrameEvent& msg) { - buffer - >> msg.timestamp - >> msg.frame - >> msg.direction - >> msg.userContext - ; + buffer >> msg.timestamp >> msg.frame >> msg.direction >> msg.userContext; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const EthernetFrameTransmitEvent& ack) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const EthernetFrameTransmitEvent& ack) { - buffer - << ack.timestamp - << ack.status - << ack.userContext - ; + buffer << ack.timestamp << ack.status << ack.userContext; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, EthernetFrameTransmitEvent& ack) { - buffer - >> ack.timestamp - >> ack.status - >> ack.userContext - ; + buffer >> ack.timestamp >> ack.status >> ack.userContext; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const EthernetStatus& msg) { - buffer << msg.timestamp - << msg.state - << msg.bitrate; + buffer << msg.timestamp << msg.state << msg.bitrate; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, EthernetStatus& msg) { - buffer >> msg.timestamp - >> msg.state - >> msg.bitrate; + buffer >> msg.timestamp >> msg.state >> msg.bitrate; return buffer; } diff --git a/SilKit/source/services/ethernet/IMsgForEthSimulator.hpp b/SilKit/source/services/ethernet/IMsgForEthSimulator.hpp index 39abc6af2..93c274234 100644 --- a/SilKit/source/services/ethernet/IMsgForEthSimulator.hpp +++ b/SilKit/source/services/ethernet/IMsgForEthSimulator.hpp @@ -42,15 +42,6 @@ class IMsgForEthSimulator { public: virtual ~IMsgForEthSimulator() = default; - - /* NB: there is no setter or getter for an EndpointAddress of the - * simulator, since the simulator manages multiple controllers - * with different endpoints. I.e., the simulator is aware of all - * the individual endpointIds. - */ - //! \brief Setter and getter for the ParticipantID associated with this ethernetsimulator - virtual void SetParticipantId(SilKit::Core::ParticipantId participantId) = 0; - virtual auto GetParticipantId() const -> SilKit::Core::ParticipantId = 0; }; } // namespace Ethernet diff --git a/SilKit/source/services/ethernet/SimBehavior.cpp b/SilKit/source/services/ethernet/SimBehavior.cpp index 92e6a1f2f..899bbba6d 100644 --- a/SilKit/source/services/ethernet/SimBehavior.cpp +++ b/SilKit/source/services/ethernet/SimBehavior.cpp @@ -29,7 +29,7 @@ namespace Ethernet { class EthController; SimBehavior::SimBehavior(Core::IParticipantInternal* participant, EthController* ethController, - Services::Orchestration::ITimeProvider* timeProvider) + Services::Orchestration::ITimeProvider* timeProvider) : _trivial{participant, ethController, timeProvider} , _detailed{participant, ethController, ethController->GetServiceDescriptor()} { @@ -48,7 +48,7 @@ void SimBehavior::SendMsgImpl(MsgT&& msg) } void SimBehavior::SendMsg(WireEthernetFrameEvent&& msg) -{ +{ SendMsgImpl(std::move(msg)); } diff --git a/SilKit/source/services/ethernet/SimBehavior.hpp b/SilKit/source/services/ethernet/SimBehavior.hpp index d7ef4cceb..749e35586 100644 --- a/SilKit/source/services/ethernet/SimBehavior.hpp +++ b/SilKit/source/services/ethernet/SimBehavior.hpp @@ -42,7 +42,7 @@ class SimBehavior : public ISimBehavior { public: SimBehavior(Core::IParticipantInternal* participant, EthController* ethController, - Services::Orchestration::ITimeProvider* timeProvider); + Services::Orchestration::ITimeProvider* timeProvider); auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; void SendMsg(WireEthernetFrameEvent&& msg) override; diff --git a/SilKit/source/services/ethernet/SimBehaviorDetailed.cpp b/SilKit/source/services/ethernet/SimBehaviorDetailed.cpp index 83f3c7569..61cc475e2 100644 --- a/SilKit/source/services/ethernet/SimBehaviorDetailed.cpp +++ b/SilKit/source/services/ethernet/SimBehaviorDetailed.cpp @@ -27,7 +27,7 @@ namespace Services { namespace Ethernet { SimBehaviorDetailed::SimBehaviorDetailed(Core::IParticipantInternal* participant, EthController* ethController, - const Core::ServiceDescriptor& serviceDescriptor) + const Core::ServiceDescriptor& serviceDescriptor) : _participant{participant} , _parentServiceEndpoint{dynamic_cast(ethController)} , _parentServiceDescriptor{&serviceDescriptor} @@ -50,9 +50,7 @@ void SimBehaviorDetailed::SendMsg(EthernetSetMode&& msg) SendMsgImpl(msg); } -void SimBehaviorDetailed::OnReceiveAck(const EthernetFrameTransmitEvent&) -{ -} +void SimBehaviorDetailed::OnReceiveAck(const EthernetFrameTransmitEvent&) {} auto SimBehaviorDetailed::AllowReception(const Core::IServiceEndpoint* from) const -> bool { diff --git a/SilKit/source/services/ethernet/SimBehaviorDetailed.hpp b/SilKit/source/services/ethernet/SimBehaviorDetailed.hpp index 4919219a0..6e2c91846 100644 --- a/SilKit/source/services/ethernet/SimBehaviorDetailed.hpp +++ b/SilKit/source/services/ethernet/SimBehaviorDetailed.hpp @@ -37,12 +37,12 @@ class SimBehaviorDetailed : public ISimBehavior { public: SimBehaviorDetailed(Core::IParticipantInternal* participant, EthController* ethController, - const Core::ServiceDescriptor& serviceDescriptor); + const Core::ServiceDescriptor& serviceDescriptor); void SendMsg(WireEthernetFrameEvent&& msg) override; void SendMsg(EthernetSetMode&& msg) override; void OnReceiveAck(const EthernetFrameTransmitEvent& msg) override; - + auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; void SetSimulatedLink(const Core::ServiceDescriptor& simulatedLink); diff --git a/SilKit/source/services/ethernet/SimBehaviorTrivial.cpp b/SilKit/source/services/ethernet/SimBehaviorTrivial.cpp index 869372818..86965b790 100644 --- a/SilKit/source/services/ethernet/SimBehaviorTrivial.cpp +++ b/SilKit/source/services/ethernet/SimBehaviorTrivial.cpp @@ -29,7 +29,8 @@ using SilKit::Services::Ethernet::EthernetTransmitStatus; auto ControllerStateToTransmitStatus(const EthernetState ethernetState) -> EthernetTransmitStatus { - switch (ethernetState) { + switch (ethernetState) + { case EthernetState::LinkUp: return EthernetTransmitStatus::Transmitted; case EthernetState::LinkDown: @@ -48,7 +49,7 @@ namespace Services { namespace Ethernet { SimBehaviorTrivial::SimBehaviorTrivial(Core::IParticipantInternal* participant, EthController* ethController, - Services::Orchestration::ITimeProvider* timeProvider) + Services::Orchestration::ITimeProvider* timeProvider) : _participant{participant} , _parentController{ethController} , _parentServiceEndpoint{dynamic_cast(ethController)} @@ -60,13 +61,13 @@ SimBehaviorTrivial::SimBehaviorTrivial(Core::IParticipantInternal* participant, template void SimBehaviorTrivial::ReceiveMsg(const MsgT& msg) { - auto receivingController = static_cast *>(_parentController); + auto receivingController = static_cast*>(_parentController); receivingController->ReceiveMsg(_parentServiceEndpoint, msg); } -auto SimBehaviorTrivial::AllowReception(const Core::IServiceEndpoint* /*from*/) const -> bool -{ - return true; +auto SimBehaviorTrivial::AllowReception(const Core::IServiceEndpoint* /*from*/) const -> bool +{ + return true; } void SimBehaviorTrivial::SendMsg(WireEthernetFrameEvent&& ethFrameEvent) @@ -111,9 +112,7 @@ void SimBehaviorTrivial::SendMsg(EthernetSetMode&& ethSetMode) ReceiveMsg(statusReply); } -void SimBehaviorTrivial::OnReceiveAck(const EthernetFrameTransmitEvent& /*msg*/) -{ -} +void SimBehaviorTrivial::OnReceiveAck(const EthernetFrameTransmitEvent& /*msg*/) {} } // namespace Ethernet } // namespace Services diff --git a/SilKit/source/services/ethernet/SimBehaviorTrivial.hpp b/SilKit/source/services/ethernet/SimBehaviorTrivial.hpp index 1d67e993f..997c13040 100644 --- a/SilKit/source/services/ethernet/SimBehaviorTrivial.hpp +++ b/SilKit/source/services/ethernet/SimBehaviorTrivial.hpp @@ -36,9 +36,8 @@ class EthController; class SimBehaviorTrivial : public ISimBehavior { public: - SimBehaviorTrivial(Core::IParticipantInternal* participant, EthController* ethController, - Services::Orchestration::ITimeProvider* timeProvider); + Services::Orchestration::ITimeProvider* timeProvider); auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; void SendMsg(WireEthernetFrameEvent&& ethFrameEvent) override; diff --git a/SilKit/source/services/ethernet/Test_EthControllerConfig.cpp b/SilKit/source/services/ethernet/Test_EthControllerConfig.cpp index 83f0ae053..7f83e60a0 100644 --- a/SilKit/source/services/ethernet/Test_EthControllerConfig.cpp +++ b/SilKit/source/services/ethernet/Test_EthControllerConfig.cpp @@ -37,7 +37,7 @@ using namespace SilKit::Services::Ethernet; class Test_EthControllerConfig : public testing::Test { public: - Test_EthControllerConfig(){}; + Test_EthControllerConfig() {}; }; auto PrepareParticipantConfiguration() -> std::shared_ptr @@ -67,8 +67,7 @@ TEST(Test_EthControllerConfig, create_controller_configured_no_network) auto participant = SilKit::Core::CreateNullConnectionParticipantImpl(config, "TestParticipant"); - auto controller = - dynamic_cast(participant->CreateEthernetController(controllerName, networkName)); + auto controller = dynamic_cast(participant->CreateEthernetController(controllerName, networkName)); auto serviceDescr = controller->GetServiceDescriptor(); EXPECT_EQ(serviceDescr.GetServiceName(), controllerName); EXPECT_EQ(serviceDescr.GetNetworkName(), expectedNetworkName); @@ -84,11 +83,10 @@ TEST(Test_EthControllerConfig, create_controller_configured_with_network) auto participant = SilKit::Core::CreateNullConnectionParticipantImpl(config, "TestParticipant"); - auto controller = - dynamic_cast(participant->CreateEthernetController(controllerName, networkName)); + auto controller = dynamic_cast(participant->CreateEthernetController(controllerName, networkName)); auto serviceDescr = controller->GetServiceDescriptor(); EXPECT_EQ(serviceDescr.GetServiceName(), controllerName); EXPECT_EQ(serviceDescr.GetNetworkName(), expectedNetworkName); } -} // anonymous namespace +} // anonymous namespace diff --git a/SilKit/source/services/ethernet/Test_EthControllerDetailedSim.cpp b/SilKit/source/services/ethernet/Test_EthControllerDetailedSim.cpp old mode 100755 new mode 100644 index 04d79ed88..367c8e399 --- a/SilKit/source/services/ethernet/Test_EthControllerDetailedSim.cpp +++ b/SilKit/source/services/ethernet/Test_EthControllerDetailedSim.cpp @@ -53,7 +53,7 @@ using namespace SilKit::Services::Ethernet; using ::SilKit::Core::Tests::DummyParticipant; -auto AnEthMessageWith(std::chrono::nanoseconds timestamp) -> testing::Matcher +auto AnEthMessageWith(std::chrono::nanoseconds timestamp) -> testing::Matcher { return testing::Field(&WireEthernetFrameEvent::timestamp, timestamp); } @@ -61,10 +61,10 @@ auto AnEthMessageWith(std::chrono::nanoseconds timestamp) -> testing::Matcher{std::vector(123)}; msg.direction = TransmitDirection::RX; - EXPECT_CALL(callbacks, FrameHandler(&controller, ToEthernetFrameEvent(msg))) - .Times(1); + EXPECT_CALL(callbacks, FrameHandler(&controller, ToEthernetFrameEvent(msg))).Times(1); controller.ReceiveMsg(&controllerBusSim, msg); } @@ -184,10 +181,9 @@ TEST_F(Test_EthControllerDetailedSim, trigger_callback_on_receive_message) */ TEST_F(Test_EthControllerDetailedSim, trigger_callback_on_receive_ack) { - EthernetFrameTransmitEvent expectedAck{ 42ms, EthernetTransmitStatus::Transmitted, reinterpret_cast(17) }; + EthernetFrameTransmitEvent expectedAck{42ms, EthernetTransmitStatus::Transmitted, reinterpret_cast(17)}; - EXPECT_CALL(callbacks, FrameTransmitHandler(&controller, expectedAck)) - .Times(1); + EXPECT_CALL(callbacks, FrameTransmitHandler(&controller, expectedAck)).Times(1); controller.ReceiveMsg(&controllerBusSim, expectedAck); } @@ -203,8 +199,7 @@ TEST_F(Test_EthControllerDetailedSim, must_not_generate_ack) WireEthernetFrameEvent msg{}; msg.userContext = reinterpret_cast(17); - EXPECT_CALL(participant, SendMsg(An(), A())) - .Times(0); + EXPECT_CALL(participant, SendMsg(An(), A())).Times(0); controller.ReceiveMsg(&controllerBusSim, msg); } @@ -223,12 +218,12 @@ TEST_F(Test_EthControllerDetailedSim, must_not_generate_ack) */ TEST_F(Test_EthControllerDetailedSim, trigger_callback_on_bitrate_change) { - EXPECT_CALL(callbacks, BitrateChangedHandler(&controller, EthernetBitrateChangeEvent{ 0ns, 100 })) - .Times(1); - EXPECT_CALL(callbacks, BitrateChangedHandler(&controller, Ne(EthernetBitrateChangeEvent{ 0ns, 100 }))) + EXPECT_CALL(callbacks, BitrateChangedHandler(&controller, EthernetBitrateChangeEvent{0ns, 100})).Times(1); + EXPECT_CALL(callbacks, BitrateChangedHandler(&controller, + Ne(EthernetBitrateChangeEvent{0ns, 100}))) .Times(0); - EthernetStatus newStatus = { 0ns, EthernetState::Inactive, 0 }; + EthernetStatus newStatus = {0ns, EthernetState::Inactive, 0}; controller.ReceiveMsg(&controllerBusSim, newStatus); newStatus.bitrate = 100; @@ -256,15 +251,18 @@ TEST_F(Test_EthControllerDetailedSim, trigger_callback_on_bitrate_change) TEST_F(Test_EthControllerDetailedSim, trigger_callback_on_state_change) { InSequence executionSequence; - EXPECT_CALL(callbacks, StateChangeHandler(&controller, Ethernet::EthernetStateChangeEvent{ 0ns, EthernetState::LinkUp })) + EXPECT_CALL(callbacks, + StateChangeHandler(&controller, Ethernet::EthernetStateChangeEvent{0ns, EthernetState::LinkUp})) .Times(1); - EXPECT_CALL(callbacks, StateChangeHandler(&controller, Ethernet::EthernetStateChangeEvent{ 0ns, EthernetState::LinkDown })) + EXPECT_CALL(callbacks, + StateChangeHandler(&controller, Ethernet::EthernetStateChangeEvent{0ns, EthernetState::LinkDown})) .Times(1); - EXPECT_CALL(callbacks, StateChangeHandler(&controller, Ethernet::EthernetStateChangeEvent{ 0ns, EthernetState::Inactive })) + EXPECT_CALL(callbacks, + StateChangeHandler(&controller, Ethernet::EthernetStateChangeEvent{0ns, EthernetState::Inactive})) .Times(1); - EthernetStatus newStatus = { 0ns, EthernetState::Inactive, 0 }; + EthernetStatus newStatus = {0ns, EthernetState::Inactive, 0}; controller.ReceiveMsg(&controllerBusSim, newStatus); newStatus.state = EthernetState::LinkUp; @@ -280,5 +278,4 @@ TEST_F(Test_EthControllerDetailedSim, trigger_callback_on_state_change) } - } // anonymous namespace diff --git a/SilKit/source/services/ethernet/Test_EthControllerTrivialSim.cpp b/SilKit/source/services/ethernet/Test_EthControllerTrivialSim.cpp old mode 100755 new mode 100644 index 744f27028..73cd72f0f --- a/SilKit/source/services/ethernet/Test_EthControllerTrivialSim.cpp +++ b/SilKit/source/services/ethernet/Test_EthControllerTrivialSim.cpp @@ -54,7 +54,7 @@ using namespace SilKit::Services::Ethernet; using ::SilKit::Core::Tests::DummyParticipant; using ::SilKit::Tests::MockTraceSink; -MATCHER_P(EthernetTransmitAckWithouthTransmitIdMatcher, truthAck, "") +MATCHER_P(EthernetTransmitAckWithouthTransmitIdMatcher, truthAck, "") { *result_listener << "matches EthernetTransmitAcks without checking the transmit id"; auto frame1 = truthAck; @@ -68,8 +68,8 @@ auto AnEthMessageWith(std::chrono::nanoseconds timestamp) -> testing::Matcher testing::Matcher +auto AnEthMessageWith(std::chrono::nanoseconds timestamp, + size_t rawFrameSize) -> testing::Matcher { const auto frameHasCorrectSize = [rawFrameSize](const WireEthernetFrame& frame) -> bool { return frame.raw.AsSpan().size() == rawFrameSize; @@ -91,7 +91,6 @@ auto AWireEthernetFrameEventWith(TransmitDirection direction) -> testing::Matche class MockParticipant : public DummyParticipant { public: - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const WireEthernetFrameEvent&)); MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const EthernetFrameTransmitEvent&)); MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const EthernetStatus&)); @@ -123,8 +122,8 @@ class Test_EthControllerTrivialSim : public testing::Test } protected: - const ServiceDescriptor controllerAddress{ "Participant1", "eth1", "EthController1", 8}; - const ServiceDescriptor otherAddress{ "Participant1", "eth1", "EthController1", 2 }; + const ServiceDescriptor controllerAddress{"Participant1", "eth1", "EthController1", 8}; + const ServiceDescriptor otherAddress{"Participant1", "eth1", "EthController1", 2}; MockTraceSink traceSink; MockParticipant participant; @@ -139,8 +138,7 @@ class Test_EthControllerTrivialSim : public testing::Test */ TEST_F(Test_EthControllerTrivialSim, send_eth_frame) { - ON_CALL(participant.mockTimeProvider, Now()) - .WillByDefault(testing::Return(42ns)); + ON_CALL(participant.mockTimeProvider, Now()).WillByDefault(testing::Return(42ns)); const auto now = 42ns; EXPECT_CALL(participant, SendMsg(&controller, AnEthMessageWith(now))).Times(1); @@ -154,7 +152,7 @@ TEST_F(Test_EthControllerTrivialSim, send_eth_frame) EXPECT_CALL(participant.mockTimeProvider, Now()).Times(3); std::vector rawFrame; - SetSourceMac(rawFrame, EthernetMac{ 0, 0, 0, 0, 0, 0 }); + SetSourceMac(rawFrame, EthernetMac{0, 0, 0, 0, 0, 0}); EthernetFrame frame{rawFrame}; controller.Activate(); @@ -178,9 +176,7 @@ TEST_F(Test_EthControllerTrivialSim, send_short_eth_frame) std::vector rawFrame; // destination and source MAC - std::generate_n(std::back_inserter(rawFrame), 6 + 6, []() -> uint8_t { - return 0xFF; - }); + std::generate_n(std::back_inserter(rawFrame), 6 + 6, []() -> uint8_t { return 0xFF; }); // EtherType rawFrame.push_back(0x00); rawFrame.push_back(0x00); @@ -202,9 +198,7 @@ TEST_F(Test_EthControllerTrivialSim, send_short_eth_frame) const auto isFramePaddingZero = [&rawFrame](const WireEthernetFrameEvent& event) -> bool { const auto eventRawFrame = event.frame.raw.AsSpan(); return std::all_of(std::next(eventRawFrame.begin(), rawFrame.size()), eventRawFrame.end(), - [](const uint8_t byte) { - return byte == 0; - }); + [](const uint8_t byte) { return byte == 0; }); }; const testing::Matcher matcher{testing::AllOf( @@ -235,7 +229,7 @@ TEST_F(Test_EthControllerTrivialSim, nack_on_inactive_controller) EXPECT_CALL(participant.mockTimeProvider, Now()).Times(2); std::vector rawFrame; - SetSourceMac(rawFrame, EthernetMac{ 0, 0, 0, 0, 0, 0 }); + SetSourceMac(rawFrame, EthernetMac{0, 0, 0, 0, 0, 0}); EthernetFrame frame{rawFrame}; controller.SendFrame(frame); @@ -257,14 +251,13 @@ TEST_F(Test_EthControllerTrivialSim, linkup_controller_inactive_on_activate_deac TEST_F(Test_EthControllerTrivialSim, trigger_callback_on_receive_message) { std::vector rawFrame; - SetSourceMac(rawFrame, EthernetMac{ 0, 0, 0, 0, 0, 0 }); + SetSourceMac(rawFrame, EthernetMac{0, 0, 0, 0, 0, 0}); WireEthernetFrameEvent msg{}; msg.frame = WireEthernetFrame{rawFrame}; msg.direction = TransmitDirection::RX; - EXPECT_CALL(callbacks, ReceiveMessage(&controller, ToEthernetFrameEvent(msg))) - .Times(1); + EXPECT_CALL(callbacks, ReceiveMessage(&controller, ToEthernetFrameEvent(msg))).Times(1); controller.Activate(); controller.ReceiveMsg(&controllerOther, msg); @@ -276,15 +269,14 @@ TEST_F(Test_EthControllerTrivialSim, trigger_callback_on_receive_message) TEST_F(Test_EthControllerTrivialSim, trigger_callback_on_receive_ack) { std::vector rawFrame; - SetSourceMac(rawFrame, EthernetMac{ 1, 2, 3, 4, 5, 6 }); + SetSourceMac(rawFrame, EthernetMac{1, 2, 3, 4, 5, 6}); EthernetFrameEvent msg{}; msg.frame.raw = rawFrame; EXPECT_CALL(participant, SendMsg(&controller, AnEthMessageWith(0ns))).Times(1); - EthernetFrameTransmitEvent ack{ 0ms, EthernetTransmitStatus::Transmitted, reinterpret_cast(0) }; - EXPECT_CALL(callbacks, MessageAck(&controller, EthernetTransmitAckWithouthTransmitIdMatcher(ack))) - .Times(1); + EthernetFrameTransmitEvent ack{0ms, EthernetTransmitStatus::Transmitted, reinterpret_cast(0)}; + EXPECT_CALL(callbacks, MessageAck(&controller, EthernetTransmitAckWithouthTransmitIdMatcher(ack))).Times(1); // once for activate and once for sending the frame EXPECT_CALL(participant.mockTimeProvider, Now()).Times(3); @@ -302,7 +294,8 @@ TEST_F(Test_EthControllerTrivialSim, add_remove_handler) std::vector handlerIds; for (int i = 0; i < numHandlers; i++) { - handlerIds.push_back(testController.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessage))); + handlerIds.push_back( + testController.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessage))); } std::vector rawFrame; @@ -346,7 +339,7 @@ TEST_F(Test_EthControllerTrivialSim, remove_handler_in_handler) msg.direction = TransmitDirection::RX; EXPECT_CALL(callbacks, ReceiveMessage(&testController, ToEthernetFrameEvent(msg))).Times(1); - // Calls testHandler and Callbacks::ReceiveMessage, the latter is removed in testHandler + // Calls testHandler and Callbacks::ReceiveMessage, the latter is removed in testHandler testController.ReceiveMsg(&controllerOther, msg); EXPECT_CALL(callbacks, ReceiveMessage(&testController, ToEthernetFrameEvent(msg))).Times(0); // Call testHandler again, handlerIdToRemove is invalid now but should only result in a warning @@ -356,8 +349,7 @@ TEST_F(Test_EthControllerTrivialSim, remove_handler_in_handler) TEST_F(Test_EthControllerTrivialSim, ethcontroller_uses_tracing) { const auto now = 1337ns; - ON_CALL(participant.mockTimeProvider, Now()) - .WillByDefault(testing::Return(now)); + ON_CALL(participant.mockTimeProvider, Now()).WillByDefault(testing::Return(now)); EthController ethController{&participant, cfg, participant.GetTimeProvider()}; auto controllerDescriptor = ethController.GetServiceDescriptor(); @@ -365,22 +357,20 @@ TEST_F(Test_EthControllerTrivialSim, ethcontroller_uses_tracing) ethController.Activate(); std::vector rawFrame; - SetDestinationMac(rawFrame, EthernetMac{ 1, 2, 3, 4, 5, 6 }); - SetSourceMac(rawFrame, EthernetMac{ 9, 8, 7, 6, 5, 4 }); + SetDestinationMac(rawFrame, EthernetMac{1, 2, 3, 4, 5, 6}); + SetSourceMac(rawFrame, EthernetMac{9, 8, 7, 6, 5, 4}); EthernetFrame ethernetFrame; ethernetFrame.raw = rawFrame; //Send direction EXPECT_CALL(participant.mockTimeProvider, Now()).Times(2); - EXPECT_CALL(traceSink, - Trace(SilKit::Services::TransmitDirection::TX, controllerDescriptor, now,ethernetFrame)) + EXPECT_CALL(traceSink, Trace(SilKit::Services::TransmitDirection::TX, controllerDescriptor, now, ethernetFrame)) .Times(1); EthernetFrame frame{rawFrame}; ethController.SendFrame(frame); // Receive direction - EXPECT_CALL(traceSink, - Trace(SilKit::Services::TransmitDirection::RX, controllerDescriptor, now, ethernetFrame)) + EXPECT_CALL(traceSink, Trace(SilKit::Services::TransmitDirection::RX, controllerDescriptor, now, ethernetFrame)) .Times(1); WireEthernetFrameEvent wireEthernetFrame; @@ -400,16 +390,14 @@ TEST_F(Test_EthControllerTrivialSim, receive_pads_with_zeros) auto expectedEvent = ToEthernetFrameEvent(msg); expectedEvent.frame.raw = SilKit::Util::Span{expectedRaw}; - EXPECT_CALL(callbacks, ReceiveMessage(&controller, expectedEvent)) - .Times(1); + EXPECT_CALL(callbacks, ReceiveMessage(&controller, expectedEvent)).Times(1); controller.ReceiveMsg(&controllerOther, msg); } TEST_F(Test_EthControllerTrivialSim, sendmsg_distributes_before_txreceive) { - ON_CALL(participant.mockTimeProvider, Now()) - .WillByDefault(testing::Return(42ns)); + ON_CALL(participant.mockTimeProvider, Now()).WillByDefault(testing::Return(42ns)); testing::Sequence sequenceRxTx; testing::Sequence sequenceRxAck; @@ -428,7 +416,7 @@ TEST_F(Test_EthControllerTrivialSim, sendmsg_distributes_before_txreceive) .InSequence(sequenceRxAck); std::vector rawFrame; - SetSourceMac(rawFrame, EthernetMac{ 0, 0, 0, 0, 0, 0 }); + SetSourceMac(rawFrame, EthernetMac{0, 0, 0, 0, 0, 0}); EthernetFrame frame{rawFrame}; controller.Activate(); diff --git a/SilKit/source/services/ethernet/Test_EthernetSerdes.cpp b/SilKit/source/services/ethernet/Test_EthernetSerdes.cpp old mode 100755 new mode 100644 index 6c5870f66..ea69b56a3 --- a/SilKit/source/services/ethernet/Test_EthernetSerdes.cpp +++ b/SilKit/source/services/ethernet/Test_EthernetSerdes.cpp @@ -37,12 +37,13 @@ TEST(Test_EthernetSerdes, SimEthernet_EthMessage) WireEthernetFrameEvent in; WireEthernetFrameEvent out; - EthernetMac destinationMac{ 0x12, 0x23, 0x45, 0x67, 0x89, 0x9a }; - EthernetMac sourceMac{ 0x9a, 0x89, 0x67, 0x45, 0x23, 0x12 }; - EthernetEtherType etherType{ 0x0800 }; + EthernetMac destinationMac{0x12, 0x23, 0x45, 0x67, 0x89, 0x9a}; + EthernetMac sourceMac{0x9a, 0x89, 0x67, 0x45, 0x23, 0x12}; + EthernetEtherType etherType{0x0800}; in.timestamp = 13ns; - in.frame = CreateEthernetFrame(destinationMac, sourceMac, etherType, + in.frame = CreateEthernetFrame( + destinationMac, sourceMac, etherType, "Hello from ethernet writer! msgId = 1 -------------------------------------------------------"); in.direction = SilKit::Services::TransmitDirection::TX; in.userContext = reinterpret_cast(0x1234); diff --git a/SilKit/source/services/flexray/FlexrayController.cpp b/SilKit/source/services/flexray/FlexrayController.cpp old mode 100755 new mode 100644 index 4e9bb5dc5..53b2592fc --- a/SilKit/source/services/flexray/FlexrayController.cpp +++ b/SilKit/source/services/flexray/FlexrayController.cpp @@ -34,6 +34,7 @@ FlexrayController::FlexrayController(Core::IParticipantInternal* participant, Co Services::Orchestration::ITimeProvider* /*timeProvider*/) : _participant(participant) , _config{std::move(config)} + , _logger{participant->GetLogger()} { } @@ -44,27 +45,41 @@ FlexrayController::FlexrayController(Core::IParticipantInternal* participant, Co void FlexrayController::RegisterServiceDiscovery() { Core::Discovery::IServiceDiscovery* disc = _participant->GetServiceDiscovery(); - disc->RegisterServiceDiscoveryHandler( - [this](Core::Discovery::ServiceDiscoveryEvent::Type discoveryType, - const Core::ServiceDescriptor& remoteServiceDescriptor) { - // check if discovered service is a network simulator (if none is known) - if (!_simulatedLinkDetected) + disc->RegisterServiceDiscoveryHandler([this](Core::Discovery::ServiceDiscoveryEvent::Type discoveryType, + const Core::ServiceDescriptor& remoteServiceDescriptor) { + // check if discovered service is a network simulator (if none is known) + if (!_simulatedLinkDetected) + { + // check if received descriptor has a matching simulated link + if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated + && IsRelevantNetwork(remoteServiceDescriptor)) + { + Logging::Info(_logger, + "Controller '{}' is using the simulated network '{}' and will route all messages to " + "the network simulator '{}'", + _config.name, remoteServiceDescriptor.GetNetworkName(), + remoteServiceDescriptor.GetParticipantName()); + SetDetailedBehavior(remoteServiceDescriptor); + } + } + else + { + if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved + && IsRelevantNetwork(remoteServiceDescriptor)) { - // check if received descriptor has a matching simulated link - if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated - && IsRelevantNetwork(remoteServiceDescriptor)) - { - SetDetailedBehavior(remoteServiceDescriptor); - } + Logging::Error(_logger, + "The network simulator for controller '{}' left the simulation. FlexRay controllers " + "require a running network simulator to operate.", + _config.name); } - }); + } + }); } auto FlexrayController::AllowReception(const IServiceEndpoint* from) const -> bool { const auto& fromDescr = from->GetServiceDescriptor(); - return _simulatedLinkDetected && - _simulatedLink.GetParticipantName() == fromDescr.GetParticipantName() + return _simulatedLinkDetected && _simulatedLink.GetParticipantName() == fromDescr.GetParticipantName() && _serviceDescriptor.GetServiceId() == fromDescr.GetServiceId(); } @@ -140,14 +155,17 @@ void FlexrayController::ReconfigureTxBuffer(uint16_t txBufferIdx, const FlexrayT { if (txBufferIdx >= _bufferConfigs.size()) { - Logging::Error(_participant->GetLogger(), "FlexrayController::ReconfigureTxBuffer() was called with unconfigured txBufferIdx={}", txBufferIdx); + Logging::Error(_participant->GetLogger(), + "FlexrayController::ReconfigureTxBuffer() was called with unconfigured txBufferIdx={}", + txBufferIdx); throw OutOfRangeError{"Unconfigured txBufferIdx!"}; } if (!IsTxBufferConfigsConfigurable()) { - Logging::Error(_participant->GetLogger(), "ReconfigureTxBuffer() was called on a preconfigured txBuffer. This is not " - "allowed and the reconfiguration will be discarded."); + Logging::Error(_participant->GetLogger(), + "ReconfigureTxBuffer() was called on a preconfigured txBuffer. This is not " + "allowed and the reconfiguration will be discarded."); return; } @@ -161,7 +179,9 @@ void FlexrayController::UpdateTxBuffer(const FlexrayTxBufferUpdate& update) { if (update.txBufferIndex >= _bufferConfigs.size()) { - Logging::Error(_participant->GetLogger(), "FlexrayController::UpdateTxBuffer() was called with unconfigured txBufferIndex={}", update.txBufferIndex); + Logging::Error(_participant->GetLogger(), + "FlexrayController::UpdateTxBuffer() was called with unconfigured txBufferIndex={}", + update.txBufferIndex); throw OutOfRangeError{"Unconfigured txBufferIndex!"}; } @@ -175,16 +195,16 @@ void FlexrayController::UpdateTxBuffer(const FlexrayTxBufferUpdate& update) if (update.payload.size() > maxLength) { Logging::Warn(_participant->GetLogger(), - "FlexrayController::UpdateTxBuffer() was called with FlexRayTxBufferUpdate.payload size" - " exceeding 2*gPayloadLengthStatic ({}). The payload will be truncated.", - maxLength); + "FlexrayController::UpdateTxBuffer() was called with FlexRayTxBufferUpdate.payload size" + " exceeding 2*gPayloadLengthStatic ({}). The payload will be truncated.", + maxLength); } if (update.payload.size() < maxLength) { Logging::Warn(_participant->GetLogger(), - "FlexrayController::UpdateTxBuffer() was called with FlexRayTxBufferUpdate.payload size" - " lower than 2*gPayloadLengthStatic ({}). The payload will be zero padded.", - maxLength); + "FlexrayController::UpdateTxBuffer() was called with FlexRayTxBufferUpdate.payload size" + " lower than 2*gPayloadLengthStatic ({}). The payload will be zero padded.", + maxLength); } } } @@ -349,7 +369,7 @@ void FlexrayController::RemoveFrameTransmitHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - Logging::Warn(_participant->GetLogger(),"RemoveFrameTransmitHandler failed: Unknown HandlerId."); + Logging::Warn(_participant->GetLogger(), "RemoveFrameTransmitHandler failed: Unknown HandlerId."); } } diff --git a/SilKit/source/services/flexray/FlexrayController.hpp b/SilKit/source/services/flexray/FlexrayController.hpp old mode 100755 new mode 100644 index 0fedc23f5..f832c493d --- a/SilKit/source/services/flexray/FlexrayController.hpp +++ b/SilKit/source/services/flexray/FlexrayController.hpp @@ -125,7 +125,7 @@ class FlexrayController // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; public: // ---------------------------------------- @@ -150,7 +150,7 @@ class FlexrayController template void CallHandlers(const MsgT& msg); - template + template inline void SendMsg(MsgT&& msg); // Check, which config parameters are configurable @@ -169,22 +169,17 @@ class FlexrayController ::SilKit::Core::ServiceDescriptor _serviceDescriptor; std::vector _bufferConfigs; Tracer _tracer; - + Services::Logging::ILogger* _logger; bool _simulatedLinkDetected = false; Core::ServiceDescriptor _simulatedLink; template using CallbacksT = Util::SynchronizedHandlers>; - std::tuple< - CallbacksT, - CallbacksT, - CallbacksT, - CallbacksT, - CallbacksT, - CallbacksT, - CallbacksT - > _callbacks; + std::tuple, CallbacksT, CallbacksT, + CallbacksT, CallbacksT, + CallbacksT, CallbacksT> + _callbacks; }; // ================================================================== diff --git a/SilKit/source/services/flexray/FlexrayDatatypeUtils.cpp b/SilKit/source/services/flexray/FlexrayDatatypeUtils.cpp old mode 100755 new mode 100644 index 1fafcddbd..d92d1566b --- a/SilKit/source/services/flexray/FlexrayDatatypeUtils.cpp +++ b/SilKit/source/services/flexray/FlexrayDatatypeUtils.cpp @@ -27,62 +27,50 @@ namespace Flexray { bool operator==(const FlexrayHeader& lhs, const FlexrayHeader& rhs) { - return lhs.flags == rhs.flags - && lhs.frameId == rhs.frameId - && lhs.headerCrc == rhs.headerCrc - && lhs.cycleCount == rhs.cycleCount - && lhs.payloadLength == rhs.payloadLength; + return lhs.flags == rhs.flags && lhs.frameId == rhs.frameId && lhs.headerCrc == rhs.headerCrc + && lhs.cycleCount == rhs.cycleCount && lhs.payloadLength == rhs.payloadLength; } bool operator==(const FlexrayFrame& lhs, const FlexrayFrame& rhs) { - return lhs.header == rhs.header - && Util::ItemsAreEqual(lhs.payload, rhs.payload); + return lhs.header == rhs.header && Util::ItemsAreEqual(lhs.payload, rhs.payload); } bool operator==(const FlexrayFrameEvent& lhs, const FlexrayFrameEvent& rhs) { - return lhs.channel == rhs.channel - && lhs.frame == rhs.frame; + return lhs.channel == rhs.channel && lhs.frame == rhs.frame; } bool operator==(const FlexrayFrameTransmitEvent& lhs, const FlexrayFrameTransmitEvent& rhs) { - return lhs.txBufferIndex == rhs.txBufferIndex - && lhs.channel == rhs.channel - && lhs.frame == rhs.frame; + return lhs.txBufferIndex == rhs.txBufferIndex && lhs.channel == rhs.channel && lhs.frame == rhs.frame; } bool operator==(const FlexraySymbolEvent& lhs, const FlexraySymbolEvent& rhs) { - return lhs.channel == rhs.channel - && lhs.pattern == rhs.pattern; + return lhs.channel == rhs.channel && lhs.pattern == rhs.pattern; } bool operator==(const FlexrayWakeupEvent& lhs, const FlexrayWakeupEvent& rhs) { - return lhs.channel == rhs.channel - && lhs.pattern == rhs.pattern; + return lhs.channel == rhs.channel && lhs.pattern == rhs.pattern; } bool operator==(const FlexrayTxBufferConfigUpdate& lhs, const FlexrayTxBufferConfigUpdate& rhs) { - return lhs.txBufferIndex == rhs.txBufferIndex - && lhs.txBufferConfig == rhs.txBufferConfig; + return lhs.txBufferIndex == rhs.txBufferIndex && lhs.txBufferConfig == rhs.txBufferConfig; } bool operator==(const WireFlexrayTxBufferUpdate& lhs, const WireFlexrayTxBufferUpdate& rhs) { - return lhs.txBufferIndex == rhs.txBufferIndex - && lhs.payloadDataValid == rhs.payloadDataValid - && Util::ItemsAreEqual(lhs.payload, rhs.payload); + return lhs.txBufferIndex == rhs.txBufferIndex && lhs.payloadDataValid == rhs.payloadDataValid + && Util::ItemsAreEqual(lhs.payload, rhs.payload); } bool operator==(const FlexrayControllerConfig& lhs, const FlexrayControllerConfig& rhs) { - return lhs.clusterParams == rhs.clusterParams - && lhs.nodeParams == rhs.nodeParams - && lhs.bufferConfigs == rhs.bufferConfigs; + return lhs.clusterParams == rhs.clusterParams && lhs.nodeParams == rhs.nodeParams + && lhs.bufferConfigs == rhs.bufferConfigs; } bool operator==(const FlexrayHostCommand& lhs, const FlexrayHostCommand& rhs) @@ -92,22 +80,16 @@ bool operator==(const FlexrayHostCommand& lhs, const FlexrayHostCommand& rhs) bool operator==(const FlexrayPocStatusEvent& lhs, const FlexrayPocStatusEvent& rhs) { - return lhs.state == rhs.state - && lhs.chiHaltRequest == rhs.chiHaltRequest - && lhs.chiReadyRequest == rhs.chiReadyRequest - && lhs.slotMode == rhs.slotMode - && lhs.errorMode == rhs.errorMode - && lhs.wakeupStatus == rhs.wakeupStatus - && lhs.startupState == rhs.startupState - && lhs.freeze == rhs.freeze - && lhs.coldstartNoise == rhs.coldstartNoise - ; + return lhs.state == rhs.state && lhs.chiHaltRequest == rhs.chiHaltRequest + && lhs.chiReadyRequest == rhs.chiReadyRequest && lhs.slotMode == rhs.slotMode + && lhs.errorMode == rhs.errorMode && lhs.wakeupStatus == rhs.wakeupStatus + && lhs.startupState == rhs.startupState && lhs.freeze == rhs.freeze + && lhs.coldstartNoise == rhs.coldstartNoise; } bool operator==(const FlexrayCycleStartEvent& lhs, const FlexrayCycleStartEvent& rhs) { - return lhs.cycleCounter == rhs.cycleCounter - && lhs.timestamp == rhs.timestamp; + return lhs.cycleCounter == rhs.cycleCounter && lhs.timestamp == rhs.timestamp; } } // namespace Flexray diff --git a/SilKit/source/services/flexray/FlexraySerdes.cpp b/SilKit/source/services/flexray/FlexraySerdes.cpp old mode 100755 new mode 100644 index 68acfb0df..c9d00f0d6 --- a/SilKit/source/services/flexray/FlexraySerdes.cpp +++ b/SilKit/source/services/flexray/FlexraySerdes.cpp @@ -29,363 +29,230 @@ using SilKit::Core::MessageBuffer; inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexrayHeader& header) { - buffer - << header.flags - << header.frameId - << header.payloadLength - << header.headerCrc - << header.cycleCount; + buffer << header.flags << header.frameId << header.payloadLength << header.headerCrc << header.cycleCount; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayHeader& header) { - buffer - >> header.flags - >> header.frameId - >> header.payloadLength - >> header.headerCrc - >> header.cycleCount; + buffer >> header.flags >> header.frameId >> header.payloadLength >> header.headerCrc >> header.cycleCount; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const WireFlexrayFrame& frame) { - buffer - << frame.header - << frame.payload; + buffer << frame.header << frame.payload; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, WireFlexrayFrame& frame) { - buffer - >> frame.header - >> frame.payload; + buffer >> frame.header >> frame.payload; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const WireFlexrayFrameEvent& msg) { - buffer - << msg.timestamp - << msg.channel - << msg.frame; + buffer << msg.timestamp << msg.channel << msg.frame; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, WireFlexrayFrameEvent& msg) { - buffer - >> msg.timestamp - >> msg.channel - >> msg.frame; + buffer >> msg.timestamp >> msg.channel >> msg.frame; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const WireFlexrayFrameTransmitEvent& msg) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const WireFlexrayFrameTransmitEvent& msg) { - buffer - << msg.timestamp - << msg.txBufferIndex - << msg.channel - << msg.frame; + buffer << msg.timestamp << msg.txBufferIndex << msg.channel << msg.frame; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, WireFlexrayFrameTransmitEvent& msg) { - buffer - >> msg.timestamp - >> msg.txBufferIndex - >> msg.channel - >> msg.frame; + buffer >> msg.timestamp >> msg.txBufferIndex >> msg.channel >> msg.frame; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexraySymbolEvent& symbol) { - buffer - << symbol.timestamp - << symbol.channel - << symbol.pattern; + buffer << symbol.timestamp << symbol.channel << symbol.pattern; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexraySymbolEvent& symbol) { - buffer - >> symbol.timestamp - >> symbol.channel - >> symbol.pattern; + buffer >> symbol.timestamp >> symbol.channel >> symbol.pattern; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexraySymbolTransmitEvent& ack) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const FlexraySymbolTransmitEvent& ack) { auto&& symbol = static_cast(ack); - buffer - << symbol; + buffer << symbol; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexraySymbolTransmitEvent& ack) { auto&& symbol = static_cast(ack); - buffer - >> symbol; + buffer >> symbol; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, - const FlexrayCycleStartEvent& flexrayCycleStartEvent) + const FlexrayCycleStartEvent& flexrayCycleStartEvent) { - buffer - << flexrayCycleStartEvent.timestamp - << flexrayCycleStartEvent.cycleCounter; + buffer << flexrayCycleStartEvent.timestamp << flexrayCycleStartEvent.cycleCounter; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayCycleStartEvent& flexrayCycleStartEvent) +inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, + FlexrayCycleStartEvent& flexrayCycleStartEvent) { - buffer - >> flexrayCycleStartEvent.timestamp - >> flexrayCycleStartEvent.cycleCounter; + buffer >> flexrayCycleStartEvent.timestamp >> flexrayCycleStartEvent.cycleCounter; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexrayHostCommand& cmd) { - buffer - << cmd.command; + buffer << cmd.command; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayHostCommand& cmd) { - buffer - >> cmd.command; + buffer >> cmd.command; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexrayClusterParameters& clusterParam) -{ - buffer - << clusterParam.gColdstartAttempts - << clusterParam.gCycleCountMax - << clusterParam.gdActionPointOffset - << clusterParam.gdDynamicSlotIdlePhase - << clusterParam.gdMiniSlot - << clusterParam.gdMiniSlotActionPointOffset - << clusterParam.gdStaticSlot - << clusterParam.gdSymbolWindow - << clusterParam.gdSymbolWindowActionPointOffset - << clusterParam.gdTSSTransmitter - << clusterParam.gdWakeupTxActive - << clusterParam.gdWakeupTxIdle - << clusterParam.gListenNoise - << clusterParam.gMacroPerCycle - << clusterParam.gMaxWithoutClockCorrectionFatal - << clusterParam.gMaxWithoutClockCorrectionPassive - << clusterParam.gNumberOfMiniSlots - << clusterParam.gNumberOfStaticSlots - << clusterParam.gPayloadLengthStatic - << clusterParam.gSyncFrameIDCountMax; +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const FlexrayClusterParameters& clusterParam) +{ + buffer << clusterParam.gColdstartAttempts << clusterParam.gCycleCountMax << clusterParam.gdActionPointOffset + << clusterParam.gdDynamicSlotIdlePhase << clusterParam.gdMiniSlot << clusterParam.gdMiniSlotActionPointOffset + << clusterParam.gdStaticSlot << clusterParam.gdSymbolWindow << clusterParam.gdSymbolWindowActionPointOffset + << clusterParam.gdTSSTransmitter << clusterParam.gdWakeupTxActive << clusterParam.gdWakeupTxIdle + << clusterParam.gListenNoise << clusterParam.gMacroPerCycle << clusterParam.gMaxWithoutClockCorrectionFatal + << clusterParam.gMaxWithoutClockCorrectionPassive << clusterParam.gNumberOfMiniSlots + << clusterParam.gNumberOfStaticSlots << clusterParam.gPayloadLengthStatic + << clusterParam.gSyncFrameIDCountMax; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayClusterParameters& clusterParam) -{ - buffer - >> clusterParam.gColdstartAttempts - >> clusterParam.gCycleCountMax - >> clusterParam.gdActionPointOffset - >> clusterParam.gdDynamicSlotIdlePhase - >> clusterParam.gdMiniSlot - >> clusterParam.gdMiniSlotActionPointOffset - >> clusterParam.gdStaticSlot - >> clusterParam.gdSymbolWindow - >> clusterParam.gdSymbolWindowActionPointOffset - >> clusterParam.gdTSSTransmitter - >> clusterParam.gdWakeupTxActive - >> clusterParam.gdWakeupTxIdle - >> clusterParam.gListenNoise - >> clusterParam.gMacroPerCycle - >> clusterParam.gMaxWithoutClockCorrectionFatal - >> clusterParam.gMaxWithoutClockCorrectionPassive - >> clusterParam.gNumberOfMiniSlots - >> clusterParam.gNumberOfStaticSlots - >> clusterParam.gPayloadLengthStatic - >> clusterParam.gSyncFrameIDCountMax; +inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, + FlexrayClusterParameters& clusterParam) +{ + buffer >> clusterParam.gColdstartAttempts >> clusterParam.gCycleCountMax >> clusterParam.gdActionPointOffset + >> clusterParam.gdDynamicSlotIdlePhase >> clusterParam.gdMiniSlot >> clusterParam.gdMiniSlotActionPointOffset + >> clusterParam.gdStaticSlot >> clusterParam.gdSymbolWindow >> clusterParam.gdSymbolWindowActionPointOffset + >> clusterParam.gdTSSTransmitter >> clusterParam.gdWakeupTxActive >> clusterParam.gdWakeupTxIdle + >> clusterParam.gListenNoise >> clusterParam.gMacroPerCycle >> clusterParam.gMaxWithoutClockCorrectionFatal + >> clusterParam.gMaxWithoutClockCorrectionPassive >> clusterParam.gNumberOfMiniSlots + >> clusterParam.gNumberOfStaticSlots >> clusterParam.gPayloadLengthStatic >> clusterParam.gSyncFrameIDCountMax; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexrayNodeParameters& nodeParams) -{ - buffer - << nodeParams.pAllowHaltDueToClock - << nodeParams.pAllowPassiveToActive - << nodeParams.pChannels - << nodeParams.pClusterDriftDamping - << nodeParams.pdAcceptedStartupRange - << nodeParams.pdListenTimeout - << nodeParams.pKeySlotId - << nodeParams.pKeySlotOnlyEnabled - << nodeParams.pKeySlotUsedForStartup - << nodeParams.pKeySlotUsedForSync - << nodeParams.pLatestTx - << nodeParams.pMacroInitialOffsetA - << nodeParams.pMacroInitialOffsetB - << nodeParams.pMicroInitialOffsetA - << nodeParams.pMicroInitialOffsetB - << nodeParams.pMicroPerCycle - << nodeParams.pOffsetCorrectionOut - << nodeParams.pOffsetCorrectionStart - << nodeParams.pRateCorrectionOut - << nodeParams.pWakeupChannel - << nodeParams.pWakeupPattern - << nodeParams.pdMicrotick - << nodeParams.pSamplesPerMicrotick; +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const FlexrayNodeParameters& nodeParams) +{ + buffer << nodeParams.pAllowHaltDueToClock << nodeParams.pAllowPassiveToActive << nodeParams.pChannels + << nodeParams.pClusterDriftDamping << nodeParams.pdAcceptedStartupRange << nodeParams.pdListenTimeout + << nodeParams.pKeySlotId << nodeParams.pKeySlotOnlyEnabled << nodeParams.pKeySlotUsedForStartup + << nodeParams.pKeySlotUsedForSync << nodeParams.pLatestTx << nodeParams.pMacroInitialOffsetA + << nodeParams.pMacroInitialOffsetB << nodeParams.pMicroInitialOffsetA << nodeParams.pMicroInitialOffsetB + << nodeParams.pMicroPerCycle << nodeParams.pOffsetCorrectionOut << nodeParams.pOffsetCorrectionStart + << nodeParams.pRateCorrectionOut << nodeParams.pWakeupChannel << nodeParams.pWakeupPattern + << nodeParams.pdMicrotick << nodeParams.pSamplesPerMicrotick; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayNodeParameters& nodeParams) { - buffer - >> nodeParams.pAllowHaltDueToClock - >> nodeParams.pAllowPassiveToActive - >> nodeParams.pChannels - >> nodeParams.pClusterDriftDamping - >> nodeParams.pdAcceptedStartupRange - >> nodeParams.pdListenTimeout - >> nodeParams.pKeySlotId - >> nodeParams.pKeySlotOnlyEnabled - >> nodeParams.pKeySlotUsedForStartup - >> nodeParams.pKeySlotUsedForSync - >> nodeParams.pLatestTx - >> nodeParams.pMacroInitialOffsetA - >> nodeParams.pMacroInitialOffsetB - >> nodeParams.pMicroInitialOffsetA - >> nodeParams.pMicroInitialOffsetB - >> nodeParams.pMicroPerCycle - >> nodeParams.pOffsetCorrectionOut - >> nodeParams.pOffsetCorrectionStart - >> nodeParams.pRateCorrectionOut - >> nodeParams.pWakeupChannel - >> nodeParams.pWakeupPattern - >> nodeParams.pdMicrotick - >> nodeParams.pSamplesPerMicrotick; + buffer >> nodeParams.pAllowHaltDueToClock >> nodeParams.pAllowPassiveToActive >> nodeParams.pChannels + >> nodeParams.pClusterDriftDamping >> nodeParams.pdAcceptedStartupRange >> nodeParams.pdListenTimeout + >> nodeParams.pKeySlotId >> nodeParams.pKeySlotOnlyEnabled >> nodeParams.pKeySlotUsedForStartup + >> nodeParams.pKeySlotUsedForSync >> nodeParams.pLatestTx >> nodeParams.pMacroInitialOffsetA + >> nodeParams.pMacroInitialOffsetB >> nodeParams.pMicroInitialOffsetA >> nodeParams.pMicroInitialOffsetB + >> nodeParams.pMicroPerCycle >> nodeParams.pOffsetCorrectionOut >> nodeParams.pOffsetCorrectionStart + >> nodeParams.pRateCorrectionOut >> nodeParams.pWakeupChannel >> nodeParams.pWakeupPattern + >> nodeParams.pdMicrotick >> nodeParams.pSamplesPerMicrotick; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexrayTxBufferConfig& config) { - buffer - << config.channels - << config.slotId - << config.offset - << config.repetition - << config.hasPayloadPreambleIndicator - << config.headerCrc - << config.transmissionMode; + buffer << config.channels << config.slotId << config.offset << config.repetition + << config.hasPayloadPreambleIndicator << config.headerCrc << config.transmissionMode; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayTxBufferConfig& config) { - buffer - >> config.channels - >> config.slotId - >> config.offset - >> config.repetition - >> config.hasPayloadPreambleIndicator - >> config.headerCrc - >> config.transmissionMode; + buffer >> config.channels >> config.slotId >> config.offset >> config.repetition + >> config.hasPayloadPreambleIndicator >> config.headerCrc >> config.transmissionMode; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexrayControllerConfig& config) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const FlexrayControllerConfig& config) { - buffer - << config.clusterParams - << config.nodeParams - << config.bufferConfigs; + buffer << config.clusterParams << config.nodeParams << config.bufferConfigs; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayControllerConfig& config) { - buffer - >> config.clusterParams - >> config.nodeParams - >> config.bufferConfigs; + buffer >> config.clusterParams >> config.nodeParams >> config.bufferConfigs; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const FlexrayTxBufferConfigUpdate& update) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const FlexrayTxBufferConfigUpdate& update) { - buffer - << update.txBufferIndex - << update.txBufferConfig; + buffer << update.txBufferIndex << update.txBufferConfig; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayTxBufferConfigUpdate& update) { - buffer - >> update.txBufferIndex - >> update.txBufferConfig; + buffer >> update.txBufferIndex >> update.txBufferConfig; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const WireFlexrayTxBufferUpdate& update) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const WireFlexrayTxBufferUpdate& update) { - buffer - << update.txBufferIndex - << update.payloadDataValid - << update.payload; + buffer << update.txBufferIndex << update.payloadDataValid << update.payload; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, WireFlexrayTxBufferUpdate& update) { - buffer - >> update.txBufferIndex - >> update.payloadDataValid - >> update.payload; + buffer >> update.txBufferIndex >> update.payloadDataValid >> update.payload; return buffer; } inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, - const FlexrayPocStatusEvent& flexrayPocStatusEvent) -{ - buffer - << flexrayPocStatusEvent.timestamp - << flexrayPocStatusEvent.chiHaltRequest - << flexrayPocStatusEvent.coldstartNoise - << flexrayPocStatusEvent.errorMode - << flexrayPocStatusEvent.freeze - << flexrayPocStatusEvent.slotMode - << flexrayPocStatusEvent.startupState - << flexrayPocStatusEvent.state - << flexrayPocStatusEvent.wakeupStatus - << flexrayPocStatusEvent.chiReadyRequest; + const FlexrayPocStatusEvent& flexrayPocStatusEvent) +{ + buffer << flexrayPocStatusEvent.timestamp << flexrayPocStatusEvent.chiHaltRequest + << flexrayPocStatusEvent.coldstartNoise << flexrayPocStatusEvent.errorMode << flexrayPocStatusEvent.freeze + << flexrayPocStatusEvent.slotMode << flexrayPocStatusEvent.startupState << flexrayPocStatusEvent.state + << flexrayPocStatusEvent.wakeupStatus << flexrayPocStatusEvent.chiReadyRequest; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, FlexrayPocStatusEvent& flexrayPocStatusEvent) +inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, + FlexrayPocStatusEvent& flexrayPocStatusEvent) { - buffer - >> flexrayPocStatusEvent.timestamp - >> flexrayPocStatusEvent.chiHaltRequest - >> flexrayPocStatusEvent.coldstartNoise - >> flexrayPocStatusEvent.errorMode - >> flexrayPocStatusEvent.freeze - >> flexrayPocStatusEvent.slotMode - >> flexrayPocStatusEvent.startupState - >> flexrayPocStatusEvent.state - >> flexrayPocStatusEvent.wakeupStatus - >> flexrayPocStatusEvent.chiReadyRequest; + buffer >> flexrayPocStatusEvent.timestamp >> flexrayPocStatusEvent.chiHaltRequest + >> flexrayPocStatusEvent.coldstartNoise >> flexrayPocStatusEvent.errorMode >> flexrayPocStatusEvent.freeze + >> flexrayPocStatusEvent.slotMode >> flexrayPocStatusEvent.startupState >> flexrayPocStatusEvent.state + >> flexrayPocStatusEvent.wakeupStatus >> flexrayPocStatusEvent.chiReadyRequest; return buffer; } diff --git a/SilKit/source/services/flexray/FlexraySerdes.hpp b/SilKit/source/services/flexray/FlexraySerdes.hpp index bea35af4f..1316fd977 100644 --- a/SilKit/source/services/flexray/FlexraySerdes.hpp +++ b/SilKit/source/services/flexray/FlexraySerdes.hpp @@ -52,6 +52,6 @@ void Deserialize(SilKit::Core::MessageBuffer& buffer, FlexrayTxBufferConfigUpdat void Deserialize(SilKit::Core::MessageBuffer& buffer, WireFlexrayTxBufferUpdate& out); void Deserialize(SilKit::Core::MessageBuffer& buffer, FlexrayPocStatusEvent& out); -} // namespace Flexray +} // namespace Flexray } // namespace Services } // namespace SilKit diff --git a/SilKit/source/services/flexray/IMsgForFlexrayBusSimulator.hpp b/SilKit/source/services/flexray/IMsgForFlexrayBusSimulator.hpp old mode 100755 new mode 100644 index 211309476..30cc05436 --- a/SilKit/source/services/flexray/IMsgForFlexrayBusSimulator.hpp +++ b/SilKit/source/services/flexray/IMsgForFlexrayBusSimulator.hpp @@ -44,14 +44,6 @@ class IMsgForFlexraySimulator { public: ~IMsgForFlexraySimulator() = default; - - /* NB: There is no setter or getter for an EndpointAddress of the bus - * simulator, since the network simulator manages multiple controllers with - * different endpoints. I.e., the network simulator is aware of the endpointIds. - */ - //! \brief Setter and getter for the ParticipantID associated with this FlexRay network simulator - virtual void SetParticipantId(SilKit::Core::ParticipantId participantId) = 0; - virtual auto GetParticipantId() const -> SilKit::Core::ParticipantId = 0; }; } // namespace Flexray diff --git a/SilKit/source/services/flexray/Test_FlexrayController.cpp b/SilKit/source/services/flexray/Test_FlexrayController.cpp old mode 100755 new mode 100644 index 34aa089e1..8378974ac --- a/SilKit/source/services/flexray/Test_FlexrayController.cpp +++ b/SilKit/source/services/flexray/Test_FlexrayController.cpp @@ -127,7 +127,7 @@ auto MakeValidTxBufferConfig() -> FlexrayTxBufferConfig bufferCfg.repetition = 0; bufferCfg.slotId = 17; bufferCfg.transmissionMode = FlexrayTransmissionMode::SingleShot; - + return bufferCfg; } @@ -145,10 +145,10 @@ auto GetDummyConfigWithValues() -> SilKit::Config::FlexrayController class MockParticipant : public DummyParticipant { public: - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const FlexrayHostCommand&)); - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const FlexrayControllerConfig&)); - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const FlexrayTxBufferConfigUpdate&)); - MOCK_METHOD2(SendMsg, void(const IServiceEndpoint*, const WireFlexrayTxBufferUpdate&)); + MOCK_METHOD2(SendMsg, void(const IServiceEndpoint *, const FlexrayHostCommand &)); + MOCK_METHOD2(SendMsg, void(const IServiceEndpoint *, const FlexrayControllerConfig &)); + MOCK_METHOD2(SendMsg, void(const IServiceEndpoint *, const FlexrayTxBufferConfigUpdate &)); + MOCK_METHOD2(SendMsg, void(const IServiceEndpoint *, const WireFlexrayTxBufferUpdate &)); }; class Test_FlexrayController : public testing::Test @@ -156,23 +156,21 @@ class Test_FlexrayController : public testing::Test protected: struct Callbacks { - MOCK_METHOD2(MessageHandler, void(IFlexrayController*, const FlexrayFrameEvent &)); - MOCK_METHOD2(MessageAckHandler, void(IFlexrayController*, const FlexrayFrameTransmitEvent &)); - MOCK_METHOD2(WakeupHandler, void(IFlexrayController*, const FlexrayWakeupEvent &)); - MOCK_METHOD2(PocStatusHandler, void(IFlexrayController*, const FlexrayPocStatusEvent &)); - MOCK_METHOD2(SymbolHandler, void(IFlexrayController*, const FlexraySymbolEvent &)); - MOCK_METHOD2(SymbolAckHandler, void(IFlexrayController*, const FlexraySymbolTransmitEvent &)); - MOCK_METHOD2(CycleStartHandler, void(IFlexrayController*, const FlexrayCycleStartEvent &)); + MOCK_METHOD2(MessageHandler, void(IFlexrayController *, const FlexrayFrameEvent &)); + MOCK_METHOD2(MessageAckHandler, void(IFlexrayController *, const FlexrayFrameTransmitEvent &)); + MOCK_METHOD2(WakeupHandler, void(IFlexrayController *, const FlexrayWakeupEvent &)); + MOCK_METHOD2(PocStatusHandler, void(IFlexrayController *, const FlexrayPocStatusEvent &)); + MOCK_METHOD2(SymbolHandler, void(IFlexrayController *, const FlexraySymbolEvent &)); + MOCK_METHOD2(SymbolAckHandler, void(IFlexrayController *, const FlexraySymbolTransmitEvent &)); + MOCK_METHOD2(CycleStartHandler, void(IFlexrayController *, const FlexrayCycleStartEvent &)); }; protected: Test_FlexrayController() : controller(&participant, GetDummyConfig(), participant.GetTimeProvider()) , controllerBusSim(&participant, GetDummyConfig(), participant.GetTimeProvider()) - , controllerConfigured(&participant, GetDummyConfigWithValues(), - participant.GetTimeProvider()) + , controllerConfigured(&participant, GetDummyConfigWithValues(), participant.GetTimeProvider()) { - controller.SetServiceDescriptor(controllerAddress); controller.SetDetailedBehavior(busSimAddress); referencePayload.resize(20); @@ -194,7 +192,6 @@ class Test_FlexrayController : public testing::Test Callbacks callbacks; SilKit::Config::FlexrayController dummyConfig; - }; TEST_F(Test_FlexrayController, send_controller_config) @@ -344,7 +341,8 @@ TEST_F(Test_FlexrayController, throw_on_unconfigured_tx_buffer_configupdate) // Attempt to reconfigure TxBuffer 6, which should be out of range FlexrayTxBufferConfig bufferCfg{}; - EXPECT_CALL(participant, SendMsg(An(), A())).Times(0); + EXPECT_CALL(participant, SendMsg(An(), A())) + .Times(0); EXPECT_THROW(controller.ReconfigureTxBuffer(6, bufferCfg), SilKit::OutOfRangeError); } @@ -366,8 +364,7 @@ TEST_F(Test_FlexrayController, send_txbuffer_update) update.payload = referencePayload; update.payloadDataValid = true; - EXPECT_CALL(participant, SendMsg(&controller, update)) - .Times(1); + EXPECT_CALL(participant, SendMsg(&controller, update)).Times(1); controller.UpdateTxBuffer(ToFlexrayTxBufferUpdate(update)); } @@ -385,38 +382,35 @@ TEST_F(Test_FlexrayController, throw_on_unconfigured_tx_buffer_update) FlexrayTxBufferUpdate update; update.txBufferIndex = 7; // only txBufferIdx = 0 is configured - EXPECT_CALL(participant, SendMsg(An(), A())).Times(0); + EXPECT_CALL(participant, SendMsg(An(), A())) + .Times(0); EXPECT_THROW(controller.UpdateTxBuffer(update), SilKit::OutOfRangeError); } TEST_F(Test_FlexrayController, send_run_command) { - EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::RUN})) - .Times(1); + EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::RUN})).Times(1); controller.Run(); } TEST_F(Test_FlexrayController, send_deferred_halt_command) { - EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::DEFERRED_HALT})) - .Times(1); + EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::DEFERRED_HALT})).Times(1); controller.DeferredHalt(); } TEST_F(Test_FlexrayController, send_freeze_command) { - EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::FREEZE})) - .Times(1); + EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::FREEZE})).Times(1); controller.Freeze(); } TEST_F(Test_FlexrayController, send_allow_coldstart_command) { - EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::ALLOW_COLDSTART})) - .Times(1); + EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::ALLOW_COLDSTART})).Times(1); controller.AllowColdstart(); } @@ -426,16 +420,14 @@ TEST_F(Test_FlexrayController, send_all_slots_command) FlexrayHostCommand cmd; cmd.command = FlexrayChiCommand::ALL_SLOTS; - EXPECT_CALL(participant, SendMsg(&controller, cmd)) - .Times(1); + EXPECT_CALL(participant, SendMsg(&controller, cmd)).Times(1); controller.AllSlots(); } TEST_F(Test_FlexrayController, send_wakeup_command) { - EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::WAKEUP})) - .Times(1); + EXPECT_CALL(participant, SendMsg(&controller, FlexrayHostCommand{FlexrayChiCommand::WAKEUP})).Times(1); controller.Wakeup(); } @@ -452,8 +444,7 @@ TEST_F(Test_FlexrayController, call_message_handler) message.frame.header.payloadLength = static_cast(referencePayload.size() / 2); message.frame.payload = referencePayload; - EXPECT_CALL(callbacks, MessageHandler(&controller, ToFlexrayFrameEvent(message))) - .Times(1); + EXPECT_CALL(callbacks, MessageHandler(&controller, ToFlexrayFrameEvent(message))).Times(1); controller.ReceiveMsg(&controllerBusSim, message); } @@ -469,8 +460,7 @@ TEST_F(Test_FlexrayController, call_message_ack_handler) ack.frame.header.payloadLength = static_cast(referencePayload.size() / 2); ack.frame.payload = referencePayload; - EXPECT_CALL(callbacks, MessageAckHandler(&controller, ToFlexrayFrameTransmitEvent(ack))) - .Times(1); + EXPECT_CALL(callbacks, MessageAckHandler(&controller, ToFlexrayFrameTransmitEvent(ack))).Times(1); controller.ReceiveMsg(&controllerBusSim, ack); } @@ -482,20 +472,17 @@ TEST_F(Test_FlexrayController, call_wakeup_handler) FlexraySymbolEvent wusSymbolEvent = {}; wusSymbolEvent.pattern = FlexraySymbolPattern::Wus; auto wus = FlexrayWakeupEvent{wusSymbolEvent}; - EXPECT_CALL(callbacks, WakeupHandler(&controller, wus)) - .Times(1); + EXPECT_CALL(callbacks, WakeupHandler(&controller, wus)).Times(1); FlexraySymbolEvent wudopSymbolEvent = {}; wudopSymbolEvent.pattern = FlexraySymbolPattern::Wudop; auto wudop = FlexrayWakeupEvent{wudopSymbolEvent}; - EXPECT_CALL(callbacks, WakeupHandler(&controller, wudop)) - .Times(1); + EXPECT_CALL(callbacks, WakeupHandler(&controller, wudop)).Times(1); FlexraySymbolEvent casMtsSymbolEvent = {}; casMtsSymbolEvent.pattern = FlexraySymbolPattern::CasMts; auto casMts = FlexrayWakeupEvent{casMtsSymbolEvent}; - EXPECT_CALL(callbacks, WakeupHandler(&controller, casMts)) - .Times(0); + EXPECT_CALL(callbacks, WakeupHandler(&controller, casMts)).Times(0); controller.ReceiveMsg(&controllerBusSim, wusSymbolEvent); controller.ReceiveMsg(&controllerBusSim, wudopSymbolEvent); @@ -510,8 +497,7 @@ TEST_F(Test_FlexrayController, call_pocstatus_handler) poc.timestamp = 14ms; poc.state = FlexrayPocState::Ready; - EXPECT_CALL(callbacks, PocStatusHandler(&controller, poc)) - .Times(1); + EXPECT_CALL(callbacks, PocStatusHandler(&controller, poc)).Times(1); controller.ReceiveMsg(&controllerBusSim, poc); } @@ -522,18 +508,15 @@ TEST_F(Test_FlexrayController, call_symbol_handler) FlexraySymbolEvent wus; wus.pattern = FlexraySymbolPattern::Wus; - EXPECT_CALL(callbacks, SymbolHandler(&controller, wus)) - .Times(1); + EXPECT_CALL(callbacks, SymbolHandler(&controller, wus)).Times(1); FlexraySymbolEvent wudop; wudop.pattern = FlexraySymbolPattern::Wudop; - EXPECT_CALL(callbacks, SymbolHandler(&controller, wudop)) - .Times(1); + EXPECT_CALL(callbacks, SymbolHandler(&controller, wudop)).Times(1); FlexraySymbolEvent casMts; casMts.pattern = FlexraySymbolPattern::CasMts; - EXPECT_CALL(callbacks, SymbolHandler(&controller, casMts)) - .Times(1); + EXPECT_CALL(callbacks, SymbolHandler(&controller, casMts)).Times(1); controller.ReceiveMsg(&controllerBusSim, wus); controller.ReceiveMsg(&controllerBusSim, wudop); @@ -548,8 +531,7 @@ TEST_F(Test_FlexrayController, call_symbol_ack_handler) ack.channel = FlexrayChannel::B; ack.pattern = FlexraySymbolPattern::CasMts; - EXPECT_CALL(callbacks, SymbolAckHandler(&controller, ack)) - .Times(1); + EXPECT_CALL(callbacks, SymbolAckHandler(&controller, ack)).Times(1); controller.ReceiveMsg(&controllerBusSim, ack); } @@ -562,8 +544,7 @@ TEST_F(Test_FlexrayController, call_cyclestart_handler) cycleStart.timestamp = 15ns; cycleStart.cycleCounter = 5u; - EXPECT_CALL(callbacks, CycleStartHandler(&controller, cycleStart)) - .Times(1); + EXPECT_CALL(callbacks, CycleStartHandler(&controller, cycleStart)).Times(1); controller.ReceiveMsg(&controllerBusSim, cycleStart); } @@ -589,7 +570,7 @@ TEST_F(Test_FlexrayController, add_remove_handler) EXPECT_CALL(callbacks, MessageHandler(&controller, ToFlexrayFrameEvent(message))).Times(numHandlers); controller.ReceiveMsg(&controllerBusSim, message); - for (auto&& handlerId : handlerIds) + for (auto &&handlerId : handlerIds) { controller.RemoveFrameHandler(handlerId); } @@ -602,7 +583,7 @@ TEST_F(Test_FlexrayController, txbuffer_update_in_static_segment_produces_warnin { // Configure Controller auto config = GetDummyConfigWithValues(); - config.txBufferConfigurations.at(0).slotId = 2;//must be in static segment + config.txBufferConfigurations.at(0).slotId = 2; //must be in static segment FlexrayControllerConfig controllerConfig{}; diff --git a/SilKit/source/services/flexray/Test_FlexrayControllerConfig.cpp b/SilKit/source/services/flexray/Test_FlexrayControllerConfig.cpp index 206d1bbe2..80ce42785 100644 --- a/SilKit/source/services/flexray/Test_FlexrayControllerConfig.cpp +++ b/SilKit/source/services/flexray/Test_FlexrayControllerConfig.cpp @@ -37,7 +37,7 @@ using namespace SilKit::Services::Flexray; class Test_FlexrayControllerConfig : public testing::Test { public: - Test_FlexrayControllerConfig(){}; + Test_FlexrayControllerConfig() {}; }; auto PrepareParticipantConfiguration() -> std::shared_ptr @@ -91,4 +91,4 @@ TEST(Test_FlexrayControllerConfig, create_controller_configured_with_network) EXPECT_EQ(serviceDescr.GetNetworkName(), expectedNetworkName); } -} // anonymous namespace +} // anonymous namespace diff --git a/SilKit/source/services/flexray/Test_FlexraySerdes.cpp b/SilKit/source/services/flexray/Test_FlexraySerdes.cpp old mode 100755 new mode 100644 index 3bdd5311a..f9ecf6af0 --- a/SilKit/source/services/flexray/Test_FlexraySerdes.cpp +++ b/SilKit/source/services/flexray/Test_FlexraySerdes.cpp @@ -28,7 +28,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using namespace std::chrono_literals; -TEST(Test_FlexraySerdes, SimFlexray_FlexrayFrameEvent){ +TEST(Test_FlexraySerdes, SimFlexray_FlexrayFrameEvent) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -51,8 +52,8 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayFrameEvent){ std::string message{"Hello from flexray! msgId = 1 -------------"}; in.frame.payload = std::vector{message.begin(), message.end()}; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.timestamp, out.timestamp); EXPECT_EQ(in.channel, out.channel); @@ -66,7 +67,8 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayFrameEvent){ EXPECT_TRUE(SilKit::Util::ItemsAreEqual(in.frame.payload, out.frame.payload)); } -TEST(Test_FlexraySerdes, SimFlexray_FlexrayFrameTransmitEvent) { +TEST(Test_FlexraySerdes, SimFlexray_FlexrayFrameTransmitEvent) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -90,8 +92,8 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayFrameTransmitEvent) { std::string message{"Hello acknowledgement sent!"}; in.frame.payload = std::vector{message.begin(), message.end()}; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.timestamp, out.timestamp); EXPECT_EQ(in.txBufferIndex, out.txBufferIndex); @@ -106,7 +108,8 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayFrameTransmitEvent) { EXPECT_TRUE(SilKit::Util::ItemsAreEqual(in.frame.payload, out.frame.payload)); } -TEST(Test_FlexraySerdes, SimFlexray_FlexraySymbolEvent) { +TEST(Test_FlexraySerdes, SimFlexray_FlexraySymbolEvent) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -117,15 +120,16 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexraySymbolEvent) { in.channel = FlexrayChannel::B; in.pattern = FlexraySymbolPattern::Wus; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.timestamp, out.timestamp); EXPECT_EQ(in.channel, out.channel); EXPECT_EQ(in.pattern, out.pattern); } -TEST(Test_FlexraySerdes, SimFlexray_FlexraySymbolTransmitEvent) { +TEST(Test_FlexraySerdes, SimFlexray_FlexraySymbolTransmitEvent) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -136,15 +140,16 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexraySymbolTransmitEvent) { in.channel = FlexrayChannel::A; in.pattern = FlexraySymbolPattern::Wudop; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.timestamp, out.timestamp); EXPECT_EQ(in.channel, out.channel); EXPECT_EQ(in.pattern, out.pattern); } -TEST(Test_FlexraySerdes, SimFlexray_FlexrayCycleStartEvent) { +TEST(Test_FlexraySerdes, SimFlexray_FlexrayCycleStartEvent) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -154,14 +159,15 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayCycleStartEvent) { in.timestamp = 1ns; in.cycleCounter = 32; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.timestamp, out.timestamp); EXPECT_EQ(in.cycleCounter, out.cycleCounter); } -TEST(Test_FlexraySerdes, SimFlexray_FlexrayHostCommand) { +TEST(Test_FlexraySerdes, SimFlexray_FlexrayHostCommand) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -170,13 +176,14 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayHostCommand) { in.command = FlexrayChiCommand::DEFERRED_HALT; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.command, out.command); } -TEST(Test_FlexraySerdes, SimFlexray_FlexrayControllerConfig) { +TEST(Test_FlexraySerdes, SimFlexray_FlexrayControllerConfig) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -239,8 +246,8 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayControllerConfig) { in.bufferConfigs = std::vector{conf1}; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.clusterParams.gColdstartAttempts, out.clusterParams.gColdstartAttempts); EXPECT_EQ(in.clusterParams.gCycleCountMax, out.clusterParams.gCycleCountMax); @@ -301,7 +308,8 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayControllerConfig) { } } -TEST(Test_FlexraySerdes, SimFlexray_FlexrayTxBufferConfigUpdate) { +TEST(Test_FlexraySerdes, SimFlexray_FlexrayTxBufferConfigUpdate) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -317,14 +325,15 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayTxBufferConfigUpdate) { in.txBufferConfig.slotId = 7; in.txBufferConfig.transmissionMode = FlexrayTransmissionMode::Continuous; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.txBufferIndex, out.txBufferIndex); EXPECT_EQ(in.txBufferConfig, out.txBufferConfig); } -TEST(Test_FlexraySerdes, SimFlexray_FlexrayTxBufferUpdate) { +TEST(Test_FlexraySerdes, SimFlexray_FlexrayTxBufferUpdate) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -335,15 +344,16 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayTxBufferUpdate) { in.payloadDataValid = true; in.payload = std::vector{1, 2, 3}; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.txBufferIndex, out.txBufferIndex); EXPECT_EQ(in.payloadDataValid, out.payloadDataValid); EXPECT_TRUE(SilKit::Util::ItemsAreEqual(in.payload, out.payload)); } -TEST(Test_FlexraySerdes, SimFlexray_FlexrayPocStatusEvent) { +TEST(Test_FlexraySerdes, SimFlexray_FlexrayPocStatusEvent) +{ using namespace SilKit::Services::Flexray; SilKit::Core::MessageBuffer buffer; @@ -361,8 +371,8 @@ TEST(Test_FlexraySerdes, SimFlexray_FlexrayPocStatusEvent) { in.coldstartNoise = true; in.wakeupStatus = FlexrayWakeupStatusType::ReceivedHeader; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.timestamp, out.timestamp); EXPECT_EQ(in.state, out.state); diff --git a/SilKit/source/services/flexray/Test_Validation.cpp b/SilKit/source/services/flexray/Test_Validation.cpp index c69849389..c91ceaca8 100644 --- a/SilKit/source/services/flexray/Test_Validation.cpp +++ b/SilKit/source/services/flexray/Test_Validation.cpp @@ -72,7 +72,7 @@ TEST(Test_Validation, valid_cluster_params_lower_boundary_must_not_throw) clusterParams.gNumberOfStaticSlots = 2; clusterParams.gPayloadLengthStatic = 0; clusterParams.gSyncFrameIDCountMax = 2; - + EXPECT_NO_THROW(Validate(clusterParams)); } @@ -99,7 +99,7 @@ TEST(Test_Validation, valid_cluster_params_upper_boundary_must_not_throw) clusterParams.gNumberOfStaticSlots = 1023; clusterParams.gPayloadLengthStatic = 127; clusterParams.gSyncFrameIDCountMax = 15; - + EXPECT_NO_THROW(Validate(clusterParams)); } diff --git a/SilKit/source/services/flexray/Validation.cpp b/SilKit/source/services/flexray/Validation.cpp index 6e4a43152..74466a20c 100644 --- a/SilKit/source/services/flexray/Validation.cpp +++ b/SilKit/source/services/flexray/Validation.cpp @@ -34,7 +34,7 @@ void Validate(const FlexrayClusterParameters& clusterParameters) if (clusterParameters.gCycleCountMax % 2 != 1) throw SilKit::ConfigurationError{"gCycleCountMax must be an odd value"}; - + if (clusterParameters.gCycleCountMax < 7 || clusterParameters.gCycleCountMax > 63) throw SilKit::ConfigurationError{"gCycleCountMax must be in range 7, 9, ..., 63"}; @@ -77,7 +77,8 @@ void Validate(const FlexrayClusterParameters& clusterParameters) if (clusterParameters.gMaxWithoutClockCorrectionFatal < 1 || clusterParameters.gMaxWithoutClockCorrectionFatal > 15) throw SilKit::ConfigurationError{"gMaxWithoutClockCorrectionFatal must be in range 1 - 15"}; - if (clusterParameters.gMaxWithoutClockCorrectionPassive < 1 || clusterParameters.gMaxWithoutClockCorrectionPassive > 15) + if (clusterParameters.gMaxWithoutClockCorrectionPassive < 1 + || clusterParameters.gMaxWithoutClockCorrectionPassive > 15) throw SilKit::ConfigurationError{"gMaxWithoutClockCorrectionPassive must be in range 1 - 15"}; if (clusterParameters.gNumberOfMiniSlots > 7988) diff --git a/SilKit/source/services/lin/ILinControllerExtensions.hpp b/SilKit/source/services/lin/ILinControllerExtensions.hpp index fb0d06243..a32f2d27f 100644 --- a/SilKit/source/services/lin/ILinControllerExtensions.hpp +++ b/SilKit/source/services/lin/ILinControllerExtensions.hpp @@ -33,8 +33,8 @@ class ILinControllerExtensions public: virtual ~ILinControllerExtensions() = default; - virtual auto AddLinSlaveConfigurationHandler(SilKit::Experimental::Services::Lin::LinSlaveConfigurationHandler handler) - -> SilKit::Util::HandlerId = 0; + virtual auto AddLinSlaveConfigurationHandler( + SilKit::Experimental::Services::Lin::LinSlaveConfigurationHandler handler) -> SilKit::Util::HandlerId = 0; virtual void RemoveLinSlaveConfigurationHandler(SilKit::Util::HandlerId handlerId) = 0; @@ -42,7 +42,8 @@ class ILinControllerExtensions virtual void InitDynamic(const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& dynamicConfig) = 0; - virtual auto AddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) -> SilKit::Util::HandlerId = 0; + virtual auto AddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) + -> SilKit::Util::HandlerId = 0; virtual void RemoveFrameHeaderHandler(SilKit::Util::HandlerId handlerId) = 0; diff --git a/SilKit/source/services/lin/IMsgForLinSimulator.hpp b/SilKit/source/services/lin/IMsgForLinSimulator.hpp index b57f75e6d..d34c391df 100644 --- a/SilKit/source/services/lin/IMsgForLinSimulator.hpp +++ b/SilKit/source/services/lin/IMsgForLinSimulator.hpp @@ -24,8 +24,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "IReceiver.hpp" #include "ISender.hpp" #include "IServiceEndpoint.hpp" +#include "WireLinMessages.hpp" -#include "silkit/services/lin/fwd_decl.hpp" +#include "silkit/services/lin/LinDatatypes.hpp" namespace SilKit { namespace Services { @@ -36,20 +37,12 @@ namespace Lin { * Used by the Participant, implemented by the LinSimulator */ class IMsgForLinSimulator - : public Core::IReceiver + : public Core::IReceiver , public Core::ISender { public: virtual ~IMsgForLinSimulator() = default; - - /* NB: there is no setter or getter for an EndpointAddress of the - * simulator, since the simulator manages multiple controllers - * with different endpoints. I.e., the simulator is aware of all - * the individual endpointIds. - */ - //! \brief Setter and getter for the ParticipantID associated with this LIN simulator - virtual void SetParticipantId(SilKit::Core::ParticipantId participantId) = 0; - virtual auto GetParticipantId() const -> SilKit::Core::ParticipantId = 0; }; } // namespace Lin diff --git a/SilKit/source/services/lin/LinController.cpp b/SilKit/source/services/lin/LinController.cpp old mode 100755 new mode 100644 index 9e0196b09..ce9431b90 --- a/SilKit/source/services/lin/LinController.cpp +++ b/SilKit/source/services/lin/LinController.cpp @@ -32,8 +32,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ILogger.hpp" #include "WireLinMessages.hpp" -namespace -{ +namespace { using namespace SilKit::Services::Lin; auto to_wire(const LinControllerConfig& config) -> WireLinControllerConfig { @@ -55,13 +54,13 @@ auto to_wire(const SilKit::Experimental::Services::Lin::LinControllerDynamicConf return result; } -} +} // namespace namespace SilKit { namespace Services { namespace Lin { LinController::LinController(Core::IParticipantInternal* participant, SilKit::Config::LinController config, - Services::Orchestration::ITimeProvider* timeProvider) + Services::Orchestration::ITimeProvider* timeProvider) : _participant{participant} , _config{config} , _logger{participant->GetLogger()} @@ -79,28 +78,36 @@ void LinController::RegisterServiceDiscovery() { _participant->GetServiceDiscovery()->RegisterServiceDiscoveryHandler( [this](Core::Discovery::ServiceDiscoveryEvent::Type discoveryType, - const Core::ServiceDescriptor& remoteServiceDescriptor) { - // check if discovered service is a network simulator (if none is known) - if (_simulationBehavior.IsTrivial()) + const Core::ServiceDescriptor& remoteServiceDescriptor) { + // check if discovered service is a network simulator (if none is known) + if (_simulationBehavior.IsTrivial()) + { + // check if received descriptor has a matching simulated link + if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated + && IsRelevantNetwork(remoteServiceDescriptor)) { - // check if received descriptor has a matching simulated link - if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated - && IsRelevantNetwork(remoteServiceDescriptor)) - { - SetDetailedBehavior(remoteServiceDescriptor); - - } + Logging::Info(_logger, + "Controller '{}' is using the simulated network '{}' and will route all messages to " + "the network simulator '{}'", + _config.name, remoteServiceDescriptor.GetNetworkName(), + remoteServiceDescriptor.GetParticipantName()); + SetDetailedBehavior(remoteServiceDescriptor); } - else + } + else + { + if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved + && IsRelevantNetwork(remoteServiceDescriptor)) + { - if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved - && IsRelevantNetwork(remoteServiceDescriptor)) - - { - SetTrivialBehavior(); - } + Logging::Warn(_logger, + "The network simulator for controller '{}' left the simulation. The controller is no " + "longer simulated.", + _config.name); + SetTrivialBehavior(); } - }); + } + }); } void LinController::SetDetailedBehavior(const Core::ServiceDescriptor& remoteServiceDescriptor) @@ -150,8 +157,7 @@ void LinController::ThrowIfNotMaster(const std::string& callingMethodName) const { if (_controllerMode != LinControllerMode::Master) { - std::string errorMsg = callingMethodName - + " must only be called in master mode!"; + std::string errorMsg = callingMethodName + " must only be called in master mode!"; _logger->Error(errorMsg); throw SilKitError{errorMsg}; } @@ -161,8 +167,7 @@ void LinController::ThrowIfDynamic(const std::string& callingMethodName) const { if (_useDynamicResponse) { - std::string errorMsg = callingMethodName - + " can not be called if the node was initialized using InitDynamic!"; + std::string errorMsg = callingMethodName + " can not be called if the node was initialized using InitDynamic!"; _logger->Error(errorMsg); throw SilKitError{errorMsg}; } @@ -172,8 +177,7 @@ void LinController::ThrowIfNotDynamic(const std::string& callingMethodName) cons { if (_useDynamicResponse) { - std::string errorMsg = callingMethodName - + " can only be called if the node was initialized using InitDynamic!"; + std::string errorMsg = callingMethodName + " can only be called if the node was initialized using InitDynamic!"; _logger->Error(errorMsg); throw SilKitError{errorMsg}; } @@ -264,8 +268,9 @@ void LinController::WarnOnResponseModeReconfiguration(LinId id, LinFrameResponse void LinController::WarnOnUnconfiguredSlaveResponse(LinId id) const { - std::string errorMsg = - fmt::format("No slave has configured a response for ID={}. Use Init() or SetFrameResponse() on the slave node to configure responses.", id); + std::string errorMsg = fmt::format("No slave has configured a response for ID={}. Use Init() or SetFrameResponse() " + "on the slave node to configure responses.", + id); _logger->Warn(errorMsg); } @@ -279,8 +284,7 @@ void LinController::WarnOnSendFrameSlaveResponseWithMasterTx(LinId id) const void LinController::ThrowOnSendAttemptWithUndefinedChecksum(const LinFrame& frame) const { std::string errorMsg = - fmt::format("LinFrame with ID {} has an undefined checksum model.", - static_cast(frame.id)); + fmt::format("LinFrame with ID {} has an undefined checksum model.", static_cast(frame.id)); _logger->Error(errorMsg); throw SilKit::StateError{errorMsg}; } @@ -288,8 +292,7 @@ void LinController::ThrowOnSendAttemptWithUndefinedChecksum(const LinFrame& fram void LinController::ThrowOnSendAttemptWithUndefinedDataLength(const LinFrame& frame) const { std::string errorMsg = - fmt::format("LinFrame with ID {} has an undefined data length.", - static_cast(frame.id)); + fmt::format("LinFrame with ID {} has an undefined data length.", static_cast(frame.id)); _logger->Error(errorMsg); throw SilKit::StateError{errorMsg}; } @@ -433,8 +436,7 @@ void LinController::SendFrameInternal(LinFrame frame, LinFrameResponseType respo } else if (responseType == LinFrameResponseType::SlaveToSlave) { - CallLinFrameStatusEventHandler( - LinFrameStatusEvent{_timeProvider->Now(), frame, LinFrameStatus::LIN_TX_OK}); + CallLinFrameStatusEventHandler(LinFrameStatusEvent{_timeProvider->Now(), frame, LinFrameStatus::LIN_TX_OK}); } } @@ -451,8 +453,8 @@ void LinController::SendFrame(LinFrame frame, LinFrameResponseType responseType) if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Send)) { - Logging::Debug(_logger, _logOnce, - "LinController: Ignoring SendFrame API call due to Replay config on {}", _config.name); + Logging::Debug(_logger, _logOnce, "LinController: Ignoring SendFrame API call due to Replay config on {}", + _config.name); return; } @@ -466,7 +468,7 @@ void LinController::SendFrameHeader(LinId linId) // Detailed: Send LinSendFrameHeaderRequest to BusSim // Trivial: Good case (numResponses == 1): Distribute LinSendFrameHeaderRequest, the receiving Tx-Node will generate the LinTransmission. - // Error case: Generate the LinTransmission and trigger a FrameStatusUpdate with + // Error case: Generate the LinTransmission and trigger a FrameStatusUpdate with // LIN_RX_NO_RESPONSE (numResponses == 0) or LIN_RX_ERROR (numResponses > 1). SendMsg(LinSendFrameHeaderRequest{_timeProvider->Now(), linId}); } @@ -511,7 +513,7 @@ void LinController::SetFrameResponse(LinFrameResponse response) if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Send)) { Logging::Debug(_logger, _logOnce, - "LinController: Ignoring SetFrameResponse API call due to Replay config on {}", _config.name); + "LinController: Ignoring SetFrameResponse API call due to Replay config on {}", _config.name); return; } @@ -536,8 +538,8 @@ void LinController::GoToSleep() if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Send)) { - Logging::Debug(_logger, _logOnce, - "LinController: Ignoring GoToSleep API call due to Replay config on {}", _config.name); + Logging::Debug(_logger, _logOnce, "LinController: Ignoring GoToSleep API call due to Replay config on {}", + _config.name); return; } @@ -655,7 +657,8 @@ void LinController::HandleResponsesUpdate(const IServiceEndpoint* from, // Node bookkeeping //------------------------ -void LinController::LinNode::UpdateResponses(std::vector responsesToUpdate, Services::Logging::ILogger* logger) +void LinController::LinNode::UpdateResponses(std::vector responsesToUpdate, + Services::Logging::ILogger* logger) { for (auto&& response : responsesToUpdate) { @@ -666,7 +669,7 @@ void LinController::LinNode::UpdateResponses(std::vector respo continue; } responses[linId] = std::move(response); - } + } } void LinController::LinNode::UpdateTxBuffer(LinId linId, std::array data, @@ -687,10 +690,9 @@ auto LinController::GetThisLinNode() -> LinNode& auto LinController::GetLinNode(Core::EndpointAddress addr) -> LinNode& { - auto iter = std::lower_bound(_linNodes.begin(), _linNodes.end(), addr, - [](const LinNode& lhs, const Core::EndpointAddress& address) { - return lhs.address < address; - }); + auto iter = std::lower_bound( + _linNodes.begin(), _linNodes.end(), addr, + [](const LinNode& lhs, const Core::EndpointAddress& address) { return lhs.address < address; }); if (iter == _linNodes.end() || iter->address != addr) { LinNode node; @@ -783,7 +785,7 @@ void LinController::ReceiveMsg(const IServiceEndpoint* from, const LinTransmissi if (frame.id >= _maxLinId) { WarnOnReceptionWithInvalidLinId(frame.id, from->GetServiceDescriptor().GetParticipantName(), - from->GetServiceDescriptor().GetServiceName()); + from->GetServiceDescriptor().GetServiceName()); return; } @@ -809,7 +811,6 @@ void LinController::ReceiveMsg(const IServiceEndpoint* from, const LinTransmissi CallHandlers(LinGoToSleepEvent{msg.timestamp}); } } - } void LinController::ReceiveMsg(const IServiceEndpoint* from, const LinWakeupPulse& msg) @@ -886,7 +887,8 @@ HandlerId LinController::AddWakeupHandler(WakeupHandler handler) return AddHandler(std::move(handler)); } -auto LinController::AddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler ) -> HandlerId +auto LinController::AddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) + -> HandlerId { return AddHandler(std::move(handler)); } @@ -913,7 +915,7 @@ HandlerId LinController::AddLinSlaveConfigurationHandler( auto handlerId = AddHandler(std::move(handler)); // Trigger handler if a LinSlaveConfigurations was received before adding a handler - // No need to cache the LinSlaveConfigs (just the reception time), + // No need to cache the LinSlaveConfigs (just the reception time), // as the user has to actively call GetSlaveConfiguration in the callback if (_triggerLinSlaveConfigurationHandlers) { @@ -957,12 +959,11 @@ void LinController::CallHandlers(const MsgT& msg) void LinController::ReplayMessage(const IReplayMessage* replayMessage) { - if (!_replayActive) { return; } - + if (_controllerMode != LinControllerMode::Master) { Logging::Debug(_logger, "ReplayMessage: skipping, because controller mode is {}", _controllerMode); @@ -972,8 +973,7 @@ void LinController::ReplayMessage(const IReplayMessage* replayMessage) // response that is going to be generated by a slave. auto&& frame = dynamic_cast(*replayMessage); - const auto isSleepFrame = (frame.id == GoToSleepFrame().id - && frame.data == GoToSleepFrame().data); + const auto isSleepFrame = (frame.id == GoToSleepFrame().id && frame.data == GoToSleepFrame().data); const auto isReceive = replayMessage->GetDirection() == TransmitDirection::RX; LinTransmission tm{}; diff --git a/SilKit/source/services/lin/LinController.hpp b/SilKit/source/services/lin/LinController.hpp old mode 100755 new mode 100644 index eda5d5e11..22ce755e8 --- a/SilKit/source/services/lin/LinController.hpp +++ b/SilKit/source/services/lin/LinController.hpp @@ -62,7 +62,7 @@ class LinController LinController(const LinController&) = delete; LinController(LinController&&) = delete; LinController(Core::IParticipantInternal* participant, Config::LinController config, - Services::Orchestration::ITimeProvider* timeProvider); + Services::Orchestration::ITimeProvider* timeProvider); public: // ---------------------------------------- @@ -76,9 +76,10 @@ class LinController // // ILinController void Init(LinControllerConfig config) override; - void InitDynamic(const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& config) override; // Experimental + void InitDynamic( + const SilKit::Experimental::Services::Lin::LinControllerDynamicConfig& config) override; // Experimental - auto Status() const noexcept->LinControllerStatus override; + auto Status() const noexcept -> LinControllerStatus override; void SendFrame(LinFrame frame, LinFrameResponseType responseType) override; void SendFrameHeader(LinId linId) override; @@ -98,7 +99,8 @@ class LinController Experimental::Services::Lin::LinSlaveConfigurationHandler handler) override; // Exprimental void RemoveLinSlaveConfigurationHandler(HandlerId handlerId) override; // Exprimental - auto AddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) -> HandlerId override; // Experimental + auto AddFrameHeaderHandler(SilKit::Experimental::Services::Lin::LinFrameHeaderHandler handler) + -> HandlerId override; // Experimental void RemoveFrameHeaderHandler(HandlerId handlerId) override; // Experimental HandlerId AddFrameStatusHandler(FrameStatusHandler handler) override; @@ -146,7 +148,6 @@ class LinController void UpdateResponses(std::vector responsesToUpdate, Services::Logging::ILogger* logger); void UpdateTxBuffer(LinId linId, std::array data, Services::Logging::ILogger* logger); - }; auto GetResponse(LinId id) -> std::pair; auto GetThisLinNode() -> LinNode&; @@ -168,6 +169,7 @@ class LinController // for ITraceMessageSource inline auto GetTracer() -> Tracer*; + private: // ---------------------------------------- // private methods @@ -208,7 +210,7 @@ class LinController void WarnOnResponseModeReconfiguration(LinId id, LinFrameResponseMode currentResponseMode) const; void WarnOnUnconfiguredSlaveResponse(LinId id) const; void WarnOnSendFrameSlaveResponseWithMasterTx(LinId id) const; - + void UpdateLinIdsRespondedBySlaves(const std::vector& responsesUpdate); void HandleResponsesUpdate(const IServiceEndpoint* from, const std::vector& responsesToUpdate); void UpdateFrameResponse(LinFrameResponse response); @@ -229,19 +231,16 @@ class LinController SimBehavior _simulationBehavior; ::SilKit::Core::ServiceDescriptor _serviceDescriptor; - LinControllerMode _controllerMode{LinControllerMode::Inactive}; + LinControllerMode _controllerMode{LinControllerMode::Inactive}; LinControllerStatus _controllerStatus{LinControllerStatus::Unknown}; template using CallbacksT = Util::SynchronizedHandlers>; - std::tuple< - CallbacksT, - CallbacksT, - CallbacksT, - CallbacksT, - CallbacksT - > _callbacks; + std::tuple, CallbacksT, CallbacksT, + CallbacksT, + CallbacksT> + _callbacks; Services::Orchestration::ITimeProvider* _timeProvider{nullptr}; bool _replayActive{false}; diff --git a/SilKit/source/services/lin/LinSerdes.cpp b/SilKit/source/services/lin/LinSerdes.cpp index 91db0c1dd..3a7a03915 100644 --- a/SilKit/source/services/lin/LinSerdes.cpp +++ b/SilKit/source/services/lin/LinSerdes.cpp @@ -28,116 +28,78 @@ namespace Lin { SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const LinFrame& frame) { - buffer - << frame.id - << frame.checksumModel - << frame.dataLength - << frame.data; + buffer << frame.id << frame.checksumModel << frame.dataLength << frame.data; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, LinFrame& frame) { - buffer - >> frame.id - >> frame.checksumModel - >> frame.dataLength - >> frame.data; + buffer >> frame.id >> frame.checksumModel >> frame.dataLength >> frame.data; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const LinSendFrameRequest& frame) { - buffer - << frame.frame - << frame.responseType; + buffer << frame.frame << frame.responseType; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, LinSendFrameRequest& frame) { - buffer - >> frame.frame - >> frame.responseType; + buffer >> frame.frame >> frame.responseType; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const LinSendFrameHeaderRequest& header) { - buffer - << header.timestamp - << header.id; + buffer << header.timestamp << header.id; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, LinSendFrameHeaderRequest& header) { - buffer - >> header.timestamp - >> header.id; + buffer >> header.timestamp >> header.id; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const LinTransmission& transmission) { - buffer - << transmission.timestamp - << transmission.frame - << transmission.status; + buffer << transmission.timestamp << transmission.frame << transmission.status; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, LinTransmission& transmission) { - buffer - >> transmission.timestamp - >> transmission.frame - >> transmission.status; + buffer >> transmission.timestamp >> transmission.frame >> transmission.status; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const LinWakeupPulse& pulse) { - buffer - << pulse.timestamp - << pulse.direction; + buffer << pulse.timestamp << pulse.direction; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, LinWakeupPulse& pulse) { - buffer - >> pulse.timestamp - >> pulse.direction; + buffer >> pulse.timestamp >> pulse.direction; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const LinFrameResponse& response) { - buffer - << response.frame - << response.responseMode; + buffer << response.frame << response.responseMode; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, LinFrameResponse& response) { - buffer - >> response.frame - >> response.responseMode; + buffer >> response.frame >> response.responseMode; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const WireLinControllerConfig& config) { - buffer - << config.controllerMode - << config.baudRate - << config.frameResponses - << config.simulationMode - ; + buffer << config.controllerMode << config.baudRate << config.frameResponses << config.simulationMode; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, WireLinControllerConfig& config) { - buffer - >> config.controllerMode - >> config.baudRate - >> config.frameResponses; + buffer >> config.controllerMode >> config.baudRate >> config.frameResponses; if (buffer.RemainingBytesLeft() >= sizeof(WireLinControllerConfig::SimulationMode)) { buffer >> config.simulationMode; @@ -147,29 +109,23 @@ SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, Wir SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const LinControllerStatusUpdate& msg) { - buffer - << msg.timestamp - << msg.status; + buffer << msg.timestamp << msg.status; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, LinControllerStatusUpdate& msg) { - buffer - >> msg.timestamp - >> msg.status; + buffer >> msg.timestamp >> msg.status; return buffer; } SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const LinFrameResponseUpdate& update) { - buffer - << update.frameResponses; + buffer << update.frameResponses; return buffer; } SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, LinFrameResponseUpdate& update) { - buffer - >> update.frameResponses; + buffer >> update.frameResponses; return buffer; } diff --git a/SilKit/source/services/lin/LinTestUtils.hpp b/SilKit/source/services/lin/LinTestUtils.hpp old mode 100755 new mode 100644 index cb302492f..3fde544c2 --- a/SilKit/source/services/lin/LinTestUtils.hpp +++ b/SilKit/source/services/lin/LinTestUtils.hpp @@ -54,8 +54,8 @@ inline auto MakeControllerConfig(LinControllerMode mode) -> LinControllerConfig return config; } -inline auto MakeFrame(LinId linId, LinChecksumModel checksumModel = LinChecksumModel::Unknown, - uint8_t dataLength = 0, std::array data = std::array{}) -> LinFrame +inline auto MakeFrame(LinId linId, LinChecksumModel checksumModel = LinChecksumModel::Unknown, uint8_t dataLength = 0, + std::array data = std::array{}) -> LinFrame { LinFrame frame; frame.id = linId; @@ -89,8 +89,8 @@ inline auto ATransmissionWith(LinFrameStatus status) -> testing::Matcher testing::Matcher +inline auto ATransmissionWith(LinFrameStatus status, + std::chrono::nanoseconds timestamp) -> testing::Matcher { using namespace testing; return AllOf(Field(&LinTransmission::status, status), Field(&LinTransmission::timestamp, timestamp)); @@ -102,8 +102,8 @@ inline auto ATransmissionWith(LinFrame frame, LinFrameStatus status) -> testing: return AllOf(Field(&LinTransmission::frame, frame), Field(&LinTransmission::status, status)); } -inline auto ATransmissionWith(LinFrame frame, LinFrameStatus status, std::chrono::nanoseconds timestamp) - -> testing::Matcher +inline auto ATransmissionWith(LinFrame frame, LinFrameStatus status, + std::chrono::nanoseconds timestamp) -> testing::Matcher { using namespace testing; return AllOf(Field(&LinTransmission::frame, frame), Field(&LinTransmission::status, status), @@ -125,9 +125,9 @@ struct Callbacks MOCK_METHOD1(LinSlaveConfigurationHandler, void(ILinController*)); }; -inline auto ToWire(LinControllerConfig config, WireLinControllerConfig::SimulationMode simulationMode = - WireLinControllerConfig::SimulationMode::Default) - -> WireLinControllerConfig +inline auto ToWire(LinControllerConfig config, + WireLinControllerConfig::SimulationMode simulationMode = + WireLinControllerConfig::SimulationMode::Default) -> WireLinControllerConfig { WireLinControllerConfig result{}; result.baudRate = config.baudRate; diff --git a/SilKit/source/services/lin/SimBehavior.cpp b/SilKit/source/services/lin/SimBehavior.cpp index 13a6106d4..068745bd8 100644 --- a/SilKit/source/services/lin/SimBehavior.cpp +++ b/SilKit/source/services/lin/SimBehavior.cpp @@ -29,7 +29,7 @@ namespace Lin { class LinController; SimBehavior::SimBehavior(Core::IParticipantInternal* participant, LinController* linController, - Services::Orchestration::ITimeProvider* timeProvider) + Services::Orchestration::ITimeProvider* timeProvider) : _trivial{participant, linController, timeProvider} , _detailed{participant, linController, linController->GetServiceDescriptor()} { diff --git a/SilKit/source/services/lin/SimBehavior.hpp b/SilKit/source/services/lin/SimBehavior.hpp index 9e85e5c81..1a82fbf56 100644 --- a/SilKit/source/services/lin/SimBehavior.hpp +++ b/SilKit/source/services/lin/SimBehavior.hpp @@ -42,7 +42,7 @@ class SimBehavior : public ISimBehavior { public: SimBehavior(Core::IParticipantInternal* participant, LinController* linController, - Services::Orchestration::ITimeProvider* timeProvider); + Services::Orchestration::ITimeProvider* timeProvider); auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; diff --git a/SilKit/source/services/lin/SimBehaviorDetailed.cpp b/SilKit/source/services/lin/SimBehaviorDetailed.cpp index ba68033ff..102f76bcc 100644 --- a/SilKit/source/services/lin/SimBehaviorDetailed.cpp +++ b/SilKit/source/services/lin/SimBehaviorDetailed.cpp @@ -27,7 +27,7 @@ namespace Services { namespace Lin { SimBehaviorDetailed::SimBehaviorDetailed(Core::IParticipantInternal* participant, LinController* linController, - const Core::ServiceDescriptor& serviceDescriptor) + const Core::ServiceDescriptor& serviceDescriptor) : _participant{participant} , _parentController{linController} , _parentServiceEndpoint{dynamic_cast(linController)} @@ -105,8 +105,8 @@ void SimBehaviorDetailed::Wakeup() _parentController->WakeupInternal(); } -auto SimBehaviorDetailed::CalcFrameStatus(const LinTransmission& linTransmission, bool isGoToSleepFrame) - -> LinFrameStatus +auto SimBehaviorDetailed::CalcFrameStatus(const LinTransmission& linTransmission, + bool isGoToSleepFrame) -> LinFrameStatus { // dynamic controllers report every transmission as it was received if (_parentController->GetThisLinNode().simulationMode == WireLinControllerConfig::SimulationMode::Dynamic) @@ -128,7 +128,7 @@ auto SimBehaviorDetailed::CalcFrameStatus(const LinTransmission& linTransmission return linTransmission.status; } -auto SimBehaviorDetailed::AllowReception(const Core::IServiceEndpoint* from) const -> bool +auto SimBehaviorDetailed::AllowReception(const Core::IServiceEndpoint* from) const -> bool { // If simulated, only allow reception from NetSim. // NetSim internally sets the ServiceId of this controller and sends messages with it, diff --git a/SilKit/source/services/lin/SimBehaviorDetailed.hpp b/SilKit/source/services/lin/SimBehaviorDetailed.hpp index 6a9088c0d..f793902ea 100644 --- a/SilKit/source/services/lin/SimBehaviorDetailed.hpp +++ b/SilKit/source/services/lin/SimBehaviorDetailed.hpp @@ -36,7 +36,7 @@ class SimBehaviorDetailed : public ISimBehavior { public: SimBehaviorDetailed(Core::IParticipantInternal* participant, LinController* linController, - const Core::ServiceDescriptor& serviceDescriptor); + const Core::ServiceDescriptor& serviceDescriptor); auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; diff --git a/SilKit/source/services/lin/SimBehaviorTrivial.cpp b/SilKit/source/services/lin/SimBehaviorTrivial.cpp old mode 100755 new mode 100644 index 1d9cf22a0..8ad52bc4a --- a/SilKit/source/services/lin/SimBehaviorTrivial.cpp +++ b/SilKit/source/services/lin/SimBehaviorTrivial.cpp @@ -32,11 +32,16 @@ inline auto ToTxFrameStatus(LinFrameStatus status) -> LinFrameStatus { switch (status) { - case LinFrameStatus::LIN_RX_BUSY: return LinFrameStatus::LIN_TX_BUSY; - case LinFrameStatus::LIN_RX_ERROR: return LinFrameStatus::LIN_TX_ERROR; - case LinFrameStatus::LIN_RX_NO_RESPONSE: return LinFrameStatus::LIN_RX_NO_RESPONSE; - case LinFrameStatus::LIN_RX_OK: return LinFrameStatus::LIN_TX_OK; - default: return status; + case LinFrameStatus::LIN_RX_BUSY: + return LinFrameStatus::LIN_TX_BUSY; + case LinFrameStatus::LIN_RX_ERROR: + return LinFrameStatus::LIN_TX_ERROR; + case LinFrameStatus::LIN_RX_NO_RESPONSE: + return LinFrameStatus::LIN_RX_NO_RESPONSE; + case LinFrameStatus::LIN_RX_OK: + return LinFrameStatus::LIN_TX_OK; + default: + return status; } } @@ -47,12 +52,14 @@ inline auto ToTracingDir(LinFrameStatus status) -> SilKit::Services::TransmitDir case LinFrameStatus::LIN_RX_ERROR: //[[fallthrough]] case LinFrameStatus::LIN_RX_BUSY: //[[fallthrough]] case LinFrameStatus::LIN_RX_NO_RESPONSE: //[[fallthrough]] - case LinFrameStatus::LIN_RX_OK: return SilKit::Services::TransmitDirection::RX; + case LinFrameStatus::LIN_RX_OK: + return SilKit::Services::TransmitDirection::RX; case LinFrameStatus::LIN_TX_ERROR: //[[fallthrough]] case LinFrameStatus::LIN_TX_BUSY: //[[fallthrough]] case LinFrameStatus::LIN_TX_HEADER_ERROR: //[[fallthrough]] - case LinFrameStatus::LIN_TX_OK: return SilKit::Services::TransmitDirection::TX; + case LinFrameStatus::LIN_TX_OK: + return SilKit::Services::TransmitDirection::TX; default: //if invalid status given, failsafe to send. @@ -79,15 +86,15 @@ void SimBehaviorTrivial::ReceiveMsg(const MsgT& msg) receivingController->ReceiveMsg(_parentServiceEndpoint, msg); } -auto SimBehaviorTrivial::AllowReception(const Core::IServiceEndpoint* /*from*/) const -> bool -{ - return true; +auto SimBehaviorTrivial::AllowReception(const Core::IServiceEndpoint* /*from*/) const -> bool +{ + return true; } template void SimBehaviorTrivial::SendMsgImpl(MsgT&& msg) { - _participant->SendMsg(_parentServiceEndpoint, std::forward(msg)); + _participant->SendMsg(_parentServiceEndpoint, std::forward(msg)); } void SimBehaviorTrivial::SendMsg(LinSendFrameRequest&& msg) @@ -208,8 +215,8 @@ void SimBehaviorTrivial::UpdateTxBuffer(const LinFrame& /*frame*/) // NOP } -auto SimBehaviorTrivial::CalcFrameStatus(const LinTransmission& linTransmission, bool /*isGoToSleepFrame*/) - -> LinFrameStatus +auto SimBehaviorTrivial::CalcFrameStatus(const LinTransmission& linTransmission, + bool /*isGoToSleepFrame*/) -> LinFrameStatus { // dynamic controllers report every transmission as it was received if (_parentController->GetThisLinNode().simulationMode == WireLinControllerConfig::SimulationMode::Dynamic) @@ -222,37 +229,37 @@ auto SimBehaviorTrivial::CalcFrameStatus(const LinTransmission& linTransmission, const auto response = thisLinNode.responses[linTransmission.frame.id]; switch (response.responseMode) { - case LinFrameResponseMode::Unused: - { - // Return NOT_OK to not trigger the reception callback - return LinFrameStatus::NOT_OK; - } - case LinFrameResponseMode::Rx: + case LinFrameResponseMode::Unused: + { + // Return NOT_OK to not trigger the reception callback + return LinFrameStatus::NOT_OK; + } + case LinFrameResponseMode::Rx: + { + // Skip check if receiving with unknown DataLength + const bool checkDataLength = (response.frame.dataLength != LinDataLengthUnknown); + if (checkDataLength && (response.frame.dataLength != linTransmission.frame.dataLength)) { - // Skip check if receiving with unknown DataLength - const bool checkDataLength = (response.frame.dataLength != LinDataLengthUnknown); - if (checkDataLength && (response.frame.dataLength != linTransmission.frame.dataLength)) - { - _parentController->WarnOnWrongDataLength(linTransmission.frame, response.frame); - return LinFrameStatus::LIN_RX_ERROR; - } - - // Skip check if sending or receiving with unknown CSM - const bool checkChecksumModel = (linTransmission.frame.checksumModel != LinChecksumModel::Unknown) - && (response.frame.checksumModel != LinChecksumModel::Unknown); - if (checkChecksumModel && (response.frame.checksumModel != linTransmission.frame.checksumModel)) - { - _parentController->WarnOnWrongChecksum(linTransmission.frame, response.frame); - return LinFrameStatus::LIN_RX_ERROR; - } - break; + _parentController->WarnOnWrongDataLength(linTransmission.frame, response.frame); + return LinFrameStatus::LIN_RX_ERROR; } - case LinFrameResponseMode::TxUnconditional: + + // Skip check if sending or receiving with unknown CSM + const bool checkChecksumModel = (linTransmission.frame.checksumModel != LinChecksumModel::Unknown) + && (response.frame.checksumModel != LinChecksumModel::Unknown); + if (checkChecksumModel && (response.frame.checksumModel != linTransmission.frame.checksumModel)) { - // Transmissions are always sent with LinFrameStatus::RX_xxx so we have to - // convert the status to a TX_xxx if we sent this frame. - return ToTxFrameStatus(linTransmission.status); + _parentController->WarnOnWrongChecksum(linTransmission.frame, response.frame); + return LinFrameStatus::LIN_RX_ERROR; } + break; + } + case LinFrameResponseMode::TxUnconditional: + { + // Transmissions are always sent with LinFrameStatus::RX_xxx so we have to + // convert the status to a TX_xxx if we sent this frame. + return ToTxFrameStatus(linTransmission.status); + } } return linTransmission.status; } diff --git a/SilKit/source/services/lin/SimBehaviorTrivial.hpp b/SilKit/source/services/lin/SimBehaviorTrivial.hpp index c62aeb4a3..4ae96a975 100644 --- a/SilKit/source/services/lin/SimBehaviorTrivial.hpp +++ b/SilKit/source/services/lin/SimBehaviorTrivial.hpp @@ -36,12 +36,11 @@ class LinController; class SimBehaviorTrivial : public ISimBehavior { public: - SimBehaviorTrivial(Core::IParticipantInternal* participant, LinController* linController, Services::Orchestration::ITimeProvider* timeProvider); auto AllowReception(const Core::IServiceEndpoint* from) const -> bool override; - + void SendMsg(LinSendFrameRequest&& sendFrameRequest) override; void SendMsg(LinTransmission&& transmission) override; void SendMsg(WireLinControllerConfig&& controllerConfig) override; diff --git a/SilKit/source/services/lin/Test_LinControllerConfig.cpp b/SilKit/source/services/lin/Test_LinControllerConfig.cpp index e58993bb1..bc9fae344 100644 --- a/SilKit/source/services/lin/Test_LinControllerConfig.cpp +++ b/SilKit/source/services/lin/Test_LinControllerConfig.cpp @@ -37,7 +37,7 @@ using namespace SilKit::Services::Lin; class Test_LinControllerConfig : public testing::Test { public: - Test_LinControllerConfig(){}; + Test_LinControllerConfig() {}; }; auto PrepareParticipantConfiguration() -> std::shared_ptr @@ -89,4 +89,4 @@ TEST(Test_LinControllerConfig, create_controller_configured_with_network) EXPECT_EQ(serviceDescr.GetNetworkName(), expectedNetworkName); } -} // anonymous namespace +} // anonymous namespace diff --git a/SilKit/source/services/lin/Test_LinControllerDetailedSim.cpp b/SilKit/source/services/lin/Test_LinControllerDetailedSim.cpp index 3e2c7cd7f..5fb04aea0 100644 --- a/SilKit/source/services/lin/Test_LinControllerDetailedSim.cpp +++ b/SilKit/source/services/lin/Test_LinControllerDetailedSim.cpp @@ -62,7 +62,8 @@ class Test_LinControllerDetailedSim : public testing::Test wakeupHandler = [this](ILinController* ctrl, const LinWakeupEvent& /*wakeupEvent*/) { callbacks.WakeupHandler(ctrl); }; - slaveConfigurationHandler = [this](ILinController* ctrl, + slaveConfigurationHandler = + [this](ILinController* ctrl, const SilKit::Experimental::Services::Lin::LinSlaveConfigurationEvent& /*slaveConfigurationEvent*/) { callbacks.LinSlaveConfigurationHandler(ctrl); }; @@ -75,7 +76,7 @@ class Test_LinControllerDetailedSim : public testing::Test } protected: - const ServiceDescriptor addr1_netsim{"P1", "N1", "C1",5}; + const ServiceDescriptor addr1_netsim{"P1", "N1", "C1", 5}; const ServiceDescriptor addr1_proxy{"P2", "N1", "C1", 5}; const ServiceDescriptor addr2_proxy{"P1", "N1", "C2", 9}; @@ -212,8 +213,7 @@ TEST_F(Test_LinControllerDetailedSim, go_to_sleep) expectedMsg.responseType = LinFrameResponseType::MasterResponse; EXPECT_CALL(participant, SendMsg(&master, expectedMsg)).Times(1); - EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::SleepPending))) - .Times(1); + EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::SleepPending))).Times(1); master.GoToSleep(); } @@ -278,8 +278,7 @@ TEST_F(Test_LinControllerDetailedSim, wake_up) master.Init(config); EXPECT_CALL(participant, SendMsg(&master, A())).Times(1); - EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Operational))) - .Times(1); + EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Operational))).Times(1); master.Wakeup(); } @@ -292,8 +291,7 @@ TEST_F(Test_LinControllerDetailedSim, wake_up_internal) master.Init(config); EXPECT_CALL(participant, SendMsg(&master, A())).Times(0); - EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Operational))) - .Times(1); + EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Operational))).Times(1); master.WakeupInternal(); } @@ -371,7 +369,7 @@ TEST_F(Test_LinControllerDetailedSim, update_tx_buffer) master.Init(config); EXPECT_EQ(master.GetThisLinNode().responses[frame.id].frame.data, frame.data); - + frame.data = {1, 1, 1, 1, 1, 1, 1, 1}; EXPECT_CALL(participant, SendMsg(&master, A())).Times(1); master.UpdateTxBuffer(frame); diff --git a/SilKit/source/services/lin/Test_LinControllerTrivialSim.cpp b/SilKit/source/services/lin/Test_LinControllerTrivialSim.cpp old mode 100755 new mode 100644 index 4afab634a..edf0a55bd --- a/SilKit/source/services/lin/Test_LinControllerTrivialSim.cpp +++ b/SilKit/source/services/lin/Test_LinControllerTrivialSim.cpp @@ -62,15 +62,15 @@ class Test_LinControllerTrivialSim : public testing::Test wakeupHandler = [this](ILinController* ctrl, const LinWakeupEvent& /*wakeupEvent*/) { callbacks.WakeupHandler(ctrl); }; - slaveConfigurationHandler = [this](ILinController* ctrl, + slaveConfigurationHandler = + [this](ILinController* ctrl, const SilKit::Experimental::Services::Lin::LinSlaveConfigurationEvent& /*slaveConfigurationEvent*/) { callbacks.LinSlaveConfigurationHandler(ctrl); }; - + master.SetServiceDescriptor(addr1); - ON_CALL(participant.mockTimeProvider, Now()) - .WillByDefault(testing::Return(35s)); + ON_CALL(participant.mockTimeProvider, Now()).WillByDefault(testing::Return(35s)); slave1.SetServiceDescriptor(addr2); slave2.SetServiceDescriptor(addr3); @@ -105,14 +105,13 @@ TEST_F(Test_LinControllerTrivialSim, throw_on_inactive_init) TEST_F(Test_LinControllerTrivialSim, throw_on_duplicate_init) { LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - + master.Init(config); EXPECT_THROW(master.Init(config), SilKit::StateError); } TEST_F(Test_LinControllerTrivialSim, send_frame_with_configured_master_response) { - LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); LinFrameResponse response; LinFrame frame = MakeFrame(17, LinChecksumModel::Enhanced, 4, {1, 2, 3, 4, 5, 6, 7, 8}); @@ -128,7 +127,6 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_with_configured_master_response) TEST_F(Test_LinControllerTrivialSim, send_frame_with_unconfigured_master_response) { - LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); @@ -154,9 +152,9 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_with_one_slave_response_via_slav // Configure Master LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - + master.Init(config); - + // Send Frame EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); EXPECT_CALL(participant, SendMsg(&master, A())).Times(1); @@ -167,7 +165,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_with_one_slave_response_via_slav { // Init Master LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - + master.Init(config); // Let master know about slave @@ -195,7 +193,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_slave_response_undefined_datalen { // Init Master LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - + master.Init(config); // Let master know about slave @@ -222,7 +220,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_slave_response_undefined_datalen TEST_F(Test_LinControllerTrivialSim, send_frame_with_unconfigured_slave_response) { LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - + master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); @@ -240,23 +238,23 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_with_multiple_slave_responses) // Configure Slave 1 auto slaveConfig = ToWire(MakeControllerConfig(LinControllerMode::Slave)); LinFrameResponse response; - response.frame = MakeFrame(17, LinChecksumModel::Enhanced, 4, {1,2,3,4,5,6,7,8}); + response.frame = MakeFrame(17, LinChecksumModel::Enhanced, 4, {1, 2, 3, 4, 5, 6, 7, 8}); response.responseMode = LinFrameResponseMode::TxUnconditional; slaveConfig.frameResponses.push_back(response); EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); master.ReceiveMsg(&slave1, slaveConfig); // Configure Slave 2 - slaveConfig.frameResponses[0].frame = MakeFrame(17, LinChecksumModel::Classic, 2, {0,1,0,1,0,1,0,1}); + slaveConfig.frameResponses[0].frame = MakeFrame(17, LinChecksumModel::Classic, 2, {0, 1, 0, 1, 0, 1, 0, 1}); EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); master.ReceiveMsg(&slave2, slaveConfig); // Configure Master LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - + master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); - + // Send Frame LinFrame frame = MakeFrame(17, LinChecksumModel::Enhanced); EXPECT_CALL(participant, SendMsg(&master, ATransmissionWith(LinFrameStatus::LIN_RX_ERROR, 35s))).Times(1); @@ -278,7 +276,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_with_master_and_slave_responses) // Configure Master LinControllerConfig masterConfig = MakeControllerConfig(LinControllerMode::Master); - + master.Init(masterConfig); master.AddFrameStatusHandler(frameStatusHandler); @@ -307,7 +305,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_slave_to_slave_receive_tx) // Init Master LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - + master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); @@ -332,7 +330,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_header_with_master_and_slave_res // Configure Master auto masterConfig = MakeControllerConfig(LinControllerMode::Master); - + masterConfig.frameResponses.push_back(slaveResponse); // Duplicate TxUnconditional master.Init(masterConfig); master.AddFrameStatusHandler(frameStatusHandler); @@ -351,7 +349,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_with_one_slave_sleeping) // Configure Slave 1 auto slaveConfig = ToWire(MakeControllerConfig(LinControllerMode::Slave)); LinFrameResponse response; - response.frame = MakeFrame(17, LinChecksumModel::Enhanced, 4, {1,2,3,4,5,6,7,8}); + response.frame = MakeFrame(17, LinChecksumModel::Enhanced, 4, {1, 2, 3, 4, 5, 6, 7, 8}); response.responseMode = LinFrameResponseMode::TxUnconditional; slaveConfig.frameResponses.push_back(response); EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); @@ -365,7 +363,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_with_one_slave_sleeping) LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); - + // Send Frame LinFrame frame = MakeFrame(17, LinChecksumModel::Enhanced); EXPECT_CALL(participant, SendMsg(&master, ATransmissionWith(LinFrameStatus::LIN_RX_NO_RESPONSE, 35s))).Times(1); @@ -377,7 +375,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_with_one_slave_sleeping) TEST_F(Test_LinControllerTrivialSim, send_frame_header_with_unconfigured_response) { LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - + master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); @@ -405,11 +403,11 @@ TEST_F(Test_LinControllerTrivialSim, receive_frame_wrong_checksum) response.frame = configuredFrame; response.responseMode = LinFrameResponseMode::Rx; config.frameResponses.push_back(response); - + master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); - LinFrame receivedFrame = MakeFrame(configuredFrame.id, LinChecksumModel::Classic); // Receive with Classic + LinFrame receivedFrame = MakeFrame(configuredFrame.id, LinChecksumModel::Classic); // Receive with Classic receivedFrame.dataLength = configuredFrame.dataLength; EXPECT_CALL(callbacks, FrameStatusHandler(&master, receivedFrame, LinFrameStatus::LIN_RX_ERROR)).Times(1); @@ -419,19 +417,19 @@ TEST_F(Test_LinControllerTrivialSim, receive_frame_wrong_checksum) TEST_F(Test_LinControllerTrivialSim, receive_frame_wrong_datalength) { LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - LinFrame configuredFrame = MakeFrame(17, LinChecksumModel::Enhanced); + LinFrame configuredFrame = MakeFrame(17, LinChecksumModel::Enhanced); configuredFrame.dataLength = 8; // Configure with 8 configuredFrame.data = {1, 2, 3, 4, 5, 6, 7, 8}; LinFrameResponse response; response.frame = configuredFrame; response.responseMode = LinFrameResponseMode::Rx; config.frameResponses.push_back(response); - + master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); LinFrame receivedFrame = MakeFrame(configuredFrame.id, LinChecksumModel::Classic); - receivedFrame.dataLength = 7; // Receive with 7 + receivedFrame.dataLength = 7; // Receive with 7 EXPECT_CALL(callbacks, FrameStatusHandler(&master, receivedFrame, LinFrameStatus::LIN_RX_ERROR)).Times(1); master.ReceiveMsg(&slave1, LinTransmission{35s, receivedFrame, LinFrameStatus::LIN_RX_OK}); @@ -440,26 +438,26 @@ TEST_F(Test_LinControllerTrivialSim, receive_frame_wrong_datalength) TEST_F(Test_LinControllerTrivialSim, receive_frame_overwrite_checksum_and_datalength) { LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - LinFrame configuredFrame = MakeFrame(17, LinChecksumModel::Unknown, LinDataLengthUnknown); // Configure with Undefined + LinFrame configuredFrame = + MakeFrame(17, LinChecksumModel::Unknown, LinDataLengthUnknown); // Configure with Undefined LinFrameResponse response; response.frame = configuredFrame; response.responseMode = LinFrameResponseMode::Rx; config.frameResponses.push_back(response); - + master.Init(config); master.AddFrameStatusHandler(frameStatusHandler); LinFrame receivedFrame = MakeFrame(configuredFrame.id, LinChecksumModel::Classic); // Receive with Classic receivedFrame.dataLength = 4; - EXPECT_CALL(callbacks, FrameStatusHandler(&master, receivedFrame, LinFrameStatus::LIN_RX_OK)).Times(1); // Receive ok + EXPECT_CALL(callbacks, FrameStatusHandler(&master, receivedFrame, LinFrameStatus::LIN_RX_OK)) + .Times(1); // Receive ok master.ReceiveMsg(&slave1, LinTransmission{35s, receivedFrame, LinFrameStatus::LIN_RX_OK}); // No overwrite of configured response - EXPECT_EQ(master.GetThisLinNode().responses[receivedFrame.id].frame.checksumModel, - configuredFrame.checksumModel); - EXPECT_EQ(master.GetThisLinNode().responses[receivedFrame.id].frame.dataLength, - configuredFrame.dataLength); + EXPECT_EQ(master.GetThisLinNode().responses[receivedFrame.id].frame.checksumModel, configuredFrame.checksumModel); + EXPECT_EQ(master.GetThisLinNode().responses[receivedFrame.id].frame.dataLength, configuredFrame.dataLength); } @@ -474,7 +472,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_header_with_master_tx_slave_rx) response.frame = frame; response.responseMode = LinFrameResponseMode::TxUnconditional; masterConfig.frameResponses.push_back(response); - + master.Init(masterConfig); master.AddFrameStatusHandler(frameStatusHandler); @@ -482,14 +480,14 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_header_with_master_tx_slave_rx) EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); slave1.ReceiveMsg(&master, ToWire(masterConfig)); - // Slave Rx on 17 + // Slave Rx on 17 LinControllerConfig slaveConfig = MakeControllerConfig(LinControllerMode::Slave); response.responseMode = LinFrameResponseMode::Rx; slaveConfig.frameResponses.push_back(response); EXPECT_CALL(participant, SendMsg(&slave1, A())).Times(1); slave1.Init(slaveConfig); slave1.AddFrameStatusHandler(frameStatusHandler); - + // Master receives the config EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); master.ReceiveMsg(&slave1, ToWire(slaveConfig)); @@ -511,7 +509,7 @@ TEST_F(Test_LinControllerTrivialSim, send_frame_header_with_master_tx_slave_rx) // Slave calls FrameStatusHandler with RX on reception EXPECT_CALL(callbacks, FrameStatusHandler(&slave1, frame, LinFrameStatus::LIN_RX_OK)).Times(1); - slave1.ReceiveMsg(&master, LinTransmission{35s, frame, LinFrameStatus::LIN_RX_OK }); + slave1.ReceiveMsg(&master, LinTransmission{35s, frame, LinFrameStatus::LIN_RX_OK}); } TEST_F(Test_LinControllerTrivialSim, send_frame_header_with_master_rx_slave_tx) @@ -571,7 +569,7 @@ TEST_F(Test_LinControllerTrivialSim, trigger_slave_callbacks) response.frame = MakeFrame(17, LinChecksumModel::Enhanced, 4); response.responseMode = LinFrameResponseMode::Rx; config.frameResponses.push_back(response); - LinFrame txFrame = MakeFrame(18, LinChecksumModel::Classic, 2, {1,2,0,0,0,0,0,0}); + LinFrame txFrame = MakeFrame(18, LinChecksumModel::Classic, 2, {1, 2, 0, 0, 0, 0, 0, 0}); response.frame = txFrame; response.responseMode = LinFrameResponseMode::TxUnconditional; config.frameResponses.push_back(response); @@ -582,19 +580,19 @@ TEST_F(Test_LinControllerTrivialSim, trigger_slave_callbacks) LinTransmission transmission; // Expect LIN_RX_OK - transmission.frame = MakeFrame(17, LinChecksumModel::Enhanced, 4, {1,2,3,4,0,0,0,0}); + transmission.frame = MakeFrame(17, LinChecksumModel::Enhanced, 4, {1, 2, 3, 4, 0, 0, 0, 0}); transmission.status = LinFrameStatus::LIN_RX_OK; EXPECT_CALL(callbacks, FrameStatusHandler(&master, transmission.frame, LinFrameStatus::LIN_RX_OK)).Times(1); master.ReceiveMsg(&slave1, transmission); // Expect LIN_RX_ERROR due to dataLength mismatch - transmission.frame = MakeFrame(17, LinChecksumModel::Enhanced, 2, {1,2,0,0,0,0,0,0}); + transmission.frame = MakeFrame(17, LinChecksumModel::Enhanced, 2, {1, 2, 0, 0, 0, 0, 0, 0}); transmission.status = LinFrameStatus::LIN_RX_OK; EXPECT_CALL(callbacks, FrameStatusHandler(&master, transmission.frame, LinFrameStatus::LIN_RX_ERROR)).Times(1); master.ReceiveMsg(&slave1, transmission); // Expect LIN_RX_ERROR due to checksumModel mismatch - transmission.frame = MakeFrame(17, LinChecksumModel::Classic, 4, {1,2,3,4,0,0,0,0}); + transmission.frame = MakeFrame(17, LinChecksumModel::Classic, 4, {1, 2, 3, 4, 0, 0, 0, 0}); transmission.status = LinFrameStatus::LIN_RX_OK; EXPECT_CALL(callbacks, FrameStatusHandler(&master, transmission.frame, LinFrameStatus::LIN_RX_ERROR)).Times(1); master.ReceiveMsg(&slave1, transmission); @@ -605,7 +603,8 @@ TEST_F(Test_LinControllerTrivialSim, trigger_slave_callbacks) master.ReceiveMsg(&slave1, transmission); // Expect no callback with LIN_RX_NO_RESPONSE - EXPECT_CALL(callbacks, FrameStatusHandler(&master, A(), LinFrameStatus::LIN_RX_NO_RESPONSE)).Times(0); + EXPECT_CALL(callbacks, FrameStatusHandler(&master, A(), LinFrameStatus::LIN_RX_NO_RESPONSE)) + .Times(0); transmission.frame.id = 19; master.ReceiveMsg(&slave1, transmission); } @@ -645,10 +644,8 @@ TEST_F(Test_LinControllerTrivialSim, go_to_sleep_internal) { master.Init(MakeControllerConfig(LinControllerMode::Master)); - EXPECT_CALL(participant, SendMsg(&master, ATransmissionWith(GoToSleepFrame(), LinFrameStatus::LIN_RX_OK))) - .Times(0); - EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Sleep))) - .Times(1); + EXPECT_CALL(participant, SendMsg(&master, ATransmissionWith(GoToSleepFrame(), LinFrameStatus::LIN_RX_OK))).Times(0); + EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Sleep))).Times(1); master.GoToSleepInternal(); } @@ -687,12 +684,9 @@ TEST_F(Test_LinControllerTrivialSim, wake_up) { master.Init(MakeControllerConfig(LinControllerMode::Master)); - EXPECT_CALL(participant, SendMsg(&master, A())) - .Times(1); - EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Operational))) - .Times(1); - EXPECT_CALL(participant.mockTimeProvider, Now()) - .Times(1); + EXPECT_CALL(participant, SendMsg(&master, A())).Times(1); + EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Operational))).Times(1); + EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); master.Wakeup(); } @@ -702,10 +696,8 @@ TEST_F(Test_LinControllerTrivialSim, wake_up_internal) LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); master.Init(config); - EXPECT_CALL(participant, SendMsg(&master, A())) - .Times(0); - EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Operational))) - .Times(1); + EXPECT_CALL(participant, SendMsg(&master, A())).Times(0); + EXPECT_CALL(participant, SendMsg(&master, AControllerStatusUpdateWith(LinControllerStatus::Operational))).Times(1); master.WakeupInternal(); } @@ -728,8 +720,7 @@ TEST_F(Test_LinControllerTrivialSim, call_wakeup_handler) TEST_F(Test_LinControllerTrivialSim, receive_frame_unknown_checksum) { LinControllerConfig config = MakeControllerConfig(LinControllerMode::Master); - LinFrame configuredFrame = - MakeFrame(17, LinChecksumModel::Enhanced, 4); // Configure with Enhanced + LinFrame configuredFrame = MakeFrame(17, LinChecksumModel::Enhanced, 4); // Configure with Enhanced LinFrameResponse response; response.frame = configuredFrame; response.responseMode = LinFrameResponseMode::Rx; @@ -831,8 +822,7 @@ TEST_F(Test_LinControllerTrivialSim, add_remove_handler) master.RemoveFrameStatusHandler(handlerId); } - EXPECT_CALL(callbacks, FrameStatusHandler(&master, transmission.frame, LinFrameStatus::LIN_RX_OK)) - .Times(0); + EXPECT_CALL(callbacks, FrameStatusHandler(&master, transmission.frame, LinFrameStatus::LIN_RX_OK)).Times(0); master.ReceiveMsg(&slave1, transmission); } @@ -842,11 +832,8 @@ TEST_F(Test_LinControllerTrivialSim, add_remove_handler) TEST_F(Test_LinControllerTrivialSim, DISABLED_send_with_tracing) { - - const auto now = 0x0815ns; - ON_CALL(participant.mockTimeProvider, Now()) - .WillByDefault(testing::Return(now)); + ON_CALL(participant.mockTimeProvider, Now()).WillByDefault(testing::Return(now)); master.AddSink(&traceSink, SilKit::Config::NetworkType::LIN); @@ -854,10 +841,8 @@ TEST_F(Test_LinControllerTrivialSim, DISABLED_send_with_tracing) master.Init(config); LinFrame frame = MakeFrame(17, LinChecksumModel::Enhanced); - EXPECT_CALL(participant.mockTimeProvider, Now()) - .Times(1); - EXPECT_CALL(traceSink, - Trace(SilKit::Services::TransmitDirection::TX, master.GetServiceDescriptor(), now, frame)) + EXPECT_CALL(participant.mockTimeProvider, Now()).Times(1); + EXPECT_CALL(traceSink, Trace(SilKit::Services::TransmitDirection::TX, master.GetServiceDescriptor(), now, frame)) .Times(1); master.SendFrame(frame, LinFrameResponseType::MasterResponse); diff --git a/SilKit/source/services/lin/Test_LinSerdes.cpp b/SilKit/source/services/lin/Test_LinSerdes.cpp index 48293a38d..59fa2aae6 100644 --- a/SilKit/source/services/lin/Test_LinSerdes.cpp +++ b/SilKit/source/services/lin/Test_LinSerdes.cpp @@ -40,8 +40,8 @@ TEST(Test_LinSerdes, SimLin_Frame) in.dataLength = 6; in.data = std::array{'V', 'E', 'C', 'T', 'O', 'R', 0, 0}; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } @@ -60,8 +60,8 @@ TEST(Test_LinSerdes, SimLin_SendFrameRequest) in.frame.data = std::array{'A', 2, 3, 6, 'c', 'Z', 'K'}; in.responseType = LinFrameResponseType::SlaveToSlave; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } @@ -77,8 +77,8 @@ TEST(Test_LinSerdes, SimLin_SendFrameHeaderRequest) in.timestamp = 13ns; in.id = 49; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } @@ -97,8 +97,8 @@ TEST(Test_LinSerdes, SimLin_Transmission) in.frame.data = std::array{'A', 2, 3, 6, 'c', 'Z', 'K'}; in.status = LinFrameStatus::LIN_TX_OK; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } @@ -113,8 +113,8 @@ TEST(Test_LinSerdes, SimLin_WakeupPulse) in.timestamp = 13ns; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } @@ -133,8 +133,8 @@ TEST(Test_LinSerdes, SimLin_FrameResponse) in.frame.data = std::array{'A', 'B', 'E', 'c', 'A', 'B', 'E', 'c'}; in.responseMode = LinFrameResponseMode::TxUnconditional; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } @@ -163,8 +163,8 @@ TEST(Test_LinSerdes, SimLin_ControllerConfig) in.frameResponses.push_back(response2); in.simulationMode = WireLinControllerConfig::SimulationMode::Dynamic; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } @@ -180,8 +180,8 @@ TEST(Test_LinSerdes, SimLin_ControllerStatusUpdate) in.timestamp = 10s; in.status = LinControllerStatus::Sleep; - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } @@ -208,8 +208,8 @@ TEST(Test_LinSerdes, SimLin_FrameResponseUpdate) in.frameResponses.push_back(response1); in.frameResponses.push_back(response2); - Serialize(buffer , in); - Deserialize(buffer , out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in, out); } diff --git a/SilKit/source/services/logging/ILogger.hpp b/SilKit/source/services/logging/ILogger.hpp index 5fa72ff08..ca2856869 100644 --- a/SilKit/source/services/logging/ILogger.hpp +++ b/SilKit/source/services/logging/ILogger.hpp @@ -36,20 +36,20 @@ namespace Logging { class LogOnceFlag { std::atomic_bool _once{false}; + public: - operator bool() const + operator bool() const { return _once.load(); } bool WasCalled() { - bool expected{ false }; + bool expected{false}; return !_once.compare_exchange_strong(expected, true); - } }; -template +template void Log(ILogger* logger, Level level, const char* fmt, const Args&... args) { if (logger && (logger->GetLogLevel() <= level)) @@ -57,21 +57,20 @@ void Log(ILogger* logger, Level level, const char* fmt, const Args&... args) const std::string msg = fmt::format(fmt, args...); logger->Log(level, msg); } - } -template +template void Trace(ILogger* logger, const char* fmt, const Args&... args) { Log(logger, Level::Trace, fmt, args...); } -template +template void Debug(ILogger* logger, const char* fmt, const Args&... args) { Log(logger, Level::Debug, fmt, args...); } -template +template void Debug(ILogger* logger, LogOnceFlag& onceflag, const char* fmt, const Args&... args) { if (onceflag.WasCalled()) @@ -82,18 +81,18 @@ void Debug(ILogger* logger, LogOnceFlag& onceflag, const char* fmt, const Args&. Log(logger, Level::Debug, fmt, args...); } -template +template void Info(ILogger* logger, const char* fmt, const Args&... args) { Log(logger, Level::Info, fmt, args...); } -template +template void Warn(ILogger* logger, const char* fmt, const Args&... args) { Log(logger, Level::Warn, fmt, args...); } -template +template void Warn(ILogger* logger, LogOnceFlag& onceFlag, const char* fmt, const Args&... args) { if (onceFlag.WasCalled()) @@ -104,12 +103,12 @@ void Warn(ILogger* logger, LogOnceFlag& onceFlag, const char* fmt, const Args&.. Log(logger, Level::Warn, fmt, args...); } -template +template void Error(ILogger* logger, const char* fmt, const Args&... args) { Log(logger, Level::Error, fmt, args...); } -template +template void Critical(ILogger* logger, const char* fmt, const Args&... args) { Log(logger, Level::Critical, fmt, args...); diff --git a/SilKit/source/services/logging/LogMsgReceiver.hpp b/SilKit/source/services/logging/LogMsgReceiver.hpp index a9f7e78af..0b4ea932b 100644 --- a/SilKit/source/services/logging/LogMsgReceiver.hpp +++ b/SilKit/source/services/logging/LogMsgReceiver.hpp @@ -45,14 +45,14 @@ class LogMsgReceiver // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; private: // ---------------------------------------- // private members Core::IParticipantInternal* _participant{nullptr}; Core::ServiceDescriptor _serviceDescriptor{}; - + Logging::Logger* _logger; }; // ================================================================================ diff --git a/SilKit/source/services/logging/LogMsgSender.hpp b/SilKit/source/services/logging/LogMsgSender.hpp index 0a448e326..316e4f0f6 100644 --- a/SilKit/source/services/logging/LogMsgSender.hpp +++ b/SilKit/source/services/logging/LogMsgSender.hpp @@ -44,7 +44,7 @@ class LogMsgSender // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; private: // ---------------------------------------- diff --git a/SilKit/source/services/logging/Logger.cpp b/SilKit/source/services/logging/Logger.cpp old mode 100755 new mode 100644 index c3e004237..d0a1318a8 --- a/SilKit/source/services/logging/Logger.cpp +++ b/SilKit/source/services/logging/Logger.cpp @@ -43,8 +43,7 @@ namespace Services { namespace Logging { namespace { -class SilKitRemoteSink - : public spdlog::sinks::base_sink +class SilKitRemoteSink : public spdlog::sinks::base_sink { public: SilKitRemoteSink() = delete; @@ -62,7 +61,8 @@ class SilKitRemoteSink void sink_it_(const spdlog::details::log_msg& msg) override { // ignore recursive calls to the remote logger or when explicitly disabled - if (_is_disabled) return; + if (_is_disabled) + return; _is_disabled = true; _logMsgHandler(from_spdlog(msg)); @@ -88,7 +88,7 @@ Logger::Logger(const std::string& participantName, Config::Logging config) // NB: logger gets dropped from registry immediately after creating so that two participant with the same // participantName won't lead to a spdlog exception because a logger with this name does already exist. spdlog::drop(participantName); - + // set_default_logger should not be used here, as there can only be one default logger and if another participant // gets created, the first default logger will be dropped from the registry as well. @@ -177,10 +177,7 @@ void Logger::Critical(const std::string& msg) void Logger::RegisterRemoteLogging(const LogMsgHandler& handler) { auto remoteSinkRef = std::find_if(_config.sinks.begin(), _config.sinks.end(), - [](const Config::Sink& sink) - { - return sink.type == Config::Sink::Type::Remote; - }); + [](const Config::Sink& sink) { return sink.type == Config::Sink::Type::Remote; }); if (remoteSinkRef != _config.sinks.end()) { diff --git a/SilKit/source/services/logging/LoggingSerdes.cpp b/SilKit/source/services/logging/LoggingSerdes.cpp index db57c70a6..36b7408c4 100644 --- a/SilKit/source/services/logging/LoggingSerdes.cpp +++ b/SilKit/source/services/logging/LoggingSerdes.cpp @@ -29,36 +29,24 @@ using SilKit::Core::MessageBuffer; inline MessageBuffer& operator<<(MessageBuffer& buffer, const SourceLoc& sourceLoc) { - buffer << sourceLoc.filename - << sourceLoc.line - << sourceLoc.funcname; + buffer << sourceLoc.filename << sourceLoc.line << sourceLoc.funcname; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, SourceLoc& sourceLoc) { - buffer >> sourceLoc.filename - >> sourceLoc.line - >> sourceLoc.funcname; + buffer >> sourceLoc.filename >> sourceLoc.line >> sourceLoc.funcname; return buffer; } inline MessageBuffer& operator<<(MessageBuffer& buffer, const LogMsg& msg) { - buffer << msg.logger_name - << msg.level - << msg.time - << msg.source - << msg.payload; + buffer << msg.logger_name << msg.level << msg.time << msg.source << msg.payload; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, LogMsg& msg) { - buffer >> msg.logger_name - >> msg.level - >> msg.time - >> msg.source - >> msg.payload; + buffer >> msg.logger_name >> msg.level >> msg.time >> msg.source >> msg.payload; return buffer; } diff --git a/SilKit/source/services/logging/LoggingSerdes.hpp b/SilKit/source/services/logging/LoggingSerdes.hpp index 2c34cc52d..3dab67822 100644 --- a/SilKit/source/services/logging/LoggingSerdes.hpp +++ b/SilKit/source/services/logging/LoggingSerdes.hpp @@ -28,7 +28,7 @@ namespace SilKit { namespace Services { namespace Logging { -void Serialize(SilKit::Core::MessageBuffer& buffer,const LogMsg& msg); +void Serialize(SilKit::Core::MessageBuffer& buffer, const LogMsg& msg); void Deserialize(SilKit::Core::MessageBuffer& buffer, LogMsg& out); } // namespace Logging diff --git a/SilKit/source/services/logging/MessageTracing.hpp b/SilKit/source/services/logging/MessageTracing.hpp old mode 100755 new mode 100644 index 386259f44..81dc0c3d1 --- a/SilKit/source/services/logging/MessageTracing.hpp +++ b/SilKit/source/services/logging/MessageTracing.hpp @@ -28,17 +28,17 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SilKit { namespace Services { -template +template void TraceRx(Logging::ILogger* logger, const Core::IServiceEndpoint* addr, const SilKitMessageT& msg, const Core::ServiceDescriptor& from) { Logging::Trace(logger, "Recv on {} from {}: {}", addr->GetServiceDescriptor(), from.GetParticipantName(), msg); } -template +template void TraceTx(Logging::ILogger* logger, const Core::IServiceEndpoint* addr, const SilKitMessageT& msg) { - Logging::Trace(logger, "Send from {}: {}", addr->GetServiceDescriptor(), msg); + Logging::Trace(logger, "Send from {}: {}", addr->GetServiceDescriptor(), msg); } // Don't trace LogMessages - this could cause cycles! @@ -47,4 +47,3 @@ inline void TraceTx(Logging::ILogger* /*logger*/, Core::IServiceEndpoint* /*addr } // namespace Services } // namespace SilKit - diff --git a/SilKit/source/services/logging/MockLogger.hpp b/SilKit/source/services/logging/MockLogger.hpp index 8d692ff26..aca3d1ff9 100644 --- a/SilKit/source/services/logging/MockLogger.hpp +++ b/SilKit/source/services/logging/MockLogger.hpp @@ -76,7 +76,7 @@ class MockLogger : public ::SilKit::Services::Logging::ILogger Log(Level::Critical, msg); } - MOCK_METHOD(SilKit::Services::Logging::Level, GetLogLevel, (), (const,override)); + MOCK_METHOD(SilKit::Services::Logging::Level, GetLogLevel, (), (const, override)); }; diff --git a/SilKit/source/services/logging/SilKitFmtFormatters.hpp b/SilKit/source/services/logging/SilKitFmtFormatters.hpp old mode 100755 new mode 100644 index e3a8e9d98..8bea70863 --- a/SilKit/source/services/logging/SilKitFmtFormatters.hpp +++ b/SilKit/source/services/logging/SilKitFmtFormatters.hpp @@ -52,7 +52,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "IServiceEndpoint.hpp" // for operator<<(... ServiceDescriptor) -#define MAKE_FORMATTER(TYPE) template<> struct fmt::formatter : ostream_formatter {} +#define MAKE_FORMATTER(TYPE) \ + template <> \ + struct fmt::formatter : ostream_formatter \ + { \ + } MAKE_FORMATTER(SilKit::Services::Can::CanConfigureBaudrate); diff --git a/SilKit/source/services/logging/SpdlogTypeConversion.hpp b/SilKit/source/services/logging/SpdlogTypeConversion.hpp old mode 100755 new mode 100644 index 8d9a19841..861bf3c71 --- a/SilKit/source/services/logging/SpdlogTypeConversion.hpp +++ b/SilKit/source/services/logging/SpdlogTypeConversion.hpp @@ -71,7 +71,8 @@ inline auto from_spdlog(spdlog::level::level_enum level) -> Level case spdlog::level::off: return Level::Off; case spdlog::level::n_levels: - throw SilKitError("SpdlogTypeConversion: Don't convert the guard. Squelch warning by covering this in the switch"); + throw SilKitError( + "SpdlogTypeConversion: Don't convert the guard. Squelch warning by covering this in the switch"); } throw SilKit::TypeConversionError{}; } @@ -79,12 +80,12 @@ inline auto from_spdlog(spdlog::level::level_enum level) -> Level inline auto from_spdlog(const spdlog::source_loc& spdLoc) -> SourceLoc { SourceLoc loc; - if(spdLoc.filename != nullptr) + if (spdLoc.filename != nullptr) { loc.filename = spdLoc.filename; } loc.line = spdLoc.line; - if(spdLoc.funcname != nullptr) + if (spdLoc.funcname != nullptr) { loc.funcname = spdLoc.funcname; } @@ -112,12 +113,7 @@ inline auto to_spdlog(const SourceLoc& loc) -> spdlog::source_loc inline auto to_spdlog(const LogMsg& msg) -> spdlog::details::log_msg { - return spdlog::details::log_msg{ - to_spdlog(msg.source), - msg.logger_name, - to_spdlog(msg.level), - msg.payload - }; + return spdlog::details::log_msg{to_spdlog(msg.source), msg.logger_name, to_spdlog(msg.level), msg.payload}; } } // namespace Logging diff --git a/SilKit/source/services/logging/Test_Logger.cpp b/SilKit/source/services/logging/Test_Logger.cpp index 95b5b3c17..e5f58a589 100644 --- a/SilKit/source/services/logging/Test_Logger.cpp +++ b/SilKit/source/services/logging/Test_Logger.cpp @@ -57,11 +57,8 @@ class MockParticipant : public DummyParticipant auto ALogMsgWith(std::string logger_name, Level level, std::string payload) -> Matcher { - return AllOf( - Field(&LogMsg::logger_name, logger_name), - Field(&LogMsg::level, level), - Field(&LogMsg::payload, payload) - ); + return AllOf(Field(&LogMsg::logger_name, logger_name), Field(&LogMsg::level, level), + Field(&LogMsg::payload, payload)); } TEST(Test_Logger, log_level_conversion) @@ -77,12 +74,12 @@ TEST(Test_Logger, log_level_conversion) TEST(Test_Logger, send_log_message_with_sender) { - ServiceDescriptor controllerAddress { "P1", "N1", "C2", 8}; + ServiceDescriptor controllerAddress{"P1", "N1", "C2", 8}; MockParticipant mockParticipant; LogMsgSender logMsgSender(&mockParticipant); - + logMsgSender.SetServiceDescriptor(controllerAddress); LogMsg msg; @@ -90,8 +87,7 @@ TEST(Test_Logger, send_log_message_with_sender) msg.level = Level::Info; msg.payload = std::string{"some payload"}; - EXPECT_CALL(mockParticipant, SendMsg(&logMsgSender, std::move(msg))) - .Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&logMsgSender, std::move(msg))).Times(1); logMsgSender.SendLogMsg(std::move(msg)); } @@ -109,29 +105,23 @@ TEST(Test_Logger, send_log_message_from_logger) Logger logger{loggerName, config}; - ServiceDescriptor controllerAddress { "P1", "N1", "C2" , 8}; + ServiceDescriptor controllerAddress{"P1", "N1", "C2", 8}; MockParticipant mockParticipant; LogMsgSender logMsgSender(&mockParticipant); logMsgSender.SetServiceDescriptor(controllerAddress); logger.RegisterRemoteLogging([&logMsgSender](LogMsg logMsg) { - logMsgSender.SendLogMsg(std::move(logMsg)); - }); std::string payload{"Test log message"}; - EXPECT_CALL(mockParticipant, SendMsg(&logMsgSender, - ALogMsgWith(loggerName, Level::Info, payload))) - .Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&logMsgSender, ALogMsgWith(loggerName, Level::Info, payload))).Times(1); logger.Info(payload); - EXPECT_CALL(mockParticipant, SendMsg(&logMsgSender, - ALogMsgWith(loggerName, Level::Critical, payload))) - .Times(1); + EXPECT_CALL(mockParticipant, SendMsg(&logMsgSender, ALogMsgWith(loggerName, Level::Critical, payload))).Times(1); logger.Critical(payload); } @@ -160,9 +150,9 @@ TEST(Test_Logger, get_log_level) TEST(Test_Logger, LogOnceFlag_check_setter) { - LogOnceFlag once; + LogOnceFlag once; EXPECT_EQ(once.WasCalled(), false); EXPECT_EQ(once.WasCalled(), true); EXPECT_EQ(once.WasCalled(), true); } -} // anonymous namespace +} // anonymous namespace diff --git a/SilKit/source/services/logging/Test_LoggingSerdes.cpp b/SilKit/source/services/logging/Test_LoggingSerdes.cpp index b2c0bdd51..877083d7b 100644 --- a/SilKit/source/services/logging/Test_LoggingSerdes.cpp +++ b/SilKit/source/services/logging/Test_LoggingSerdes.cpp @@ -30,7 +30,7 @@ TEST(Test_LoggingSerdes, LoggingSerdes) in.level = SilKit::Services::Logging::Level::Trace; SilKit::Services::Logging::SourceLoc loc; loc.filename = "somefile.txt"; - loc.funcname ="TEST(LoggingSerdes)"; + loc.funcname = "TEST(LoggingSerdes)"; loc.line = 15; in.source = loc; in.payload = "Hello, logger!"; diff --git a/SilKit/source/services/orchestration/ILifecycleStates.hpp b/SilKit/source/services/orchestration/ILifecycleStates.hpp index 582625655..6d33d842c 100644 --- a/SilKit/source/services/orchestration/ILifecycleStates.hpp +++ b/SilKit/source/services/orchestration/ILifecycleStates.hpp @@ -37,7 +37,7 @@ class ILifecycleState { public: virtual ~ILifecycleState() = default; - + // Advance from Invalid to ServicesCreated; Fail otherwise. virtual void Initialize(std::string reason) = 0; @@ -45,7 +45,7 @@ class ILifecycleState // Coordinated: Wait for SystemState::ServicesCreated, then... // ... advance to CommunicationInitializingState after receiving replies from all other participants. virtual void ServicesCreated(std::string reason) = 0; - + // Advance to CommunicationInitialized after all pending service subscriptions are completed. virtual void CommunicationInitializing(std::string reason) = 0; @@ -73,7 +73,7 @@ class ILifecycleState // ... trigger StopHandler; If completed, advance to Stopped. Then, // advance to ShuttingDown after receiving replies from all other participants. virtual void StopSimulation(std::string reason) = 0; - + // Trigger the ShutdownHandler; If completed, advance to ShutdownState. virtual void ShutdownParticipant(std::string reason) = 0; @@ -81,7 +81,7 @@ class ILifecycleState virtual void ResolveAbortSimulation(std::string reason) = 0; virtual void Error(std::string reason) = 0; - + virtual auto toString() -> std::string = 0; virtual auto GetParticipantState() -> ParticipantState = 0; diff --git a/SilKit/source/services/orchestration/LifecycleManagement.cpp b/SilKit/source/services/orchestration/LifecycleManagement.cpp old mode 100755 new mode 100644 index 88ad53bd8..3b8d558c1 --- a/SilKit/source/services/orchestration/LifecycleManagement.cpp +++ b/SilKit/source/services/orchestration/LifecycleManagement.cpp @@ -84,7 +84,7 @@ void LifecycleManagement::Restart(std::string reason) _currentState->RestartParticipant(std::move(reason)); } -void LifecycleManagement::Shutdown(std::string reason) +void LifecycleManagement::Shutdown(std::string reason) { _currentState->ShutdownParticipant(std::move(reason)); } @@ -251,9 +251,9 @@ void LifecycleManagement::StartTime() (dynamic_cast(_lifecycleService->GetTimeSyncService()))->StartTime(); } -void LifecycleManagement::SetAsyncSubscriptionsCompletionHandler(std::function handler) +void LifecycleManagement::AddAsyncSubscriptionsCompletionHandler(std::function handler) { - _lifecycleService->SetAsyncSubscriptionsCompletionHandler(std::move(handler)); + _lifecycleService->AddAsyncSubscriptionsCompletionHandler(std::move(handler)); } void LifecycleManagement::SetState(ILifecycleState* newState, std::string reason) @@ -263,7 +263,7 @@ void LifecycleManagement::SetState(ILifecycleState* newState, std::string reason } void LifecycleManagement::SetStateAndForwardIntent(ILifecycleState* newState, - void (ILifecycleState::*intent)(std::string), std::string reason) + void (ILifecycleState::*intent)(std::string), std::string reason) { UpdateLifecycleState(newState); // NB: UpdateParticipantState can alter _currentState if the ParticipantState change causes a SystemState change. diff --git a/SilKit/source/services/orchestration/LifecycleManagement.hpp b/SilKit/source/services/orchestration/LifecycleManagement.hpp old mode 100755 new mode 100644 index 380c20a7e..adf985d8a --- a/SilKit/source/services/orchestration/LifecycleManagement.hpp +++ b/SilKit/source/services/orchestration/LifecycleManagement.hpp @@ -38,23 +38,21 @@ namespace Orchestration { //forwards class LifecycleService; -class LifecycleManagement +class LifecycleManagement { public: //CTors - LifecycleManagement( - Core::IParticipantInternal* participant, - Services::Logging::ILogger* logger, - LifecycleService* parentService); + LifecycleManagement(Core::IParticipantInternal* participant, Services::Logging::ILogger* logger, + LifecycleService* parentService); // Triggered by Public API calls - void Pause(std::string reason); // ILifecycleService::Pause - void Continue(std::string reason); // ILifecycleService::Continue - void Stop(std::string reason); // ILifecycleService::Stop - void AbortSimulation(std::string reason); // ISystemController::AbortSimulation - void Error(std::string reason); // ILifecycleService::ReportError + void Pause(std::string reason); // ILifecycleService::Pause + void Continue(std::string reason); // ILifecycleService::Continue + void Stop(std::string reason); // ILifecycleService::Stop + void AbortSimulation(std::string reason); // ISystemController::AbortSimulation + void Error(std::string reason); // ILifecycleService::ReportError // Currently not part of ILifecycleService - void Restart(std::string reason); // LifecycleService::Restart + void Restart(std::string reason); // LifecycleService::Restart // Common internal actions void Initialize(std::string reason); @@ -79,7 +77,7 @@ class LifecycleManagement bool HandleAbort(); // Wait for pending subscriptions before advancing from CommunicationInitializing to CommunicationInitialized - void SetAsyncSubscriptionsCompletionHandler(std::function handler); + void AddAsyncSubscriptionsCompletionHandler(std::function handler); // Abort handling void ResolveAbortSimulation(std::string reason); @@ -95,10 +93,8 @@ class LifecycleManagement void SetState(ILifecycleState* newState, std::string message); // Set state and trigger an action on the new state. - void SetStateAndForwardIntent( - ILifecycleState* nextState, - void (ILifecycleState::*intent)(std::string), - std::string reason); + void SetStateAndForwardIntent(ILifecycleState* nextState, void (ILifecycleState::*intent)(std::string), + std::string reason); // State getter ILifecycleState* GetCurrentState(); diff --git a/SilKit/source/services/orchestration/LifecycleService.cpp b/SilKit/source/services/orchestration/LifecycleService.cpp old mode 100755 new mode 100644 index ed7d20a4f..1a5d31b21 --- a/SilKit/source/services/orchestration/LifecycleService.cpp +++ b/SilKit/source/services/orchestration/LifecycleService.cpp @@ -47,9 +47,7 @@ LifecycleService::LifecycleService(Core::IParticipantInternal* participant) _timeSyncService = _participant->CreateTimeSyncService(this); } - LifecycleService::~LifecycleService() -{ -} +LifecycleService::~LifecycleService() {} void LifecycleService::SetCommunicationReadyHandler(CommunicationReadyHandler handler) { @@ -67,9 +65,10 @@ void LifecycleService::CompleteCommunicationReadyHandlerAsync() { _logger->Debug("LifecycleService::CompleteCommunicationReadyHandler: enter"); // async handler is finished, now continue to the Running state without triggering the CommunicationReadyHandler again - if(!_commReadyHandlerInvoked) + if (!_commReadyHandlerInvoked) { - _logger->Debug("LifecycleService::CompleteCommunicationReadyHandler was called without invoking the CommunicationReadyHandler, ignoring."); + _logger->Debug("LifecycleService::CompleteCommunicationReadyHandler was called without invoking the " + "CommunicationReadyHandler, ignoring."); return; } if (_commReadyHandlerCompleted) @@ -105,15 +104,14 @@ void LifecycleService::SetAbortHandler(AbortHandler handler) _abortHandler = std::move(handler); } -auto LifecycleService::StartLifecycle() - -> std::future +auto LifecycleService::StartLifecycle() -> std::future { std::stringstream ss; ss << "Lifecycle of participant " << _participant->GetParticipantName() << " started"; _logger->Debug(ss.str()); - _isLifecycleStarted = true; - + _isLifecycleStarted = true; + if (_finalStatePromise == nullptr) { throw LogicError{"LifecycleService::StartLifecycle must not be called twice"}; @@ -155,27 +153,26 @@ auto LifecycleService::StartLifecycle() serviceDiscovery->NotifyServiceCreated(_serviceDescriptor); serviceDiscovery->NotifyServiceCreated(_timeSyncService->GetServiceDescriptor()); - _participant->GetSystemMonitor()->AddSystemStateHandler([&](auto systemState) { - this->NewSystemState(systemState); - }); + _participant->GetSystemMonitor()->AddSystemStateHandler( + [&](auto systemState) { this->NewSystemState(systemState); }); - // Initialize switches to ServicesCreated. In parallel, the reception of an invalid WorkflowConfiguration could + // Initialize switches to ServicesCreated. In parallel, the reception of an invalid WorkflowConfiguration could // lead to ErrorState, so we need to defer this to the IO-Worker Thread - _participant->ExecuteDeferred([this] { - _lifecycleManager.Initialize("LifecycleService::StartLifecycle was called."); - }); + _participant->ExecuteDeferred( + [this] { _lifecycleManager.Initialize("LifecycleService::StartLifecycle was called."); }); switch (_operationMode) { - case OperationMode::Invalid: + case OperationMode::Invalid: throw ConfigurationError("OperationMode was not set. This is mandatory."); - case OperationMode::Coordinated: + case OperationMode::Coordinated: // ServicesCreated is triggered by SystemState break; case OperationMode::Autonomous: // Autonomous start direcly, coordinated wait for SystemState Change - _participant->ExecuteDeferred([this]{ - _lifecycleManager.StartAutonomous("LifecycleService::StartLifecycle was called without start coordination."); + _participant->ExecuteDeferred([this] { + _lifecycleManager.StartAutonomous( + "LifecycleService::StartLifecycle was called without start coordination."); }); break; @@ -186,7 +183,6 @@ auto LifecycleService::StartLifecycle() void LifecycleService::ReportError(std::string errorMsg) { _participant->ExecuteDeferred([errorMsg, this] { - _logger->Error(errorMsg); if (!_isLifecycleStarted) @@ -242,9 +238,7 @@ void LifecycleService::Continue() void LifecycleService::Stop(std::string reason) { _stopRequested = true; - _participant->ExecuteDeferred([this, reason] { - _lifecycleManager.Stop(reason); - }); + _participant->ExecuteDeferred([this, reason] { _lifecycleManager.Stop(reason); }); } void LifecycleService::Restart(std::string /*reason*/) @@ -264,11 +258,11 @@ OperationMode LifecycleService::GetOperationMode() const bool LifecycleService::TriggerCommunicationReadyHandler() { - if(_commReadyHandler) + if (_commReadyHandler) { - if(_commReadyHandlerIsAsync) + if (_commReadyHandlerIsAsync) { - if(!_commReadyHandlerInvoked) + if (!_commReadyHandlerInvoked) { _commReadyHandlerInvoked = true; _commReadyHandlerCompleted = false; @@ -330,9 +324,7 @@ void LifecycleService::AbortSimulation(std::string reason) _abortedBeforeLifecycleStart = true; return; } - _participant->ExecuteDeferred([this, reason] { - _lifecycleManager.AbortSimulation(reason); - }); + _participant->ExecuteDeferred([this, reason] { _lifecycleManager.AbortSimulation(reason); }); } bool LifecycleService::CheckForValidConfiguration() @@ -352,9 +344,9 @@ bool LifecycleService::CheckForValidConfiguration() std::stringstream ss; ss << _participant->GetParticipantName() - << ": This participant is in OperationMode::Coordinated but it is not part of the " - "set of \"required\" participants declared by the system controller. "; - + << ": This participant is in OperationMode::Coordinated but it is not part of the " + "set of \"required\" participants declared by the system controller. "; + ReportError(ss.str()); return false; @@ -413,9 +405,9 @@ auto LifecycleService::Status() const -> const ParticipantStatus& return _returnValueForStatus; } -void LifecycleService::SetAsyncSubscriptionsCompletionHandler(std::function handler) +void LifecycleService::AddAsyncSubscriptionsCompletionHandler(std::function handler) { - _participant->SetAsyncSubscriptionsCompletionHandler(std::move(handler)); + _participant->AddAsyncSubscriptionsCompletionHandler(std::move(handler)); } auto LifecycleService::GetTimeSyncService() -> ITimeSyncService* @@ -440,12 +432,14 @@ void LifecycleService::ReceiveMsg(const IServiceEndpoint*, const SystemCommand& { switch (command.kind) { - case SystemCommand::Kind::Invalid: break; + case SystemCommand::Kind::Invalid: + break; case SystemCommand::Kind::AbortSimulation: AbortSimulation("Received SystemCommand::AbortSimulation"); return; - default: break; + default: + break; } // We should not reach this point in normal operation. @@ -494,10 +488,10 @@ void LifecycleService::NewSystemState(SystemState systemState) { switch (_operationMode) { - case OperationMode::Invalid: + case OperationMode::Invalid: // ignore return; - case OperationMode::Coordinated: + case OperationMode::Coordinated: break; case OperationMode::Autonomous: // autonomous participants do not react to system states changes! @@ -510,30 +504,30 @@ void LifecycleService::NewSystemState(SystemState systemState) switch (systemState) { - case SystemState::Invalid: - break; - case SystemState::ServicesCreated: + case SystemState::Invalid: + break; + case SystemState::ServicesCreated: _lifecycleManager.ServicesCreated(ss.str()); break; - case SystemState::CommunicationInitializing: - break; - case SystemState::CommunicationInitialized: + case SystemState::CommunicationInitializing: + break; + case SystemState::CommunicationInitialized: _lifecycleManager.CommunicationInitialized(ss.str()); break; - case SystemState::ReadyToRun: - _lifecycleManager.ReadyToRun(ss.str()); + case SystemState::ReadyToRun: + _lifecycleManager.ReadyToRun(ss.str()); break; - case SystemState::Running: - _logger->Info("Simulation running"); - break; - case SystemState::Paused: - _logger->Info("Simulation paused"); - break; - case SystemState::Stopping: - _logger->Info("Simulation stopping"); + case SystemState::Running: + _logger->Info("Simulation is now running"); + break; + case SystemState::Paused: + _logger->Info("Simulation is paused"); + break; + case SystemState::Stopping: + _logger->Info("Simulation is stopping"); // Only allow external stop signal if we are actually running or paused - if (_lifecycleManager.GetCurrentState() == _lifecycleManager.GetRunningState() || - _lifecycleManager.GetCurrentState() == _lifecycleManager.GetPausedState()) + if (_lifecycleManager.GetCurrentState() == _lifecycleManager.GetRunningState() + || _lifecycleManager.GetCurrentState() == _lifecycleManager.GetPausedState()) { _lifecycleManager.Stop(ss.str()); } @@ -541,13 +535,13 @@ void LifecycleService::NewSystemState(SystemState systemState) case SystemState::Stopped: break; case SystemState::ShuttingDown: - break; - case SystemState::Shutdown: - _logger->Info("Simulation has shutdown"); - break; - case SystemState::Aborting: - break; - case SystemState::Error: + break; + case SystemState::Shutdown: + _logger->Info("Simulation is shut down"); + break; + case SystemState::Aborting: + break; + case SystemState::Error: break; } } diff --git a/SilKit/source/services/orchestration/LifecycleService.hpp b/SilKit/source/services/orchestration/LifecycleService.hpp old mode 100755 new mode 100644 index 192b7a1df..be03049db --- a/SilKit/source/services/orchestration/LifecycleService.hpp +++ b/SilKit/source/services/orchestration/LifecycleService.hpp @@ -73,8 +73,7 @@ class LifecycleService auto CreateTimeSyncService() -> ITimeSyncService* override; auto GetTimeSyncService() -> ITimeSyncService*; - auto StartLifecycle() - -> std::future override; + auto StartLifecycle() -> std::future override; void ReportError(std::string errorMsg) override; @@ -119,7 +118,7 @@ class LifecycleService void SetLifecycleConfiguration(LifecycleConfiguration startConfiguration); void SetWorkflowConfiguration(const WorkflowConfiguration& msg); - void SetAsyncSubscriptionsCompletionHandler(std::function handler); + void AddAsyncSubscriptionsCompletionHandler(std::function handler); OperationMode GetOperationMode() const; auto StopRequested() const -> bool; @@ -160,7 +159,7 @@ class LifecycleService std::atomic _isLifecycleStarted{false}; std::atomic _abortedBeforeLifecycleStart{false}; - + LifecycleManagement _lifecycleManager; std::atomic _timeSyncActive{false}; @@ -195,7 +194,6 @@ class LifecycleService // for immediate checks (e.g., not to send out the NextSimTask after a stopping in the SimTaskHandler). std::atomic _stopRequested{false}; std::atomic _pauseRequested{false}; - }; // ================================================================================ diff --git a/SilKit/source/services/orchestration/LifecycleStates.cpp b/SilKit/source/services/orchestration/LifecycleStates.cpp old mode 100755 new mode 100644 index fd8447019..4e849f8e8 --- a/SilKit/source/services/orchestration/LifecycleStates.cpp +++ b/SilKit/source/services/orchestration/LifecycleStates.cpp @@ -122,9 +122,7 @@ void State::InvalidStateTransition(std::string transitionName, bool triggerError bool State::IsAnyOf(SystemState state, std::initializer_list stateList) { - return std::any_of(begin(stateList), end(stateList), [=](auto candidate) { - return candidate == state; - }); + return std::any_of(begin(stateList), end(stateList), [=](auto candidate) { return candidate == state; }); } void State::ProcessAbortCommandInCallback() @@ -137,8 +135,7 @@ void State::ProcessAbortCommand(std::string reason) { _abortRequested = false; _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetAbortingState(), - &ILifecycleState::ResolveAbortSimulation, - std::move(reason)); + &ILifecycleState::ResolveAbortSimulation, std::move(reason)); } // ------------------------------------ @@ -183,9 +180,9 @@ void ServicesCreatedState::ServicesCreated(std::string reason) // subscriptions have been received. _lifecycleManager->GetParticipant()->GetParticipantRepliesProcedure()->CallAfterAllParticipantsReplied( [reason, this]() { - // If done, move forward to CommunicationInitializingState and call ServicesCreated - _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetCommunicationInitializingState(), - &ILifecycleState::ServicesCreated, reason); + // If done, move forward to CommunicationInitializingState and call ServicesCreated + _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetCommunicationInitializingState(), + &ILifecycleState::ServicesCreated, reason); }); } @@ -197,8 +194,8 @@ void ServicesCreatedState::AbortSimulation(std::string reason) void ServicesCreatedState::ResolveAbortSimulation(std::string reason) { // Skip stopping as the simulation was not running yet - _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetAbortingState(), &ILifecycleState::ResolveAbortSimulation, - std::move(reason)); + _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetAbortingState(), + &ILifecycleState::ResolveAbortSimulation, std::move(reason)); } auto ServicesCreatedState::toString() -> std::string @@ -224,10 +221,10 @@ void CommunicationInitializingState::CommunicationInitializing(std::string reaso { // Delay the next state until pending subscriptions of controllers are completed. // Applies to all controllers that are included in the trait UseAsyncRegistration(). - _lifecycleManager->SetAsyncSubscriptionsCompletionHandler([reason, this]() { + _lifecycleManager->AddAsyncSubscriptionsCompletionHandler([reason, this]() { // If done, move forward to CommunicationInitializedState and call CommunicationInitializing _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetCommunicationInitializedState(), - &ILifecycleState::CommunicationInitializing, reason); + &ILifecycleState::CommunicationInitializing, reason); }); } @@ -239,8 +236,8 @@ void CommunicationInitializingState::AbortSimulation(std::string reason) void CommunicationInitializingState::ResolveAbortSimulation(std::string reason) { // Skip stopping as the simulation was not running yet - _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetAbortingState(), &ILifecycleState::ResolveAbortSimulation, - std::move(reason)); + _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetAbortingState(), + &ILifecycleState::ResolveAbortSimulation, std::move(reason)); } auto CommunicationInitializingState::toString() -> std::string @@ -267,7 +264,7 @@ void CommunicationInitializedState::CommunicationInitializing(std::string /*reas } } -void CommunicationInitializedState::CommunicationInitialized(std::string reason) +void CommunicationInitializedState::CommunicationInitialized(std::string reason) { _handlerExecuting = true; auto callbackResult = _lifecycleManager->HandleCommunicationReady(); @@ -281,7 +278,8 @@ void CommunicationInitializedState::CommunicationInitialized(std::string reason) else { // Switch to error state if handle triggers error - _lifecycleManager->SetState(_lifecycleManager->GetErrorState(), "Exception during CommunicationReadyHandle execution."); + _lifecycleManager->SetState(_lifecycleManager->GetErrorState(), + "Exception during CommunicationReadyHandle execution."); } break; case SilKit::Services::Orchestration::CallbackResult::Completed: @@ -294,18 +292,19 @@ void CommunicationInitializedState::CommunicationInitialized(std::string reason) CompleteCommunicationReadyHandler(std::move(reason)); } break; - case SilKit::Services::Orchestration::CallbackResult::Deferred: + case SilKit::Services::Orchestration::CallbackResult::Deferred: _lifecycleManager->GetLogger()->Debug("Deferred CommunicationReady callback."); break; - default: break; + default: + break; } _handlerExecuting = false; } void CommunicationInitializedState::CompleteCommunicationReadyHandler(std::string reason) { - _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetReadyToRunState(), &ILifecycleState::CommunicationInitialized, - reason); + _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetReadyToRunState(), + &ILifecycleState::CommunicationInitialized, reason); } @@ -354,7 +353,7 @@ void ReadyToRunState::CommunicationInitialized(std::string /*reason*/) } } -void ReadyToRunState::ReadyToRun(std::string reason) +void ReadyToRunState::ReadyToRun(std::string reason) { if (!_lifecycleManager->GetService()->IsTimeSyncActive()) { @@ -371,7 +370,8 @@ void ReadyToRunState::ReadyToRun(std::string reason) } else { - _lifecycleManager->SetState(_lifecycleManager->GetRunningState(), "Finished StartingHandler execution."); + _lifecycleManager->SetState(_lifecycleManager->GetRunningState(), + "Finished StartingHandler execution."); } } else @@ -383,7 +383,8 @@ void ReadyToRunState::ReadyToRun(std::string reason) else { // Switch to error state if handle triggers error - _lifecycleManager->SetState(_lifecycleManager->GetErrorState(), "Exception during StartingHandler execution."); + _lifecycleManager->SetState(_lifecycleManager->GetErrorState(), + "Exception during StartingHandler execution."); } } _handlerExecuting = false; @@ -396,8 +397,8 @@ void ReadyToRunState::ReadyToRun(std::string reason) } else { - _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetRunningState(), &ILifecycleState::ReadyToRun, - std::move(reason)); + _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetRunningState(), + &ILifecycleState::ReadyToRun, std::move(reason)); } } } @@ -463,7 +464,7 @@ void RunningState::ContinueSimulation(std::string reason) void RunningState::StopSimulation(std::string reason) { _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetStoppingState(), &ILifecycleState::StopSimulation, - std::move(reason)); + std::move(reason)); } void RunningState::AbortSimulation(std::string reason) @@ -505,7 +506,7 @@ void PausedState::ContinueSimulation(std::string reason) void PausedState::StopSimulation(std::string reason) { _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetStoppingState(), &ILifecycleState::StopSimulation, - std::move(reason)); + std::move(reason)); } void PausedState::AbortSimulation(std::string /*reason*/) @@ -545,8 +546,8 @@ void StoppingState::StopSimulation(std::string reason) } else { - _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetStoppedState(), &ILifecycleState::StopSimulation, - std::move(reason)); + _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetStoppedState(), + &ILifecycleState::StopSimulation, std::move(reason)); } } else @@ -590,12 +591,10 @@ auto StoppingState::GetParticipantState() -> ParticipantState void StoppedState::StopSimulation(std::string reason) { // StoppedState will only advance to ShuttingDown after receiving replies from all participants. - // This guarantees that the ParticipantState::Stopping has arrived and other participants will + // This guarantees that the ParticipantState::Stopping has arrived and other participants will // evaluate the correct SystemState and stop themselves. _lifecycleManager->GetParticipant()->GetParticipantRepliesProcedure()->CallAfterAllParticipantsReplied( - [this, reason]() { - _lifecycleManager->Shutdown(reason); - }); + [this, reason]() { _lifecycleManager->Shutdown(reason); }); } void StoppedState::RestartParticipant(std::string /*reason*/) @@ -605,8 +604,8 @@ void StoppedState::RestartParticipant(std::string /*reason*/) void StoppedState::ShutdownParticipant(std::string reason) { - _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetShuttingDownState(), &ILifecycleState::ShutdownParticipant, - std::move(reason)); + _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetShuttingDownState(), + &ILifecycleState::ShutdownParticipant, std::move(reason)); } void StoppedState::AbortSimulation(std::string reason) @@ -647,8 +646,7 @@ void ShuttingDownState::ShutdownParticipant(std::string reason) "ShutdownHandler threw an exception. This is ignored. The participant will now shut down."); } _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetShutdownState(), - &ILifecycleState::ShutdownParticipant, - std::move(reason)); + &ILifecycleState::ShutdownParticipant, std::move(reason)); } void ShuttingDownState::AbortSimulation(std::string /*reason*/) @@ -704,18 +702,18 @@ void ShutdownState::ShutdownParticipant(std::string reason) { _lifecycleManager->GetParticipant()->GetParticipantRepliesProcedure()->CallAfterAllParticipantsReplied( [this, reason]() { - bool success = _lifecycleManager->GetCurrentState() != _lifecycleManager->GetErrorState(); - if (success) - { - _lifecycleManager->NotifyShutdownInConnection(); - _lifecycleManager->GetService()->SetFinalStatePromise(); - } - else - { - Logging::Warn(_lifecycleManager->GetLogger(), - "lifecycle failed to shut down correctly - original shutdown reason was '{}'.", - std::move(reason)); - } + bool success = _lifecycleManager->GetCurrentState() != _lifecycleManager->GetErrorState(); + if (success) + { + _lifecycleManager->NotifyShutdownInConnection(); + _lifecycleManager->GetService()->SetFinalStatePromise(); + } + else + { + Logging::Warn(_lifecycleManager->GetLogger(), + "lifecycle failed to shut down correctly - original shutdown reason was '{}'.", + std::move(reason)); + } }); } @@ -754,7 +752,7 @@ void AbortingState::ShutdownParticipant(std::string reason) &ILifecycleState::ShutdownParticipant, std::move(reason)); } -void AbortingState::AbortSimulation(std::string /*reason*/) +void AbortingState::AbortSimulation(std::string /*reason*/) { // NOP: Ignore AbortSimulation() in AbortingState } @@ -790,7 +788,7 @@ auto AbortingState::GetParticipantState() -> ParticipantState void ErrorState::Initialize(std::string /*reason*/) { - // Ignore due to possible invalid transition between InvalidWorkflowConfig->Error->Abort->Shutdown and StartLifecycle->Initialize + // Ignore due to possible invalid transition between InvalidWorkflowConfig->Error->Abort->Shutdown and StartLifecycle->Initialize } void ErrorState::RestartParticipant(std::string /*reason*/) @@ -805,8 +803,8 @@ void ErrorState::StopSimulation(std::string reason) void ErrorState::ShutdownParticipant(std::string reason) { - _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetShuttingDownState(), &ILifecycleState::ShutdownParticipant, - std::move(reason)); + _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetShuttingDownState(), + &ILifecycleState::ShutdownParticipant, std::move(reason)); } void ErrorState::AbortSimulation(std::string reason) diff --git a/SilKit/source/services/orchestration/LifecycleStates.hpp b/SilKit/source/services/orchestration/LifecycleStates.hpp index fe4520bbe..9c57eadae 100644 --- a/SilKit/source/services/orchestration/LifecycleStates.hpp +++ b/SilKit/source/services/orchestration/LifecycleStates.hpp @@ -42,9 +42,9 @@ class State : public ILifecycleState public: virtual ~State() = default; - + // See method description in ILifecycleState - + virtual void Initialize(std::string reason) override; virtual void ServicesCreated(std::string reason) override; virtual void CommunicationInitializing(std::string reason) override; @@ -70,7 +70,7 @@ class State : public ILifecycleState LifecycleManagement* _lifecycleManager; bool _abortRequested{false}; }; - + class InvalidState : public State { public: @@ -113,7 +113,7 @@ class CommunicationInitializingState : public State void ServicesCreated(std::string reason) override; void CommunicationInitializing(std::string reason) override; - + void AbortSimulation(std::string reason) override; void ResolveAbortSimulation(std::string reason) override; auto toString() -> std::string override; @@ -169,7 +169,7 @@ class RunningState : public State : State(lifecycleManager) { } - + void CommunicationInitializing(std::string reason) override; void CommunicationInitialized(std::string reason) override; void ReadyToRun(std::string reason) override; @@ -226,7 +226,7 @@ class StoppedState : public State } void StopSimulation(std::string reason) override; - + void RestartParticipant(std::string reason) override; void ShutdownParticipant(std::string reason) override; @@ -262,7 +262,7 @@ class ShutdownState : public State { } void Initialize(std::string reason) override; - + void CommunicationInitialized(std::string reason) override; void ReadyToRun(std::string reason) override; void StopSimulation(std::string reason) override; diff --git a/SilKit/source/services/orchestration/SyncDatatypeUtils.cpp b/SilKit/source/services/orchestration/SyncDatatypeUtils.cpp index f77bf3a09..8ed2f2e43 100644 --- a/SilKit/source/services/orchestration/SyncDatatypeUtils.cpp +++ b/SilKit/source/services/orchestration/SyncDatatypeUtils.cpp @@ -27,11 +27,8 @@ namespace Orchestration { bool operator==(const ParticipantStatus& lhs, const ParticipantStatus& rhs) { - return lhs.participantName == rhs.participantName - && lhs.state == rhs.state - && lhs.enterReason == rhs.enterReason - && lhs.enterTime == rhs.enterTime - && lhs.refreshTime == rhs.refreshTime; + return lhs.participantName == rhs.participantName && lhs.state == rhs.state && lhs.enterReason == rhs.enterReason + && lhs.enterTime == rhs.enterTime && lhs.refreshTime == rhs.refreshTime; } bool operator==(const SystemCommand& lhs, const SystemCommand& rhs) diff --git a/SilKit/source/services/orchestration/SyncSerdes.cpp b/SilKit/source/services/orchestration/SyncSerdes.cpp index e9e609b21..93d06e83c 100644 --- a/SilKit/source/services/orchestration/SyncSerdes.cpp +++ b/SilKit/source/services/orchestration/SyncSerdes.cpp @@ -26,60 +26,57 @@ namespace SilKit { namespace Services { namespace Orchestration { -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const SilKit::Services::Orchestration::NextSimTask& task) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const SilKit::Services::Orchestration::NextSimTask& task) { - buffer << task.timePoint - << task.duration; + buffer << task.timePoint << task.duration; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, SilKit::Services::Orchestration::NextSimTask& task) +inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, + SilKit::Services::Orchestration::NextSimTask& task) { - buffer >> task.timePoint - >> task.duration; + buffer >> task.timePoint >> task.duration; return buffer; } - -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const SilKit::Services::Orchestration::SystemCommand& cmd) + +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const SilKit::Services::Orchestration::SystemCommand& cmd) { buffer << cmd.kind; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, SilKit::Services::Orchestration::SystemCommand& cmd) +inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, + SilKit::Services::Orchestration::SystemCommand& cmd) { buffer >> cmd.kind; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const SilKit::Services::Orchestration::ParticipantStatus& status) +inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, + const SilKit::Services::Orchestration::ParticipantStatus& status) { - buffer << status.participantName - << status.state - << status.enterReason - << status.enterTime - << status.refreshTime; + buffer << status.participantName << status.state << status.enterReason << status.enterTime << status.refreshTime; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, SilKit::Services::Orchestration::ParticipantStatus& status) +inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, + SilKit::Services::Orchestration::ParticipantStatus& status) { - buffer >> status.participantName - >> status.state - >> status.enterReason - >> status.enterTime - >> status.refreshTime; + buffer >> status.participantName >> status.state >> status.enterReason >> status.enterTime >> status.refreshTime; return buffer; } -inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, - const SilKit::Services::Orchestration::WorkflowConfiguration& workflowConfiguration) +inline SilKit::Core::MessageBuffer& operator<<( + SilKit::Core::MessageBuffer& buffer, + const SilKit::Services::Orchestration::WorkflowConfiguration& workflowConfiguration) { buffer << workflowConfiguration.requiredParticipantNames; return buffer; } -inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, - SilKit::Services::Orchestration::WorkflowConfiguration& workflowConfiguration) +inline SilKit::Core::MessageBuffer& operator>>( + SilKit::Core::MessageBuffer& buffer, SilKit::Services::Orchestration::WorkflowConfiguration& workflowConfiguration) { buffer >> workflowConfiguration.requiredParticipantNames; return buffer; @@ -123,6 +120,6 @@ void Deserialize(SilKit::Core::MessageBuffer& buffer, NextSimTask& out) buffer >> out; } -} // namespace Orchestration +} // namespace Orchestration } // namespace Services } // namespace SilKit diff --git a/SilKit/source/services/orchestration/SyncSerdes.hpp b/SilKit/source/services/orchestration/SyncSerdes.hpp index 3b0830c70..f2eb3abf1 100644 --- a/SilKit/source/services/orchestration/SyncSerdes.hpp +++ b/SilKit/source/services/orchestration/SyncSerdes.hpp @@ -38,6 +38,6 @@ void Deserialize(SilKit::Core::MessageBuffer& buffer, ParticipantStatus& out); void Deserialize(SilKit::Core::MessageBuffer& buffer, WorkflowConfiguration& out); void Deserialize(SilKit::Core::MessageBuffer& buffer, NextSimTask& out); -} // namespace Orchestration +} // namespace Orchestration } // namespace Services } // namespace SilKit diff --git a/SilKit/source/services/orchestration/SystemController.cpp b/SilKit/source/services/orchestration/SystemController.cpp index f7a9577b8..d955167fe 100644 --- a/SilKit/source/services/orchestration/SystemController.cpp +++ b/SilKit/source/services/orchestration/SystemController.cpp @@ -45,7 +45,7 @@ void SystemController::AbortSimulation() const void SystemController::SetWorkflowConfiguration(const WorkflowConfiguration& workflowConfiguration) { - // Distribute to SystemMonitors (including self delivery) + // Distribute to SystemMonitors (including self delivery) _participant->SendMsg(this, workflowConfiguration); } diff --git a/SilKit/source/services/orchestration/SystemController.hpp b/SilKit/source/services/orchestration/SystemController.hpp index 0afa5750e..001f7d092 100644 --- a/SilKit/source/services/orchestration/SystemController.hpp +++ b/SilKit/source/services/orchestration/SystemController.hpp @@ -37,10 +37,10 @@ class SystemController , public IMsgForSystemController , public Core::IServiceEndpoint { - public: +public: // ---------------------------------------- // Public Data Types - + public: // ---------------------------------------- // Constructors, Destructor, and Assignment @@ -50,7 +50,7 @@ class SystemController SystemController(SystemController&& other) = default; SystemController& operator=(const SystemController& other) = default; SystemController& operator=(SystemController&& other) = default; - + public: // ---------------------------------------- // Public Methods @@ -60,7 +60,7 @@ class SystemController // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; private: // ---------------------------------------- @@ -69,7 +69,7 @@ class SystemController inline void SendMsg(MsgT&& msg) const; inline void SendSystemCommand(SystemCommand::Kind kind) const; - + private: // ---------------------------------------- // private members @@ -86,7 +86,7 @@ void SystemController::SendMsg(MsgT&& msg) const SILKIT_ASSERT(_participant); _participant->SendMsg(this, std::forward(msg)); } - + void SystemController::SendSystemCommand(SystemCommand::Kind kind) const { SystemCommand cmd; diff --git a/SilKit/source/services/orchestration/SystemMonitor.hpp b/SilKit/source/services/orchestration/SystemMonitor.hpp index 8abcf1a2d..ac0802fe7 100644 --- a/SilKit/source/services/orchestration/SystemMonitor.hpp +++ b/SilKit/source/services/orchestration/SystemMonitor.hpp @@ -69,7 +69,8 @@ class SystemMonitor void RemoveParticipantStatusHandler(HandlerId handlerId) override; auto SystemState() const -> Orchestration::SystemState override; - auto ParticipantStatus(const std::string& participantName) const -> const Orchestration::ParticipantStatus& override; + auto ParticipantStatus(const std::string& participantName) const + -> const Orchestration::ParticipantStatus& override; void ReceiveMsg(const IServiceEndpoint* from, const Orchestration::ParticipantStatus& msg) override; void ReceiveMsg(const IServiceEndpoint* from, const Orchestration::WorkflowConfiguration& msg) override; @@ -81,7 +82,7 @@ class SystemMonitor // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; public: // ---------------------------------------- diff --git a/SilKit/source/services/orchestration/SystemStateTracker.cpp b/SilKit/source/services/orchestration/SystemStateTracker.cpp index 0d00056d0..af40157ff 100644 --- a/SilKit/source/services/orchestration/SystemStateTracker.cpp +++ b/SilKit/source/services/orchestration/SystemStateTracker.cpp @@ -23,9 +23,8 @@ using SilKit::Services::Orchestration::SystemState; auto ValidateParticipantStateUpdate(ParticipantState oldParticipantState, ParticipantState newParticipantState) -> bool { auto OldParticipantStateWas = [oldParticipantState](std::initializer_list stateList) { - return std::any_of(begin(stateList), end(stateList), [oldParticipantState](auto candidate) { - return candidate == oldParticipantState; - }); + return std::any_of(begin(stateList), end(stateList), + [oldParticipantState](auto candidate) { return candidate == oldParticipantState; }); }; switch (newParticipantState) @@ -58,7 +57,7 @@ auto ValidateParticipantStateUpdate(ParticipantState oldParticipantState, Partic return OldParticipantStateWas({ParticipantState::Error, ParticipantState::Stopped}); case ParticipantState::Shutdown: - return OldParticipantStateWas({ParticipantState::ShuttingDown}); + return OldParticipantStateWas({ParticipantState::ShuttingDown, ParticipantState::Aborting}); case ParticipantState::Aborting: case ParticipantState::Error: @@ -148,11 +147,13 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar if (!ValidateParticipantStateUpdate(oldParticipantState, newParticipantState)) { - Log::Error( - _logger, - "SystemMonitor detected invalid ParticipantState transition from {} to {} EnterTime={}, EnterReason=\"{}\"", - oldParticipantState, newParticipantState, FormatTimePoint(newParticipantStatus.enterTime), - newParticipantStatus.enterReason); + const auto logLevel = IsRequiredParticipant(participantName) ? Log::Level::Warn : Log::Level::Debug; + + Log::Log(_logger, logLevel, + "SystemMonitor detected invalid ParticipantState transition for {} from {} to {} EnterTime={}, " + "EnterReason=\"{}\"", + participantName, oldParticipantState, newParticipantState, + FormatTimePoint(newParticipantStatus.enterTime), newParticipantStatus.enterReason); // NB: Failing validation doesn't actually stop the participants state from being changed, it just logs the // invalid transition @@ -306,10 +307,9 @@ auto SystemStateTracker::ComputeSystemState(ParticipantState newParticipantState const auto requiredParticipantState{requiredParticipantStatus->state}; - const bool accepted = - std::any_of(begin(stateList), end(stateList), [requiredParticipantState](auto candidate) { - return candidate == requiredParticipantState; - }); + const bool accepted = std::any_of( + begin(stateList), end(stateList), + [requiredParticipantState](auto candidate) { return candidate == requiredParticipantState; }); if (!accepted) { diff --git a/SilKit/source/services/orchestration/Test_LifecycleService.cpp b/SilKit/source/services/orchestration/Test_LifecycleService.cpp old mode 100755 new mode 100644 index 952ee5967..9896ff724 --- a/SilKit/source/services/orchestration/Test_LifecycleService.cpp +++ b/SilKit/source/services/orchestration/Test_LifecycleService.cpp @@ -56,9 +56,10 @@ class MockTimeSync : public TimeSyncService using TimeSyncService::TimeSyncService; public: - MOCK_METHOD(void, SetSimulationStepHandler, (SimulationStepHandler task, std::chrono::nanoseconds initialStepSize), (override)); - MOCK_METHOD(void, SetSimulationStepHandlerAsync, (SimulationStepHandler task, std::chrono::nanoseconds initialStepSize), + MOCK_METHOD(void, SetSimulationStepHandler, (SimulationStepHandler task, std::chrono::nanoseconds initialStepSize), (override)); + MOCK_METHOD(void, SetSimulationStepHandlerAsync, + (SimulationStepHandler task, std::chrono::nanoseconds initialStepSize), (override)); MOCK_METHOD(void, CompleteSimulationStep, (), (override)); MOCK_METHOD(void, SetPeriod, (std::chrono::nanoseconds)); MOCK_METHOD(std::chrono::nanoseconds, Now, (), (override, const)); @@ -67,9 +68,7 @@ class MockTimeSync : public TimeSyncService class MockParticipant : public DummyParticipant { public: - MockParticipant() - { - } + MockParticipant() {} public: MOCK_METHOD(TimeSyncService*, CreateTimeSyncService, (LifecycleService*)); @@ -101,8 +100,8 @@ class Test_LifecycleService : public testing::Test protected: // ---------------------------------------- // Members - NiceMock p1Id{"P1","N1", "C1", 1024}; - NiceMock p2Id{"P2","N1", "C1", 1024}; + NiceMock p1Id{"P1", "N1", "C1", 1024}; + NiceMock p2Id{"P2", "N1", "C1", 1024}; NiceMock masterId{"Master", "N1", "C2", 1027}; NiceMock participant; @@ -110,7 +109,7 @@ class Test_LifecycleService : public testing::Test Config::HealthCheck healthCheckConfig; }; -// will forward lifecycle with coordination up to +// will forward lifecycle with coordination up to // ParticipantState::ReadyToRun & SystemState::ReadyToRun void PrepareLifecycle(LifecycleService* lifecycleService) { @@ -120,7 +119,7 @@ void PrepareLifecycle(LifecycleService* lifecycleService) lifecycleService->NewSystemState(SystemState::ReadyToRun); } -auto StartCoordinated() +auto StartCoordinated() { LifecycleConfiguration sc{}; sc.operationMode = OperationMode::Coordinated; @@ -145,38 +144,27 @@ TEST_F(Test_LifecycleService, autonomous_must_not_react_to_system_states) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) - .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(0); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))).Times(0); lifecycleService.StartLifecycle(); // coordinated participants stay in ServicesCreated, autonomous advance to running @@ -219,7 +207,7 @@ TEST_F(Test_LifecycleService, start_stop_autonomous) lifecycleService.SetStartingHandler(bind_method(&callbacks, &Callbacks::StartingHandler)); lifecycleService.SetStopHandler(bind_method(&callbacks, &Callbacks::StopHandler)); lifecycleService.SetShutdownHandler(bind_method(&callbacks, &Callbacks::ShutdownHandler)); - + EXPECT_CALL(callbacks, CommunicationReadyHandler()).Times(1); EXPECT_CALL(callbacks, StartingHandler()).Times(1); EXPECT_CALL(callbacks, StopHandler()).Times(1); @@ -267,47 +255,33 @@ TEST_F(Test_LifecycleService, start_stop_coordinated_self_stop) lifecycleService.SetStartingHandler(bind_method(&callbacks, &Callbacks::StartingHandler)); lifecycleService.SetStopHandler(bind_method(&callbacks, &Callbacks::StopHandler)); lifecycleService.SetShutdownHandler(bind_method(&callbacks, &Callbacks::ShutdownHandler)); - - EXPECT_CALL(callbacks, CommunicationReadyHandler()) - .Times(1); - EXPECT_CALL(callbacks, StartingHandler()) - .Times(1); - EXPECT_CALL(callbacks, StopHandler()) - .Times(1); - EXPECT_CALL(callbacks, ShutdownHandler()) - .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(callbacks, CommunicationReadyHandler()).Times(1); + EXPECT_CALL(callbacks, StartingHandler()).Times(1); + EXPECT_CALL(callbacks, StopHandler()).Times(1); + EXPECT_CALL(callbacks, ShutdownHandler()).Times(1); + + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(2); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Paused))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Paused))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(1); lifecycleService.StartLifecycle(); @@ -400,27 +374,21 @@ TEST_F(Test_LifecycleService, error_on_double_pause) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Paused))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Paused))) .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))).Times(1); lifecycleService.StartLifecycle(); PrepareLifecycle(&lifecycleService); @@ -431,7 +399,6 @@ TEST_F(Test_LifecycleService, error_on_double_pause) } - TEST_F(Test_LifecycleService, error_handling_run_run_shutdown) { LifecycleService lifecycleService(&participant); @@ -445,29 +412,22 @@ TEST_F(Test_LifecycleService, error_handling_run_run_shutdown) lifecycleService.SetStopHandler(bind_method(&callbacks, &Callbacks::StopHandler)); lifecycleService.SetShutdownHandler(bind_method(&callbacks, &Callbacks::ShutdownHandler)); - EXPECT_CALL(callbacks, StopHandler()) - .Times(0); - EXPECT_CALL(callbacks, ShutdownHandler()) - .Times(0); + EXPECT_CALL(callbacks, StopHandler()).Times(0); + EXPECT_CALL(callbacks, ShutdownHandler()).Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))).Times(1); lifecycleService.StartLifecycle(); PrepareLifecycle(&lifecycleService); @@ -492,35 +452,26 @@ TEST_F(Test_LifecycleService, error_handling_exception_in_stop_callback) EXPECT_CALL(callbacks, StopHandler()).Times(1).WillRepeatedly(Throw(SilKitError("StopCallbackException"))); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Aborting))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))).Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Aborting))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(1); lifecycleService.StartLifecycle(); @@ -708,23 +659,19 @@ TEST_F(Test_LifecycleService, Abort_ReadyToRun) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) .Times(0); EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(1); @@ -809,32 +756,25 @@ TEST_F(Test_LifecycleService, Abort_Running) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(1); EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Aborting))) .Times(1); @@ -865,37 +805,29 @@ TEST_F(Test_LifecycleService, Abort_Paused) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Paused))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Paused))) .Times(1); - // Note: if aborting during Running, the simulation will stop regularly (including the stopping command), + // Note: if aborting during Running, the simulation will stop regularly (including the stopping command), // but without stopping if there are errors in the callbacks - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(1); EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Aborting))) .Times(1); @@ -930,41 +862,31 @@ TEST_F(Test_LifecycleService, Abort_Stopping) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(callbacks, StopHandler()) - .Times(1) - .WillRepeatedly(Invoke([&]() - { - SystemCommand abortCommand{SystemCommand::Kind::AbortSimulation}; - lifecycleService.ReceiveMsg(&masterId, abortCommand); - EXPECT_EQ(lifecycleService.State(), ParticipantState::Stopping); - })); - - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(callbacks, StopHandler()).Times(1).WillRepeatedly(Invoke([&]() { + SystemCommand abortCommand{SystemCommand::Kind::AbortSimulation}; + lifecycleService.ReceiveMsg(&masterId, abortCommand); + EXPECT_EQ(lifecycleService.State(), ParticipantState::Stopping); + })); + + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) .Times(0); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(1); EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Aborting))) .Times(1); @@ -992,41 +914,31 @@ TEST_F(Test_LifecycleService, Abort_ShuttingDown) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(callbacks, ShutdownHandler()) - .Times(1) - .WillRepeatedly(Invoke([&]() - { - SystemCommand abortCommand{SystemCommand::Kind::AbortSimulation}; - lifecycleService.ReceiveMsg(&masterId, abortCommand); - EXPECT_EQ(lifecycleService.State(), ParticipantState::ShuttingDown); - })); + EXPECT_CALL(callbacks, ShutdownHandler()).Times(1).WillRepeatedly(Invoke([&]() { + SystemCommand abortCommand{SystemCommand::Kind::AbortSimulation}; + lifecycleService.ReceiveMsg(&masterId, abortCommand); + EXPECT_EQ(lifecycleService.State(), ParticipantState::ShuttingDown); + })); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(1); EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Aborting))) .Times(0); @@ -1053,32 +965,25 @@ TEST_F(Test_LifecycleService, Abort_Shutdown) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Running))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopping))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Stopped))) .Times(1); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(1); lifecycleService.StartLifecycle(); @@ -1156,25 +1061,21 @@ TEST_F(Test_LifecycleService, Abort_LifecycleNotExecuted) lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(0); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) - .Times(0); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(0); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(0); EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(0); - EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(0); - EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ShuttingDown))) + .Times(0); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Shutdown))) .Times(0); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))).Times(0); EXPECT_EQ(lifecycleService.State(), ParticipantState::Invalid); // Abort right away @@ -1192,26 +1093,21 @@ TEST_F(Test_LifecycleService, error_handling_exception_in_starting_callback) ON_CALL(participant, CreateTimeSyncService(_)).WillByDefault(Return(&mockTimeSync)); lifecycleService.SetStartingHandler(bind_method(&callbacks, &Callbacks::StartingHandler)); - EXPECT_CALL(callbacks, StartingHandler()) - .Times(1) - .WillRepeatedly(Throw(SilKitError("StartingException"))); + EXPECT_CALL(callbacks, StartingHandler()).Times(1).WillRepeatedly(Throw(SilKitError("StartingException"))); lifecycleService.SetServiceDescriptor(p1Id.GetServiceDescriptor()); - EXPECT_CALL(participant, - SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) - .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ServicesCreated))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitializing))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, - AParticipantStatusWithState(ParticipantState::ReadyToRun))) + EXPECT_CALL(participant, + SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::CommunicationInitialized))) .Times(1); - EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))) + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::ReadyToRun))) .Times(1); + EXPECT_CALL(participant, SendMsg(&lifecycleService, AParticipantStatusWithState(ParticipantState::Error))).Times(1); lifecycleService.StartLifecycle(); PrepareLifecycle(&lifecycleService); @@ -1237,25 +1133,25 @@ TEST_F(Test_LifecycleService, async_comm_ready_handler) lifecycleService.CompleteCommunicationReadyHandlerAsync(); lifecycleService.SetCommunicationReadyHandlerAsync([&myPromise] { - std::cout <<"async_comm_ready_handler: signaling myPromise" << std::endl; + std::cout << "async_comm_ready_handler: signaling myPromise" << std::endl; myPromise.set_value(); }); - std::thread completer{[&completed, &lifecycleService]{ - std::cout <<"async_comm_ready_handler: completer waiting" - " after call to CompleteCommReadyHandler" << std::endl; + std::thread completer{[&completed, &lifecycleService] { + std::cout << "async_comm_ready_handler: completer waiting" + " after call to CompleteCommReadyHandler" + << std::endl; auto status = completed.wait_for(5s); EXPECT_EQ(status, std::future_status::ready) << "Error: CommunicationReadyHandler async should have been called"; - std::cout <<"async_comm_ready_Handler: completer calling CommunicationReadyHandler 1st" << std::endl; + std::cout << "async_comm_ready_Handler: completer calling CommunicationReadyHandler 1st" << std::endl; lifecycleService.CompleteCommunicationReadyHandlerAsync(); - + // Calling this multiple times should not result in an error: - std::cout <<"async_comm_ready_Handler: completer calling CommunicationReadyHandler 2nd" << std::endl; + std::cout << "async_comm_ready_Handler: completer calling CommunicationReadyHandler 2nd" << std::endl; lifecycleService.CompleteCommunicationReadyHandlerAsync(); - }}; lifecycleService.StartLifecycle(); @@ -1264,7 +1160,7 @@ TEST_F(Test_LifecycleService, async_comm_ready_handler) lifecycleService.NewSystemState(SystemState::CommunicationInitializing); lifecycleService.NewSystemState(SystemState::CommunicationInitialized); - if(completer.joinable()) + if (completer.joinable()) { completer.join(); } @@ -1304,7 +1200,7 @@ TEST_F(Test_LifecycleService, error_on_create_time_sync_service_twice) TEST_F(Test_LifecycleService, error_on_coordinated_not_required) { - // Goal: make sure that the lifecycleService throws an exception if it is first + // Goal: make sure that the lifecycleService throws an exception if it is first // set to be coordinated and then receives a required participant list without its own name LifecycleService lifecycleService(&participant); lifecycleService.SetLifecycleConfiguration(StartCoordinated()); @@ -1318,7 +1214,7 @@ TEST_F(Test_LifecycleService, error_on_coordinated_not_required) TEST_F(Test_LifecycleService, error_on_not_required_coordinated) { - // Goal: make sure that the lifecycleService throws an exception if it first + // Goal: make sure that the lifecycleService throws an exception if it first // receives a required participant list without its own name and is then set to be coordinated LifecycleService lifecycleService(&participant); lifecycleService.SetLifecycleConfiguration(StartCoordinated()); @@ -1328,12 +1224,11 @@ TEST_F(Test_LifecycleService, error_on_not_required_coordinated) lifecycleService.SetTimeSyncService(&mockTimeSync); lifecycleService.StartLifecycle(); - + WorkflowConfiguration workflowConfiguration; workflowConfiguration.requiredParticipantNames = {"NotThisParticipant", "AlsoNotThisParticipant"}; lifecycleService.SetWorkflowConfiguration(workflowConfiguration); EXPECT_EQ(lifecycleService.State(), ParticipantState::Error); - } } // namespace diff --git a/SilKit/source/services/orchestration/Test_SyncSerdes.cpp b/SilKit/source/services/orchestration/Test_SyncSerdes.cpp index a93f03d68..4e037b053 100644 --- a/SilKit/source/services/orchestration/Test_SyncSerdes.cpp +++ b/SilKit/source/services/orchestration/Test_SyncSerdes.cpp @@ -37,8 +37,8 @@ TEST(Test_SyncSerdes, MwSync_SystemCommand) SystemCommand in{SystemCommand::Kind::AbortSimulation}; SystemCommand out{SystemCommand::Kind::Invalid}; - Serialize(buffer , in); - Deserialize(buffer,out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.kind, out.kind); } @@ -49,7 +49,8 @@ TEST(Test_SyncSerdes, MwSync_ParticipantStatus) SilKit::Core::MessageBuffer buffer; auto now = std::chrono::system_clock::now(); - decltype(now) nowUs = std::chrono::system_clock::time_point{std::chrono::duration_cast(now.time_since_epoch())}; + decltype(now) nowUs = std::chrono::system_clock::time_point{ + std::chrono::duration_cast(now.time_since_epoch())}; ParticipantStatus in; ParticipantStatus out{}; @@ -60,8 +61,8 @@ TEST(Test_SyncSerdes, MwSync_ParticipantStatus) in.enterTime = nowUs; in.refreshTime = nowUs; - Serialize(buffer , in); - Deserialize(buffer,out); + Serialize(buffer, in); + Deserialize(buffer, out); EXPECT_EQ(in.participantName, out.participantName); EXPECT_EQ(in.state, out.state); @@ -71,4 +72,3 @@ TEST(Test_SyncSerdes, MwSync_ParticipantStatus) } } // anonymous namespace - diff --git a/SilKit/source/services/orchestration/Test_SystemMonitor.cpp b/SilKit/source/services/orchestration/Test_SystemMonitor.cpp index fc284a629..de4cd552f 100644 --- a/SilKit/source/services/orchestration/Test_SystemMonitor.cpp +++ b/SilKit/source/services/orchestration/Test_SystemMonitor.cpp @@ -54,8 +54,8 @@ class Test_SystemMonitor : public testing::Test MOCK_METHOD1(SystemStateHandler, void(SystemState)); MOCK_METHOD1(ParticipantStatusHandler, void(ParticipantStatus)); - MOCK_METHOD(void, ParticipantConnectedHandler, (const ParticipantConnectionInformation &), (const)); - MOCK_METHOD(void, ParticipantDisconnectedHandler, (const ParticipantConnectionInformation &), (const)); + MOCK_METHOD(void, ParticipantConnectedHandler, (const ParticipantConnectionInformation&), (const)); + MOCK_METHOD(void, ParticipantDisconnectedHandler, (const ParticipantConnectionInformation&), (const)); }; protected: @@ -69,10 +69,10 @@ class Test_SystemMonitor : public testing::Test ON_CALL(participant.logger, Log) .WillByDefault([](SilKit::Services::Logging::Level level, const std::string& message) { - std::ostringstream ss; - ss << "[" << to_string(level) << "] " << message << '\n'; - std::cout << ss.str() << std::flush; - }); + std::ostringstream ss; + ss << "[" << to_string(level) << "] " << message << '\n'; + std::cout << ss.str() << std::flush; + }); } auto AddSystemStateHandler() -> HandlerId @@ -80,14 +80,20 @@ class Test_SystemMonitor : public testing::Test return monitor.AddSystemStateHandler(bind_method(&callbacks, &Callbacks::SystemStateHandler)); } - void RemoveSystemStateHandler(HandlerId handlerId) { monitor.RemoveSystemStateHandler(handlerId); } + void RemoveSystemStateHandler(HandlerId handlerId) + { + monitor.RemoveSystemStateHandler(handlerId); + } auto AddParticipantStatusHandler() -> HandlerId { return monitor.AddParticipantStatusHandler(bind_method(&callbacks, &Callbacks::ParticipantStatusHandler)); } - void RemoveParticipantStatusHandler(HandlerId handlerId) { monitor.RemoveParticipantStatusHandler(handlerId); } + void RemoveParticipantStatusHandler(HandlerId handlerId) + { + monitor.RemoveParticipantStatusHandler(handlerId); + } void SetParticipantStatus(ParticipantId participantId, ParticipantState state, std::string reason = std::string{}) { @@ -97,7 +103,7 @@ class Test_SystemMonitor : public testing::Test status.participantName = syncParticipantNames.at(static_cast(id)); status.enterReason = reason; - ServiceDescriptor from{ "P1", "N1", "C2" , 1024}; + ServiceDescriptor from{"P1", "N1", "C2", 1024}; monitorFrom.SetServiceDescriptor(from); @@ -120,7 +126,7 @@ class Test_SystemMonitor : public testing::Test protected: // ---------------------------------------- // Members - ServiceDescriptor addr{ "P1", "N1", "C1", 1025}; + ServiceDescriptor addr{"P1", "N1", "C1", 1025}; std::vector syncParticipantNames; @@ -161,8 +167,7 @@ TEST_F(Test_SystemMonitor, detect_system_communication_initializing) AddSystemStateHandler(); - EXPECT_CALL(callbacks, SystemStateHandler(SystemState::CommunicationInitializing)) - .Times(1); + EXPECT_CALL(callbacks, SystemStateHandler(SystemState::CommunicationInitializing)).Times(1); SetParticipantStatus(1, ParticipantState::CommunicationInitializing); EXPECT_EQ(monitor.ParticipantStatus("P1").state, ParticipantState::CommunicationInitializing); EXPECT_EQ(monitor.SystemState(), SystemState::ServicesCreated); @@ -184,8 +189,7 @@ TEST_F(Test_SystemMonitor, detect_system_communication_initialized) AddSystemStateHandler(); - EXPECT_CALL(callbacks, SystemStateHandler(SystemState::CommunicationInitialized)) - .Times(1); + EXPECT_CALL(callbacks, SystemStateHandler(SystemState::CommunicationInitialized)).Times(1); SetParticipantStatus(1, ParticipantState::CommunicationInitialized); EXPECT_EQ(monitor.ParticipantStatus("P1").state, ParticipantState::CommunicationInitialized); EXPECT_EQ(monitor.SystemState(), SystemState::CommunicationInitializing); @@ -261,8 +265,7 @@ TEST_F(Test_SystemMonitor, detect_system_pause) AddSystemStateHandler(); EXPECT_CALL(callbacks, SystemStateHandler(SystemState::Paused)).Times(1); - EXPECT_CALL(callbacks, SystemStateHandler(SystemState::Running)) - .Times(1); + EXPECT_CALL(callbacks, SystemStateHandler(SystemState::Running)).Times(1); SetParticipantStatus(1, ParticipantState::Paused); EXPECT_EQ(monitor.ParticipantStatus("P1").state, ParticipantState::Paused); @@ -286,8 +289,7 @@ TEST_F(Test_SystemMonitor, detect_multiple_paused_clients) AddSystemStateHandler(); EXPECT_CALL(callbacks, SystemStateHandler(SystemState::Paused)).Times(1); - EXPECT_CALL(callbacks, SystemStateHandler(SystemState::Running)) - .Times(1); + EXPECT_CALL(callbacks, SystemStateHandler(SystemState::Running)).Times(1); SetParticipantStatus(1, ParticipantState::Paused); EXPECT_EQ(monitor.ParticipantStatus("P1").state, ParticipantState::Paused); diff --git a/SilKit/source/services/orchestration/Test_TimeProvider.cpp b/SilKit/source/services/orchestration/Test_TimeProvider.cpp old mode 100755 new mode 100644 index 35d9d51c0..82946efd1 --- a/SilKit/source/services/orchestration/Test_TimeProvider.cpp +++ b/SilKit/source/services/orchestration/Test_TimeProvider.cpp @@ -38,35 +38,32 @@ using namespace SilKit::Services::Orchestration; TEST(Test_TimeProvider, check_time_provider_impls) { - TimeProvider timeProvider{}; - timeProvider.SetSynchronizeVirtualTime(true); - //Check default implementation is NoSync - ASSERT_EQ(timeProvider.TimeProviderName(), "NoSyncProvider"); + TimeProvider timeProvider{}; + timeProvider.SetSynchronizeVirtualTime(true); + //Check default implementation is NoSync + ASSERT_EQ(timeProvider.TimeProviderName(), "NoSyncProvider"); - timeProvider.ConfigureTimeProvider(TimeProviderKind::SyncTime); - ASSERT_EQ(timeProvider.TimeProviderName(), "SynchronizedVirtualTimeProvider"); + timeProvider.ConfigureTimeProvider(TimeProviderKind::SyncTime); + ASSERT_EQ(timeProvider.TimeProviderName(), "SynchronizedVirtualTimeProvider"); - timeProvider.ConfigureTimeProvider(TimeProviderKind::WallClock); - ASSERT_EQ(timeProvider.TimeProviderName(), "WallclockProvider"); + timeProvider.ConfigureTimeProvider(TimeProviderKind::WallClock); + ASSERT_EQ(timeProvider.TimeProviderName(), "WallclockProvider"); - // synchronized state must be kept, even after re-configuring - ASSERT_TRUE(timeProvider.IsSynchronizingVirtualTime()); + // synchronized state must be kept, even after re-configuring + ASSERT_TRUE(timeProvider.IsSynchronizingVirtualTime()); } TEST(Test_TimeProvider, check_handlers) { - TimeProvider timeProvider{}; - // handlers only work for ::SyncTime and ::WallClock - int invocationCount = 0; - timeProvider.ConfigureTimeProvider(TimeProviderKind::SyncTime); - auto handle = timeProvider.AddNextSimStepHandler([&invocationCount](auto, auto){ - invocationCount++; - }); - timeProvider.SetTime(1ms, 0ms); //implicitly invoke handler - timeProvider.RemoveNextSimStepHandler(handle); - - timeProvider.SetTime(2ms, 0ms); //implicitly invoke handler - ASSERT_EQ(invocationCount, 1) << "Only the first SetTime should trigger the handler"; - + TimeProvider timeProvider{}; + // handlers only work for ::SyncTime and ::WallClock + int invocationCount = 0; + timeProvider.ConfigureTimeProvider(TimeProviderKind::SyncTime); + auto handle = timeProvider.AddNextSimStepHandler([&invocationCount](auto, auto) { invocationCount++; }); + timeProvider.SetTime(1ms, 0ms); //implicitly invoke handler + timeProvider.RemoveNextSimStepHandler(handle); + + timeProvider.SetTime(2ms, 0ms); //implicitly invoke handler + ASSERT_EQ(invocationCount, 1) << "Only the first SetTime should trigger the handler"; } } // namespace diff --git a/SilKit/source/services/orchestration/Test_TimeSyncService.cpp b/SilKit/source/services/orchestration/Test_TimeSyncService.cpp old mode 100755 new mode 100644 index a2f6fede2..5924d792a --- a/SilKit/source/services/orchestration/Test_TimeSyncService.cpp +++ b/SilKit/source/services/orchestration/Test_TimeSyncService.cpp @@ -67,22 +67,22 @@ class Test_TimeSyncService : public testing::Test Test_TimeSyncService() { // this CTor calls CreateTimeSyncService implicitly - lifecycleService = - std::make_unique(&participant); + lifecycleService = std::make_unique(&participant); lifecycleService->SetLifecycleConfiguration(LifecycleConfiguration{OperationMode::Coordinated}); timeSyncService = std::make_unique(&participant, &timeProvider, healthCheckConfig, lifecycleService.get()); lifecycleService->SetTimeSyncService(timeSyncService.get()); } + protected: // Methods void PrepareLifecycle() { lifecycleService->SetTimeSyncActive(true); (void)lifecycleService->StartLifecycle(); - + // Add other participant to lookup timeSyncService->GetTimeConfiguration()->AddSynchronizedParticipant("P1"); - + // skip uninteresting states lifecycleService->NewSystemState(SystemState::ServicesCreated); lifecycleService->NewSystemState(SystemState::CommunicationInitializing); @@ -90,6 +90,7 @@ class Test_TimeSyncService : public testing::Test lifecycleService->NewSystemState(SystemState::ReadyToRun); lifecycleService->NewSystemState(SystemState::Running); } + protected: // ---------------------------------------- // Members @@ -107,35 +108,30 @@ class Test_TimeSyncService : public testing::Test TEST_F(Test_TimeSyncService, async_simtask_once_without_complete_call) { auto numAsyncTaskCalled{0}; - timeSyncService->SetSimulationStepHandlerAsync([&](auto, auto){ - numAsyncTaskCalled++; - }, 1ms); + timeSyncService->SetSimulationStepHandlerAsync([&](auto, auto) { numAsyncTaskCalled++; }, 1ms); PrepareLifecycle(); timeSyncService->ReceiveMsg(&endpoint, {0ms}); timeSyncService->ReceiveMsg(&endpoint, {1ms}); timeSyncService->ReceiveMsg(&endpoint, {2ms}); - ASSERT_EQ(numAsyncTaskCalled, 1) - << "SimulationStepHandlerAsync should only be called once" - << " until completed with a call to CompleteSimulationStep()."; + ASSERT_EQ(numAsyncTaskCalled, 1) << "SimulationStepHandlerAsync should only be called once" + << " until completed with a call to CompleteSimulationStep()."; } TEST_F(Test_TimeSyncService, async_simtask_complete_lockstep) { auto numAsyncTaskCalled{0}; - timeSyncService->SetSimulationStepHandlerAsync([&](auto, auto){ - numAsyncTaskCalled++; - }, 1ms); + timeSyncService->SetSimulationStepHandlerAsync([&](auto, auto) { numAsyncTaskCalled++; }, 1ms); PrepareLifecycle(); timeSyncService->ReceiveMsg(&endpoint, {0ms}); timeSyncService->CompleteSimulationStep(); - + timeSyncService->ReceiveMsg(&endpoint, {1ms}); timeSyncService->CompleteSimulationStep(); - + timeSyncService->ReceiveMsg(&endpoint, {2ms}); timeSyncService->CompleteSimulationStep(); ASSERT_EQ(numAsyncTaskCalled, 3) @@ -146,9 +142,7 @@ TEST_F(Test_TimeSyncService, async_simtask_mismatching_number_of_complete_calls) { // What happens when the User calls CompleteSimulationStep() multiple times? auto numAsyncTaskCalled{0}; - timeSyncService->SetSimulationStepHandlerAsync([&](auto, auto){ - numAsyncTaskCalled++; - }, 1ms); + timeSyncService->SetSimulationStepHandlerAsync([&](auto, auto) { numAsyncTaskCalled++; }, 1ms); PrepareLifecycle(); @@ -164,8 +158,7 @@ TEST_F(Test_TimeSyncService, async_simtask_mismatching_number_of_complete_calls) timeSyncService->CompleteSimulationStep(); timeSyncService->CompleteSimulationStep(); - ASSERT_EQ(numAsyncTaskCalled, 3) - << "Calling too many CompleteSimulationStep() should not wreak havoc"; + ASSERT_EQ(numAsyncTaskCalled, 3) << "Calling too many CompleteSimulationStep() should not wreak havoc"; } } // namespace diff --git a/SilKit/source/services/orchestration/Test_WatchDog.cpp b/SilKit/source/services/orchestration/Test_WatchDog.cpp index befa8400d..ef4754efb 100644 --- a/SilKit/source/services/orchestration/Test_WatchDog.cpp +++ b/SilKit/source/services/orchestration/Test_WatchDog.cpp @@ -92,7 +92,10 @@ class LimitedMockClock : public WatchDog::IClock } private: - auto GetLimit() const -> std::chrono::nanoseconds { return std::chrono::nanoseconds{_limitRep}; } + auto GetLimit() const -> std::chrono::nanoseconds + { + return std::chrono::nanoseconds{_limitRep}; + } private: std::atomic _limitRep; diff --git a/SilKit/source/services/orchestration/TimeConfiguration.cpp b/SilKit/source/services/orchestration/TimeConfiguration.cpp old mode 100755 new mode 100644 index 42405dda2..a5507a16b --- a/SilKit/source/services/orchestration/TimeConfiguration.cpp +++ b/SilKit/source/services/orchestration/TimeConfiguration.cpp @@ -26,7 +26,7 @@ namespace SilKit { namespace Services { namespace Orchestration { -TimeConfiguration::TimeConfiguration(Logging::ILogger* logger) +TimeConfiguration::TimeConfiguration(Logging::ILogger* logger) : _blocking(false) , _logger(logger) @@ -91,10 +91,11 @@ void TimeConfiguration::OnReceiveNextSimStep(const std::string& participantName, if (nextStep.timePoint < itOtherNextTask->second.timePoint) { - Logging::Error(_logger, - "Chonology error: Received NextSimTask from participant \'{}\' with lower timePoint {} than last " - "known timePoint {}", - participantName, nextStep.timePoint.count(), itOtherNextTask->second.timePoint.count()); + Logging::Error( + _logger, + "Chonology error: Received NextSimTask from participant \'{}\' with lower timePoint {} than last " + "known timePoint {}", + participantName, nextStep.timePoint.count(), itOtherNextTask->second.timePoint.count()); } _otherNextTasks.at(participantName) = std::move(nextStep); diff --git a/SilKit/source/services/orchestration/TimeProvider.cpp b/SilKit/source/services/orchestration/TimeProvider.cpp old mode 100755 new mode 100644 index 4784e1578..29a766553 --- a/SilKit/source/services/orchestration/TimeProvider.cpp +++ b/SilKit/source/services/orchestration/TimeProvider.cpp @@ -94,9 +94,7 @@ class WallclockProvider final : public ProviderBase void OnHandlerAdded() final { - _timer.WithPeriod(_tickPeriod, [this](const auto& now) { - NotifyListenerAboutTick(now, _tickPeriod); - }); + _timer.WithPeriod(_tickPeriod, [this](const auto& now) { NotifyListenerAboutTick(now, _tickPeriod); }); } auto Now() const -> std::chrono::nanoseconds override @@ -123,9 +121,7 @@ class NoSyncProvider final : public ProviderBase void OnHandlerAdded() override { - _timer.WithPeriod(_tickPeriod, [this](const auto& now) { - NotifyListenerAboutTick(now, _tickPeriod); - }); + _timer.WithPeriod(_tickPeriod, [this](const auto& now) { NotifyListenerAboutTick(now, _tickPeriod); }); } auto Now() const -> std::chrono::nanoseconds override @@ -197,7 +193,8 @@ void TimeProvider::ConfigureTimeProvider(Orchestration::TimeProviderKind timePro providerPtr = std::make_unique(static_cast(*this), 1ms); break; case Orchestration::TimeProviderKind::SyncTime: - providerPtr = std::make_unique(static_cast(*this)); + providerPtr = + std::make_unique(static_cast(*this)); break; default: break; diff --git a/SilKit/source/services/orchestration/TimeProvider.hpp b/SilKit/source/services/orchestration/TimeProvider.hpp old mode 100755 new mode 100644 index 2cd46e953..f12d423f2 --- a/SilKit/source/services/orchestration/TimeProvider.hpp +++ b/SilKit/source/services/orchestration/TimeProvider.hpp @@ -58,7 +58,9 @@ struct ITimeProviderImplListener virtual void OnTick(std::chrono::nanoseconds now, std::chrono::nanoseconds duration) = 0; }; -class TimeProvider : public ITimeProvider, private ITimeProviderImplListener +class TimeProvider + : public ITimeProvider + , private ITimeProviderImplListener { public: TimeProvider(); diff --git a/SilKit/source/services/orchestration/TimeSyncService.cpp b/SilKit/source/services/orchestration/TimeSyncService.cpp old mode 100755 new mode 100644 index b4dc0fd18..6ef63369c --- a/SilKit/source/services/orchestration/TimeSyncService.cpp +++ b/SilKit/source/services/orchestration/TimeSyncService.cpp @@ -65,7 +65,8 @@ struct UnsynchronizedPolicy : public ITimeSyncPolicy struct SynchronizedPolicy : public ITimeSyncPolicy { public: - SynchronizedPolicy(TimeSyncService& controller, Core::IParticipantInternal* participant, TimeConfiguration* configuration) + SynchronizedPolicy(TimeSyncService& controller, Core::IParticipantInternal* participant, + TimeConfiguration* configuration) : _controller(controller) , _participant(participant) , _configuration(configuration) @@ -85,16 +86,14 @@ struct SynchronizedPolicy : public ITimeSyncPolicy void RequestNextStep() override { - if (_controller.State() == ParticipantState::Running - && !_controller.StopRequested() - && !_controller.PauseRequested()) // ensure that calls to Stop()/Pause() in a SimTask won't send out a new step and eventually call the SimTask again + if (_controller.State() == ParticipantState::Running && !_controller.StopRequested() + && !_controller + .PauseRequested()) // ensure that calls to Stop()/Pause() in a SimTask won't send out a new step and eventually call the SimTask again { _controller.SendMsg(_configuration->NextSimStep()); // Bootstrap checked execution, in case there is no other participant. // Else, checked execution is initiated when we receive their NextSimTask messages. - _participant->ExecuteDeferred([this]() { - this->ProcessSimulationTimeUpdate(); - }); + _participant->ExecuteDeferred([this]() { this->ProcessSimulationTimeUpdate(); }); } } @@ -164,8 +163,9 @@ struct SynchronizedPolicy : public ITimeSyncPolicy } // Another coordinated participant has disconnected without gracefully shutting down - if (static_cast(_participant->GetLifecycleService())->GetOperationMode() == OperationMode::Coordinated && - _participant->GetSystemMonitor()->SystemState() == SystemState::Error) + if (static_cast(_participant->GetLifecycleService())->GetOperationMode() + == OperationMode::Coordinated + && _participant->GetSystemMonitor()->SystemState() == SystemState::Error) { return false; } @@ -179,7 +179,7 @@ struct SynchronizedPolicy : public ITimeSyncPolicy return true; } - void AdvanceTimeSimStepSync() + void AdvanceTimeSimStepSync() { AdvanceTimeAndExecuteSimStep(); @@ -191,7 +191,7 @@ struct SynchronizedPolicy : public ITimeSyncPolicy } } - void AdvanceTimeSimStepAsync() + void AdvanceTimeSimStepAsync() { // when running in Async mode, set the _isExecutingSimStep guard // which will be cleared in CompleteSimulationStep() @@ -211,8 +211,7 @@ struct SynchronizedPolicy : public ITimeSyncPolicy void AdvanceTimeAndExecuteSimStep() { - if (_controller.State() == ParticipantState::Paused || - _controller.State() == ParticipantState::Running) + if (_controller.State() == ParticipantState::Paused || _controller.State() == ParticipantState::Running) { if (_configuration->HandleHopOn()) { @@ -248,7 +247,7 @@ TimeSyncService::TimeSyncService(Core::IParticipantInternal* participant, ITimeP { _watchDog.SetWarnHandler([logger = _logger](std::chrono::milliseconds timeout) { Warn(logger, "SimStep did not finish within soft time limit. Timeout detected after {} ms", - std::chrono::duration_cast>(timeout).count()); + std::chrono::duration_cast>(timeout).count()); }); _watchDog.SetErrorHandler([this](std::chrono::milliseconds timeout) { std::stringstream buffer; @@ -261,71 +260,74 @@ TimeSyncService::TimeSyncService(Core::IParticipantInternal* participant, ITimeP participant->GetServiceDiscovery()->RegisterServiceDiscoveryHandler( [&](auto discoveryEventType, const Core::ServiceDescriptor& descriptor) { - if (descriptor.GetServiceType() == Core::ServiceType::InternalController) + if (descriptor.GetServiceType() == Core::ServiceType::InternalController) + { + std::string controllerType; + descriptor.GetSupplementalDataItem(Core::Discovery::controllerType, controllerType); + if (controllerType == Core::Discovery::controllerTypeTimeSyncService) { - std::string controllerType; - descriptor.GetSupplementalDataItem(Core::Discovery::controllerType, controllerType); - if (controllerType == Core::Discovery::controllerTypeTimeSyncService) + auto descriptorParticipantName = descriptor.GetParticipantName(); + if (descriptorParticipantName == _participant->GetParticipantName()) { - auto descriptorParticipantName = descriptor.GetParticipantName(); - if (descriptorParticipantName == _participant->GetParticipantName()) - { - // ignore self - return; - } + // ignore self + return; + } - std::string timeSyncActive; - descriptor.GetSupplementalDataItem(Core::Discovery::timeSyncActive, timeSyncActive); - if (timeSyncActive == "1") + std::string timeSyncActive; + descriptor.GetSupplementalDataItem(Core::Discovery::timeSyncActive, timeSyncActive); + if (timeSyncActive == "1") + { + if (discoveryEventType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated) { - if (discoveryEventType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated) + // Check capabilities of newly discovered participants. + // This might happen before TimeSyncService and LifecycleService are finally configured, + // so this check happens also in TimeSyncService::StartTime() + if (!ParticipantHasAutonomousSynchronousCapability(descriptorParticipantName)) { - // Check capabilities of newly discovered participants. - // This might happen before TimeSyncService and LifecycleService are finally configured, - // so this check happens also in TimeSyncService::StartTime() - if (!ParticipantHasAutonomousSynchronousCapability(descriptorParticipantName)) - { - _participant->GetSystemController()->AbortSimulation(); - return; - } + _participant->GetSystemController()->AbortSimulation(); + return; + } - Debug(_participant->GetLogger(), "TimeSyncService: Participant \'{}\' is added to the distributed time synchronization", - descriptorParticipantName); + Debug(_participant->GetLogger(), + "TimeSyncService: Participant \'{}\' is added to the distributed time synchronization", + descriptorParticipantName); - _timeConfiguration.AddSynchronizedParticipant(descriptorParticipantName); + _timeConfiguration.AddSynchronizedParticipant(descriptorParticipantName); - // If our time has advanced, we just added a late-joining participant. - if (_timeConfiguration.CurrentSimStep().timePoint >= 0ns) - { - // Resend our NextSimTask again because it is not assured that the late-joiner has seen our last update. - // At this point, the late-joiner will receive it because its TimeSyncPolicy is configured when the - // discovery arrives that triggered this handler. - Debug(_participant->GetLogger(), "Participant \'{}\' is joining an already running simulation. Resending our NextSimTask.", - descriptorParticipantName); - SendMsg(_timeConfiguration.NextSimStep()); - } + // If our time has advanced, we just added a late-joining participant. + if (_timeConfiguration.CurrentSimStep().timePoint >= 0ns) + { + // Resend our NextSimTask again because it is not assured that the late-joiner has seen our last update. + // At this point, the late-joiner will receive it because its TimeSyncPolicy is configured when the + // discovery arrives that triggered this handler. + Debug(_participant->GetLogger(), + "Participant \'{}\' is joining an already running simulation. Resending our " + "NextSimTask.", + descriptorParticipantName); + SendMsg(_timeConfiguration.NextSimStep()); } - else if (discoveryEventType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved) + } + else if (discoveryEventType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved) + { + // Other participant hopped off + if (_timeConfiguration.RemoveSynchronizedParticipant(descriptorParticipantName)) { - // Other participant hopped off - if (_timeConfiguration.RemoveSynchronizedParticipant(descriptorParticipantName)) + Debug(_logger, + "TimeSyncService: Participant '{}' is no longer part of the " + "distributed time synchronization.", + descriptorParticipantName); + + if (_timeSyncPolicy) { - Debug(_logger, - "TimeSyncService: Participant '{}' is no longer part of the " - "distributed time synchronization.", - descriptorParticipantName); - - if (_timeSyncPolicy) - { - // _otherNextTasks has changed, check if our sim task is due - GetTimeSyncPolicy()->ProcessSimulationTimeUpdate(); - } + // _otherNextTasks has changed, check if our sim task is due + GetTimeSyncPolicy()->ProcessSimulationTimeUpdate(); } } } } } - }); + } + }); } bool TimeSyncService::IsSynchronizingVirtualTime() @@ -347,11 +349,9 @@ auto TimeSyncService::PauseRequested() const -> bool return _lifecycleService->PauseRequested(); } -void TimeSyncService::RequestNextStep() +void TimeSyncService::RequestNextStep() { - _participant->ExecuteDeferred([this] { - GetTimeSyncPolicy()->RequestNextStep(); - }); + _participant->ExecuteDeferred([this] { GetTimeSyncPolicy()->RequestNextStep(); }); } void TimeSyncService::SetSimulationStepHandler(SimulationStepHandler task, std::chrono::nanoseconds initialStepSize) @@ -361,7 +361,8 @@ void TimeSyncService::SetSimulationStepHandler(SimulationStepHandler task, std:: _timeConfiguration.SetStepDuration(initialStepSize); } -void TimeSyncService::SetSimulationStepHandlerAsync(SimulationStepHandler task, std::chrono::nanoseconds initialStepSize) +void TimeSyncService::SetSimulationStepHandlerAsync(SimulationStepHandler task, + std::chrono::nanoseconds initialStepSize) { _simTask = std::move(task); _timeConfiguration.SetBlockingMode(false); @@ -402,10 +403,10 @@ void TimeSyncService::ReceiveMsg(const IServiceEndpoint* from, const NextSimTask { timeSyncPolicy->ReceiveNextSimTask(from, task); } - else + else { Logging::Debug(_logger, "Received NextSimTask from participant \'{}\' but TimeSyncPolicy is not yet configured", - from->GetServiceDescriptor().GetParticipantName()); + from->GetServiceDescriptor().GetParticipantName()); } } @@ -416,7 +417,7 @@ void TimeSyncService::ExecuteSimStep(std::chrono::nanoseconds timePoint, std::ch _waitTimeMonitor.StopMeasurement(); Trace(_logger, "Starting next Simulation Task. Waiting time was: {}ms", - std::chrono::duration_cast(_waitTimeMonitor.CurrentDuration()).count()); + std::chrono::duration_cast(_waitTimeMonitor.CurrentDuration()).count()); _timeProvider->SetTime(timePoint, duration); @@ -427,7 +428,7 @@ void TimeSyncService::ExecuteSimStep(std::chrono::nanoseconds timePoint, std::ch _execTimeMonitor.StopMeasurement(); Trace(_logger, "Finished Simulation Step. Execution time was: {}ms", - std::chrono::duration_cast(_execTimeMonitor.CurrentDuration()).count()); + std::chrono::duration_cast(_execTimeMonitor.CurrentDuration()).count()); _waitTimeMonitor.StartMeasurement(); } @@ -455,7 +456,8 @@ void TimeSyncService::InitializeTimeSyncPolicy(bool isSynchronizingVirtualTime) return; } - _serviceDescriptor.SetSupplementalDataItem(SilKit::Core::Discovery::timeSyncActive, (isSynchronizingVirtualTime) ? "1" : "0"); + _serviceDescriptor.SetSupplementalDataItem(SilKit::Core::Discovery::timeSyncActive, + (isSynchronizingVirtualTime) ? "1" : "0"); ResetTime(); } catch (const std::exception& e) @@ -489,7 +491,7 @@ void TimeSyncService::StartTime() { if (!ParticipantHasAutonomousSynchronousCapability(participantName)) { - missingCapability = true; + missingCapability = true; } } if (missingCapability) @@ -514,9 +516,9 @@ auto TimeSyncService::GetTimeConfiguration() -> TimeConfiguration* bool TimeSyncService::ParticipantHasAutonomousSynchronousCapability(const std::string& participantName) const { - if ( _lifecycleService && _lifecycleService->GetOperationMode() == OperationMode::Autonomous && - _lifecycleService->IsTimeSyncActive() && - !_participant->ParticipantHasCapability(participantName, SilKit::Core::Capabilities::AutonomousSynchronous)) + if (_lifecycleService && _lifecycleService->GetOperationMode() == OperationMode::Autonomous + && _lifecycleService->IsTimeSyncActive() + && !_participant->ParticipantHasCapability(participantName, SilKit::Core::Capabilities::AutonomousSynchronous)) { // We are a participant with autonomous lifecycle and virtual time sync. // The remote participant must support this, otherwise Hop-On / Hop-Off will fail. diff --git a/SilKit/source/services/orchestration/TimeSyncService.hpp b/SilKit/source/services/orchestration/TimeSyncService.hpp old mode 100755 new mode 100644 index df605d7b7..a4afac4ba --- a/SilKit/source/services/orchestration/TimeSyncService.hpp +++ b/SilKit/source/services/orchestration/TimeSyncService.hpp @@ -111,7 +111,7 @@ class TimeSyncService //! assigned before. bool SetupTimeSyncPolicy(bool isSynchronizingVirtualTime); - inline auto GetTimeSyncPolicy() const -> ITimeSyncPolicy *; + inline auto GetTimeSyncPolicy() const -> ITimeSyncPolicy*; private: // ---------------------------------------- @@ -138,7 +138,6 @@ class TimeSyncService Util::PerformanceMonitor _execTimeMonitor; Util::PerformanceMonitor _waitTimeMonitor; WatchDog _watchDog; - }; // ================================================================================ diff --git a/SilKit/source/services/pubsub/DataPublisher.cpp b/SilKit/source/services/pubsub/DataPublisher.cpp index 189b9c71d..b64af2443 100644 --- a/SilKit/source/services/pubsub/DataPublisher.cpp +++ b/SilKit/source/services/pubsub/DataPublisher.cpp @@ -31,10 +31,8 @@ namespace PubSub { DataPublisher::DataPublisher(Core::IParticipantInternal* participant, Services::Orchestration::ITimeProvider* timeProvider, - const SilKit::Services::PubSub::PubSubSpec& dataSpec, - const std::string& pubUUID, - const Config::DataPublisher& config -) + const SilKit::Services::PubSub::PubSubSpec& dataSpec, const std::string& pubUUID, + const Config::DataPublisher& config) : _topic{dataSpec.Topic()} , _mediaType{dataSpec.MediaType()} , _labels{dataSpec.Labels()} @@ -76,7 +74,7 @@ void DataPublisher::ReplayMessage(const SilKit::IReplayMessage* message) case SilKit::Services::TransmitDirection::RX: break; default: - throw SilKitError("CanController: replay message has undefined Direction"); + throw SilKitError("DataPublisher: replay message has undefined Direction"); break; } } diff --git a/SilKit/source/services/pubsub/DataPublisher.hpp b/SilKit/source/services/pubsub/DataPublisher.hpp index 3df78b2ad..a9ede6969 100644 --- a/SilKit/source/services/pubsub/DataPublisher.hpp +++ b/SilKit/source/services/pubsub/DataPublisher.hpp @@ -44,12 +44,9 @@ class DataPublisher , public Tracing::IReplayDataController { public: - DataPublisher(Core::IParticipantInternal* participant, - Services::Orchestration::ITimeProvider* timeProvider, - const SilKit::Services::PubSub::PubSubSpec& dataSpec, - const std::string& pubUUID, - const Config::DataPublisher& config - ); + DataPublisher(Core::IParticipantInternal* participant, Services::Orchestration::ITimeProvider* timeProvider, + const SilKit::Services::PubSub::PubSubSpec& dataSpec, const std::string& pubUUID, + const Config::DataPublisher& config); public: // Methods @@ -60,7 +57,7 @@ class DataPublisher // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; //ITraceMessageSource inline void AddSink(ITraceMessageSink* sink, SilKit::Config::NetworkType networkType) override; @@ -68,7 +65,8 @@ class DataPublisher auto GetTracer() -> Tracer*; // IReplayDataController - void ReplayMessage(const SilKit::IReplayMessage *message) override; + void ReplayMessage(const SilKit::IReplayMessage* message) override; + private: // Methods void PublishInternal(Util::Span data); diff --git a/SilKit/source/services/pubsub/DataSerdes.cpp b/SilKit/source/services/pubsub/DataSerdes.cpp index 3bfcff25d..5cb51f1ee 100644 --- a/SilKit/source/services/pubsub/DataSerdes.cpp +++ b/SilKit/source/services/pubsub/DataSerdes.cpp @@ -27,15 +27,13 @@ namespace PubSub { inline SilKit::Core::MessageBuffer& operator<<(SilKit::Core::MessageBuffer& buffer, const WireDataMessageEvent& msg) { - buffer << msg.data - << msg.timestamp; + buffer << msg.data << msg.timestamp; return buffer; } inline SilKit::Core::MessageBuffer& operator>>(SilKit::Core::MessageBuffer& buffer, WireDataMessageEvent& msg) { - buffer >> msg.data - >> msg.timestamp; + buffer >> msg.data >> msg.timestamp; return buffer; } @@ -50,6 +48,6 @@ void Deserialize(SilKit::Core::MessageBuffer& buffer, WireDataMessageEvent& out) buffer >> out; } -} // namespace PubSub +} // namespace PubSub } // namespace Services } // namespace SilKit diff --git a/SilKit/source/services/pubsub/DataSerdes.hpp b/SilKit/source/services/pubsub/DataSerdes.hpp index a3a10ee7a..3fed2ecc9 100644 --- a/SilKit/source/services/pubsub/DataSerdes.hpp +++ b/SilKit/source/services/pubsub/DataSerdes.hpp @@ -33,6 +33,6 @@ namespace PubSub { void Serialize(SilKit::Core::MessageBuffer& buffer, const WireDataMessageEvent& msg); void Deserialize(SilKit::Core::MessageBuffer& buffer, WireDataMessageEvent& out); -} // namespace PubSub +} // namespace PubSub } // namespace Services } // namespace SilKit diff --git a/SilKit/source/services/pubsub/DataSubscriber.cpp b/SilKit/source/services/pubsub/DataSubscriber.cpp index 19f950122..22c8ee267 100644 --- a/SilKit/source/services/pubsub/DataSubscriber.cpp +++ b/SilKit/source/services/pubsub/DataSubscriber.cpp @@ -39,7 +39,7 @@ DataSubscriber::DataSubscriber(Core::IParticipantInternal* participant, Config:: , _labels{dataSpec.Labels()} , _defaultDataHandler{WrapTracingCallback(defaultDataHandler)} , _timeProvider{timeProvider} - , _participant{ participant } + , _participant{participant} , _config{std::move(config)} { } @@ -113,7 +113,7 @@ void DataSubscriber::AddInternalSubscriber(const std::string& pubUUID, const std { auto internalSubscriber = dynamic_cast(_participant->CreateDataSubscriberInternal( _topic, pubUUID, joinedMediaType, publisherLabels, _defaultDataHandler, this)); - + _internalSubscribers.emplace(pubUUID, internalSubscriber); } @@ -127,10 +127,9 @@ void DataSubscriber::RemoveInternalSubscriber(const std::string& pubUUID) } } - auto DataSubscriber::WrapTracingCallback(DataMessageHandler callback) -> - SilKit::Services::PubSub::DataMessageHandler +auto DataSubscriber::WrapTracingCallback(DataMessageHandler callback) -> SilKit::Services::PubSub::DataMessageHandler { - auto tracingCallback = [this, callback=std::move(callback)](auto&& service, auto&& message) { + auto tracingCallback = [this, callback = std::move(callback)](auto&& service, auto&& message) { _tracer.Trace(TransmitDirection::RX, _timeProvider->Now(), message); if (callback) { diff --git a/SilKit/source/services/pubsub/DataSubscriber.hpp b/SilKit/source/services/pubsub/DataSubscriber.hpp index 44b12133e..ee0c897de 100644 --- a/SilKit/source/services/pubsub/DataSubscriber.hpp +++ b/SilKit/source/services/pubsub/DataSubscriber.hpp @@ -46,9 +46,9 @@ class DataSubscriber , public ITraceMessageSource { public: - DataSubscriber(Core::IParticipantInternal* participant, Config::DataSubscriber config, Services::Orchestration::ITimeProvider* timeProvider, - const SilKit::Services::PubSub::PubSubSpec& dataSpec, - DataMessageHandler defaultDataHandler); + DataSubscriber(Core::IParticipantInternal* participant, Config::DataSubscriber config, + Services::Orchestration::ITimeProvider* timeProvider, + const SilKit::Services::PubSub::PubSubSpec& dataSpec, DataMessageHandler defaultDataHandler); public: //methods void RegisterServiceDiscovery(); @@ -56,10 +56,10 @@ class DataSubscriber // SilKit::Services::Orchestration::ITimeConsumer inline void SetTimeProvider(Services::Orchestration::ITimeProvider* provider) override; - + // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; //ITraceMessageSource @@ -73,11 +73,12 @@ class DataSubscriber private: //methods void AddInternalSubscriber(const std::string& pubUUID, const std::string& joinedMediaType, - const std::vector& publisherLabels); + const std::vector& publisherLabels); void RemoveInternalSubscriber(const std::string& pubUUID); DataMessageHandler WrapTracingCallback(DataMessageHandler callback); + private: //members std::string _topic; std::string _mediaType; diff --git a/SilKit/source/services/pubsub/DataSubscriberInternal.cpp b/SilKit/source/services/pubsub/DataSubscriberInternal.cpp index 07f2126c1..ed7a56773 100644 --- a/SilKit/source/services/pubsub/DataSubscriberInternal.cpp +++ b/SilKit/source/services/pubsub/DataSubscriberInternal.cpp @@ -28,7 +28,8 @@ namespace SilKit { namespace Services { namespace PubSub { -DataSubscriberInternal::DataSubscriberInternal(Core::IParticipantInternal* participant, Services::Orchestration::ITimeProvider* timeProvider, +DataSubscriberInternal::DataSubscriberInternal(Core::IParticipantInternal* participant, + Services::Orchestration::ITimeProvider* timeProvider, const std::string& topic, const std::string& mediaType, const std::vector& labels, DataMessageHandler defaultHandler, IDataSubscriber* parent) @@ -65,7 +66,6 @@ void DataSubscriberInternal::ReceiveMsg(const IServiceEndpoint* /*from*/, const void DataSubscriberInternal::ReceiveInternal(const WireDataMessageEvent& dataMessageEvent) { - if (_defaultHandler) { _defaultHandler(_parent, ToDataMessageEvent(dataMessageEvent)); @@ -73,7 +73,8 @@ void DataSubscriberInternal::ReceiveInternal(const WireDataMessageEvent& dataMes if (!_defaultHandler) { - _participant->GetLogger()->Warn("DataSubscriber on topic " + _topic + " received data, but has no default handler assigned"); + _participant->GetLogger()->Warn("DataSubscriber on topic " + _topic + + " received data, but has no default handler assigned"); } } @@ -98,7 +99,7 @@ void DataSubscriberInternal::ReplayMessage(const IReplayMessage* message) //Ignore transmit messages break; default: - throw SilKitError("DataSubscriberInternal: replay message has undefined direction"); + throw SilKitError("DataSubscriber: replay message has undefined direction"); break; } } diff --git a/SilKit/source/services/pubsub/DataSubscriberInternal.hpp b/SilKit/source/services/pubsub/DataSubscriberInternal.hpp index d11b08c2c..76ddc69ac 100644 --- a/SilKit/source/services/pubsub/DataSubscriberInternal.hpp +++ b/SilKit/source/services/pubsub/DataSubscriberInternal.hpp @@ -43,36 +43,42 @@ class DataSubscriberInternal DataSubscriberInternal(Core::IParticipantInternal* participant, Services::Orchestration::ITimeProvider* timeProvider, const std::string& topic, const std::string& mediaType, const std::vector& labels, - DataMessageHandler defaultHandler, - IDataSubscriber* parent); + DataMessageHandler defaultHandler, IDataSubscriber* parent); public: //Methods void SetDataMessageHandler(DataMessageHandler handler); - + //! \brief Accepts messages originating from SilKit communications. void ReceiveMsg(const IServiceEndpoint* from, const WireDataMessageEvent& dataMessageEvent) override; //SilKit::Services::Orchestration::ITimeConsumer void SetTimeProvider(Services::Orchestration::ITimeProvider* provider) override; - std::string GetMediaType() { return _mediaType; }; - auto GetLabels() -> const std::vector& { return _labels; }; + std::string GetMediaType() + { + return _mediaType; + }; + auto GetLabels() -> const std::vector& + { + return _labels; + }; // IServiceEndpoint inline void SetServiceDescriptor(const Core::ServiceDescriptor& serviceDescriptor) override; - inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor & override; + inline auto GetServiceDescriptor() const -> const Core::ServiceDescriptor& override; // IReplayDataProvider void ReplayMessage(const IReplayMessage* replayMessage) override; private: //Methods void ReceiveInternal(const WireDataMessageEvent& dataMessageEvent); + private: // Member std::string _topic; std::string _mediaType; std::vector _labels; DataMessageHandler _defaultHandler; - + Config::Replay _replayConfig; IDataSubscriber* _parent{nullptr}; diff --git a/SilKit/source/services/pubsub/IMsgForDataPublisher.hpp b/SilKit/source/services/pubsub/IMsgForDataPublisher.hpp index 22d93b629..c988f33b2 100644 --- a/SilKit/source/services/pubsub/IMsgForDataPublisher.hpp +++ b/SilKit/source/services/pubsub/IMsgForDataPublisher.hpp @@ -41,4 +41,3 @@ class IMsgForDataPublisher } // namespace PubSub } // namespace Services } // namespace SilKit - diff --git a/SilKit/source/services/pubsub/IMsgForDataSubscriber.hpp b/SilKit/source/services/pubsub/IMsgForDataSubscriber.hpp index a829330c1..4da2c75ae 100644 --- a/SilKit/source/services/pubsub/IMsgForDataSubscriber.hpp +++ b/SilKit/source/services/pubsub/IMsgForDataSubscriber.hpp @@ -40,4 +40,3 @@ class IMsgForDataSubscriber } // namespace PubSub } // namespace Services } // namespace SilKit - diff --git a/SilKit/source/services/pubsub/IMsgForDataSubscriberInternal.hpp b/SilKit/source/services/pubsub/IMsgForDataSubscriberInternal.hpp index 30e558258..70daebe90 100644 --- a/SilKit/source/services/pubsub/IMsgForDataSubscriberInternal.hpp +++ b/SilKit/source/services/pubsub/IMsgForDataSubscriberInternal.hpp @@ -41,4 +41,3 @@ class IMsgForDataSubscriberInternal } // namespace PubSub } // namespace Services } // namespace SilKit - diff --git a/SilKit/source/services/pubsub/Test_DataPublisher.cpp b/SilKit/source/services/pubsub/Test_DataPublisher.cpp index 999c4dc2a..71a83b9ce 100644 --- a/SilKit/source/services/pubsub/Test_DataPublisher.cpp +++ b/SilKit/source/services/pubsub/Test_DataPublisher.cpp @@ -53,13 +53,13 @@ class Test_DataPublisher : public ::testing::Test { protected: Test_DataPublisher() - : publisher{ &participant, participant.GetTimeProvider(), testDataNodeSpec, "pubUUID", {} } + : publisher{&participant, participant.GetTimeProvider(), testDataNodeSpec, "pubUUID", {}} { publisher.SetServiceDescriptor(portAddress); } protected: - const ServiceDescriptor portAddress{ "P1", "N1", "C1", 5}; + const ServiceDescriptor portAddress{"P1", "N1", "C1", 5}; const std::vector sampleData{0u, 1u, 2u, 3u, 4u, 5u, 6u, 7u}; MockParticipant participant; @@ -70,8 +70,7 @@ TEST_F(Test_DataPublisher, publish) { WireDataMessageEvent msg{0ns, sampleData}; - EXPECT_CALL(participant, SendMsg(&publisher, msg)) - .Times(1); + EXPECT_CALL(participant, SendMsg(&publisher, msg)).Times(1); publisher.Publish(sampleData); } diff --git a/SilKit/source/services/pubsub/Test_DataSerdes.cpp b/SilKit/source/services/pubsub/Test_DataSerdes.cpp index 32c224b1e..966fb54d2 100644 --- a/SilKit/source/services/pubsub/Test_DataSerdes.cpp +++ b/SilKit/source/services/pubsub/Test_DataSerdes.cpp @@ -30,14 +30,13 @@ using namespace std::chrono_literals; namespace SilKit { namespace Services { namespace PubSub { - static bool operator==(const WireDataMessageEvent& lhs, const WireDataMessageEvent& rhs) - { - return Util::ItemsAreEqual(lhs.data, rhs.data) - && lhs.timestamp == rhs.timestamp; - } -} -} +static bool operator==(const WireDataMessageEvent& lhs, const WireDataMessageEvent& rhs) +{ + return Util::ItemsAreEqual(lhs.data, rhs.data) && lhs.timestamp == rhs.timestamp; } +} // namespace PubSub +} // namespace Services +} // namespace SilKit TEST(Test_DataSerdes, SimData_LargeDataMessage) { using namespace SilKit::Services::PubSub; @@ -46,12 +45,11 @@ TEST(Test_DataSerdes, SimData_LargeDataMessage) const std::vector referenceData(114'793, 'D'); SilKit::Core::MessageBuffer buffer; SilKit::Services::PubSub::WireDataMessageEvent in, out; - in.data = {1,2,3,4}; + in.data = {1, 2, 3, 4}; in.timestamp = 0xabcdefns; - Serialize(buffer, in); + Serialize(buffer, in); Deserialize(buffer, out); EXPECT_EQ(in, out); } - diff --git a/SilKit/source/services/pubsub/Test_DataSubscriber.cpp b/SilKit/source/services/pubsub/Test_DataSubscriber.cpp index dea5c0061..ce0480813 100644 --- a/SilKit/source/services/pubsub/Test_DataSubscriber.cpp +++ b/SilKit/source/services/pubsub/Test_DataSubscriber.cpp @@ -69,9 +69,10 @@ class Test_DataSubscriber : public ::testing::Test Test_DataSubscriber() : subscriber{&participant, {}, - participant.GetTimeProvider(), matchingDataSpec, + participant.GetTimeProvider(), + matchingDataSpec, SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveDataDefault)} - , publisher{ &participant, participant.GetTimeProvider(), dataSpec, publisherUuid,{} } + , publisher{&participant, participant.GetTimeProvider(), dataSpec, publisherUuid, {}} { subscriber.SetServiceDescriptor(subscriberDescriptor); SetupPublisherServiceDescriptor(publisher, publisherUuid); @@ -82,8 +83,7 @@ class Test_DataSubscriber : public ::testing::Test { publisherDescriptor.SetSupplementalDataItem(Core::Discovery::supplKeyDataPublisherTopic, topic); publisherDescriptor.SetSupplementalDataItem(Core::Discovery::supplKeyDataPublisherMediaType, mediaType); - publisherDescriptor.SetSupplementalDataItem(Core::Discovery::supplKeyDataPublisherPubLabels, - labelsSerialized); + publisherDescriptor.SetSupplementalDataItem(Core::Discovery::supplKeyDataPublisherPubLabels, labelsSerialized); publisherDescriptor.SetSupplementalDataItem(Core::Discovery::supplKeyDataPublisherPubUUID, uuid); dataPublisher.SetServiceDescriptor(publisherDescriptor); } diff --git a/SilKit/source/services/pubsub/Test_DataSubscriberInternal.cpp b/SilKit/source/services/pubsub/Test_DataSubscriberInternal.cpp index ae1ff9426..dfc3a91b1 100644 --- a/SilKit/source/services/pubsub/Test_DataSubscriberInternal.cpp +++ b/SilKit/source/services/pubsub/Test_DataSubscriberInternal.cpp @@ -62,8 +62,8 @@ class Test_DataSubscriberInternal : public ::testing::Test } protected: - const ServiceDescriptor endpointAddress{ "P1", "N1", "C1" , 5}; - const ServiceDescriptor otherEndpointAddress{ "P2", "N1", "C3", 7 }; + const ServiceDescriptor endpointAddress{"P1", "N1", "C1", 5}; + const ServiceDescriptor otherEndpointAddress{"P2", "N1", "C3", 7}; SilKit::Core::Tests::DummyParticipant participant; Callbacks callbacks; diff --git a/SilKit/source/services/rpc/IMsgForRpcClient.hpp b/SilKit/source/services/rpc/IMsgForRpcClient.hpp index 8b0e600b9..a1c330c43 100644 --- a/SilKit/source/services/rpc/IMsgForRpcClient.hpp +++ b/SilKit/source/services/rpc/IMsgForRpcClient.hpp @@ -43,4 +43,3 @@ class IMsgForRpcClient } // namespace Rpc } // namespace Services } // namespace SilKit - diff --git a/SilKit/source/services/rpc/IMsgForRpcServer.hpp b/SilKit/source/services/rpc/IMsgForRpcServer.hpp index 926ab924e..702f65809 100644 --- a/SilKit/source/services/rpc/IMsgForRpcServer.hpp +++ b/SilKit/source/services/rpc/IMsgForRpcServer.hpp @@ -42,4 +42,3 @@ class IMsgForRpcServer } // namespace Rpc } // namespace Services } // namespace SilKit - diff --git a/SilKit/source/services/rpc/IMsgForRpcServerInternal.hpp b/SilKit/source/services/rpc/IMsgForRpcServerInternal.hpp index 4fad4446b..5a22f2cca 100644 --- a/SilKit/source/services/rpc/IMsgForRpcServerInternal.hpp +++ b/SilKit/source/services/rpc/IMsgForRpcServerInternal.hpp @@ -42,4 +42,3 @@ class IMsgForRpcServerInternal } // namespace Rpc } // namespace Services } // namespace SilKit - diff --git a/SilKit/source/services/rpc/RpcCallHandle.hpp b/SilKit/source/services/rpc/RpcCallHandle.hpp index 63dbf9ef7..ea33d23bd 100644 --- a/SilKit/source/services/rpc/RpcCallHandle.hpp +++ b/SilKit/source/services/rpc/RpcCallHandle.hpp @@ -45,7 +45,10 @@ class RpcCallHandle : public IRpcCallHandle { } - auto GetCallUuid() const -> const Util::Uuid& { return _callUuid; } + auto GetCallUuid() const -> const Util::Uuid& + { + return _callUuid; + } private: Util::Uuid _callUuid{}; diff --git a/SilKit/source/services/rpc/RpcClient.cpp b/SilKit/source/services/rpc/RpcClient.cpp index f27b6ddf6..0ad7b9d2b 100644 --- a/SilKit/source/services/rpc/RpcClient.cpp +++ b/SilKit/source/services/rpc/RpcClient.cpp @@ -37,8 +37,10 @@ auto ToRpcCallStatus(const FunctionCallResponse::Status status) -> RpcCallStatus { switch (status) { - case FunctionCallResponse::Status::Success: return RpcCallStatus::Success; - case FunctionCallResponse::Status::InternalError: return RpcCallStatus::InternalServerError; + case FunctionCallResponse::Status::Success: + return RpcCallStatus::Success; + case FunctionCallResponse::Status::InternalError: + return RpcCallStatus::InternalServerError; } return RpcCallStatus::UndefinedError; @@ -153,7 +155,8 @@ void RpcClient::TimeHandler(std::chrono::nanoseconds now, std::chrono::nanosecon } -void RpcClient::TriggerCall(Util::Span data, bool hasTimeout, std::chrono::nanoseconds timeout, void* userContext) +void RpcClient::TriggerCall(Util::Span data, bool hasTimeout, std::chrono::nanoseconds timeout, + void* userContext) { if (_numCounterparts == 0) { @@ -186,8 +189,8 @@ void RpcClient::TriggerCall(Util::Span data, bool hasTimeout, std { _timeoutHandlerId = _timeProvider->AddNextSimStepHandler( [this](std::chrono::nanoseconds now, std::chrono::nanoseconds duration) { - this->TimeHandler(now, duration); - }); + this->TimeHandler(now, duration); + }); _isTimeoutHandlerSet = true; } } @@ -217,7 +220,8 @@ void RpcClient::ReceiveMessage(const FunctionCallResponse& msg) if (it == _activeCalls.end()) { - std::string warningMsg{"RpcClient: Received function call response with an unknown/deleted uuid. Might be a call reply that ran into a timeout."}; + std::string warningMsg{"RpcClient: Received function call response with an unknown/deleted uuid. Might be " + "a call reply that ran into a timeout."}; _logger->Warn(warningMsg); return; } diff --git a/SilKit/source/services/rpc/RpcClient.hpp b/SilKit/source/services/rpc/RpcClient.hpp index abb1c85c4..275ea5e08 100644 --- a/SilKit/source/services/rpc/RpcClient.hpp +++ b/SilKit/source/services/rpc/RpcClient.hpp @@ -75,7 +75,7 @@ class RpcClient private: void TriggerCall(Util::Span data, bool hasTimeout, std::chrono::nanoseconds timeout, - void* userContext); + void* userContext); void TimeHandler(std::chrono::nanoseconds now, std::chrono::nanoseconds duration); class RpcCallInfo @@ -87,9 +87,15 @@ class RpcClient { } - auto DecrementRemainingReturnCount() -> int32_t { return --_remainingReturnCount; } + auto DecrementRemainingReturnCount() -> int32_t + { + return --_remainingReturnCount; + } - auto GetUserContext() const -> void* { return _userContext; } + auto GetUserContext() const -> void* + { + return _userContext; + } private: int32_t _remainingReturnCount = 0; @@ -122,7 +128,7 @@ class RpcClient std::vector _timeoutEntries{}; std::function _timeoutHandler{}; Services::HandlerId _timeoutHandlerId{}; - std::atomic _isTimeoutHandlerSet{ false }; + std::atomic _isTimeoutHandlerSet{false}; }; // ================================================================================ diff --git a/SilKit/source/services/rpc/RpcSerdes.hpp b/SilKit/source/services/rpc/RpcSerdes.hpp index 71217c954..4f6b39c12 100644 --- a/SilKit/source/services/rpc/RpcSerdes.hpp +++ b/SilKit/source/services/rpc/RpcSerdes.hpp @@ -30,8 +30,8 @@ namespace SilKit { namespace Services { namespace Rpc { -void Serialize(SilKit::Core::MessageBuffer& buffer,const FunctionCall& msg); -void Serialize(SilKit::Core::MessageBuffer& buffer,const FunctionCallResponse& msg); +void Serialize(SilKit::Core::MessageBuffer& buffer, const FunctionCall& msg); +void Serialize(SilKit::Core::MessageBuffer& buffer, const FunctionCallResponse& msg); void Deserialize(SilKit::Core::MessageBuffer& buffer, FunctionCall& out); void Deserialize(SilKit::Core::MessageBuffer& buffer, FunctionCallResponse& out); diff --git a/SilKit/source/services/rpc/RpcServer.cpp b/SilKit/source/services/rpc/RpcServer.cpp index 28552f4df..3a0d0b716 100644 --- a/SilKit/source/services/rpc/RpcServer.cpp +++ b/SilKit/source/services/rpc/RpcServer.cpp @@ -74,7 +74,8 @@ void RpcServer::RegisterServiceDiscovery() // How this controller is discovered by RpcClient const std::string discoveryLookupKey = Core::Discovery::controllerTypeRpcClient + "/" - + Core::Discovery::supplKeyRpcClientFunctionName + "/" + _dataSpec.FunctionName(); + + Core::Discovery::supplKeyRpcClientFunctionName + "/" + + _dataSpec.FunctionName(); // RpcServer discovers RpcClient and adds RpcServerInternal on a matching connection _participant->GetServiceDiscovery()->RegisterSpecificServiceDiscoveryHandler( diff --git a/SilKit/source/services/rpc/RpcServerInternal.cpp b/SilKit/source/services/rpc/RpcServerInternal.cpp index 1f03cc47b..506fed410 100644 --- a/SilKit/source/services/rpc/RpcServerInternal.cpp +++ b/SilKit/source/services/rpc/RpcServerInternal.cpp @@ -30,11 +30,11 @@ namespace SilKit { namespace Services { namespace Rpc { -RpcServerInternal::RpcServerInternal(Core::IParticipantInternal* participant, Services::Orchestration::ITimeProvider* timeProvider, +RpcServerInternal::RpcServerInternal(Core::IParticipantInternal* participant, + Services::Orchestration::ITimeProvider* timeProvider, const std::string& functionName, const std::string& mediaType, const std::vector& labels, - const std::string& clientUUID, - RpcCallHandler handler, IRpcServer* parent) + const std::string& clientUUID, RpcCallHandler handler, IRpcServer* parent) : _functionName{functionName} , _mediaType{mediaType} , _labels{labels} diff --git a/SilKit/source/services/rpc/RpcTestUtilities.hpp b/SilKit/source/services/rpc/RpcTestUtilities.hpp index 36d772aa6..734a6e4c5 100644 --- a/SilKit/source/services/rpc/RpcTestUtilities.hpp +++ b/SilKit/source/services/rpc/RpcTestUtilities.hpp @@ -43,8 +43,8 @@ namespace Tests { struct MockConnection { - MockConnection(SilKit::Core::IParticipantInternal*, SilKit::Config::ParticipantConfiguration /*config*/, std::string /*participantName*/, - SilKit::Core::ParticipantId /*participantId*/, + MockConnection(SilKit::Core::IParticipantInternal*, SilKit::Config::ParticipantConfiguration /*config*/, + std::string /*participantName*/, SilKit::Core::ParticipantId /*participantId*/, SilKit::Services::Orchestration::ITimeProvider* /*timeProvider*/, SilKit::Core::ProtocolVersion) { } @@ -104,7 +104,8 @@ struct MockConnection MOCK_METHOD(void, Mock_SendMsg, (const SilKit::Core::IServiceEndpoint* /*from*/, FunctionCallResponse /*msg*/)); template - void SendMsg(const SilKit::Core::IServiceEndpoint* /*from*/, const std::string& /*target*/, SilKitMessageT&& /*msg*/) + void SendMsg(const SilKit::Core::IServiceEndpoint* /*from*/, const std::string& /*target*/, + SilKitMessageT&& /*msg*/) { } @@ -120,7 +121,7 @@ struct MockConnection void RegisterPeerShutdownCallback(std::function /*callback*/) {} - void SetAsyncSubscriptionsCompletionHandler(std::function /*completionHandler*/){}; + void AddAsyncSubscriptionsCompletionHandler(std::function /*completionHandler*/){}; void Test_SetTimeProvider(SilKit::Services::Orchestration::ITimeProvider* timeProvider) { @@ -140,7 +141,10 @@ struct MockConnection } } - size_t GetNumberOfConnectedParticipants() { return 0; } + size_t GetNumberOfConnectedParticipants() + { + return 0; + } size_t GetNumberOfRemoteReceivers(const SilKit::Core::IServiceEndpoint* /*service*/, const std::string& /*msgTypeName*/) @@ -154,8 +158,7 @@ struct MockConnection return {}; }; - bool ParticipantHasCapability(const std::string& /*participantName*/, - const std::string& /*capability*/) const + bool ParticipantHasCapability(const std::string& /*participantName*/, const std::string& /*capability*/) const { return true; } @@ -207,8 +210,7 @@ class RpcTestBase : public testing::Test if (_rpcServer == nullptr) { SilKit::Services::Rpc::RpcSpec dataSpec{"FunctionA", "application/octet-stream"}; - _rpcServer = - participant->CreateRpcServer("RpcServer", dataSpec, nullptr); + _rpcServer = participant->CreateRpcServer("RpcServer", dataSpec, nullptr); } return _rpcServer; } @@ -216,7 +218,8 @@ class RpcTestBase : public testing::Test private: static auto MakeParticipantConfiguration() -> std::shared_ptr { - auto configuration = std::make_shared(SilKit::Config::ParticipantConfiguration()); + auto configuration = + std::make_shared(SilKit::Config::ParticipantConfiguration()); SilKit::Config::RpcClient rpcClientConfig; rpcClientConfig.name = "RpcClient"; diff --git a/SilKit/source/services/rpc/Test_RpcClient.cpp b/SilKit/source/services/rpc/Test_RpcClient.cpp old mode 100755 new mode 100644 index 75ae0065e..516294c38 --- a/SilKit/source/services/rpc/Test_RpcClient.cpp +++ b/SilKit/source/services/rpc/Test_RpcClient.cpp @@ -49,8 +49,8 @@ TEST_F(Test_RpcClient, rpc_client_calls_result_handler_with_error_when_no_server EXPECT_CALL(callbacks, CallResultHandler(testing::Eq(rpcClient), testing::_)) .WillOnce([](IRpcClient* /*rpcClient*/, const RpcCallResultEvent& event) { - ASSERT_EQ(event.callStatus, RpcCallStatus::ServerNotReachable); - }); + ASSERT_EQ(event.callStatus, RpcCallStatus::ServerNotReachable); + }); rpcClient->SetCallResultHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::CallResultHandler)); rpcClient->Call(sampleData); @@ -69,8 +69,7 @@ TEST_F(Test_RpcClient, rpc_client_does_not_fail_on_timeout_reply) const FunctionCallResponse response{}; EXPECT_NO_THROW(rpcClientInternal->ReceiveMessage(response)); - EXPECT_CALL(callbacks, CallResultHandler(testing::Eq(rpcClient), testing::_)) - .Times(0); + EXPECT_CALL(callbacks, CallResultHandler(testing::Eq(rpcClient), testing::_)).Times(0); } TEST_F(Test_RpcClient, rpc_client_call_sends_message_with_current_timestamp_and_data) @@ -87,9 +86,9 @@ TEST_F(Test_RpcClient, rpc_client_call_sends_message_with_current_timestamp_and_ EXPECT_CALL(participant->GetSilKitConnection(), Mock_SendMsg(testing::_, testing::A())) .WillOnce([this, &fixedTimeProvider](const SilKit::Core::IServiceEndpoint* /*from*/, const FunctionCall& msg) { - ASSERT_EQ(msg.timestamp, fixedTimeProvider.now); - ASSERT_EQ(msg.data, sampleData); - }); + ASSERT_EQ(msg.timestamp, fixedTimeProvider.now); + ASSERT_EQ(msg.data, sampleData); + }); // HACK: Change the time provider for the captured services. Must happen _after_ the RpcServer and RpcClient (and // therefore the RpcServerInternal) have been created. diff --git a/SilKit/source/services/rpc/Test_RpcSerdes.cpp b/SilKit/source/services/rpc/Test_RpcSerdes.cpp index f989c887f..83e27eb4a 100644 --- a/SilKit/source/services/rpc/Test_RpcSerdes.cpp +++ b/SilKit/source/services/rpc/Test_RpcSerdes.cpp @@ -37,7 +37,7 @@ TEST(Test_RpcSerdes, SimRpc_functionCall) SilKit::Core::MessageBuffer buffer; FunctionCall in, out; - in.callUuid ={1234565, 0x789abcdf}; + in.callUuid = {1234565, 0x789abcdf}; in.data = referenceData; in.timestamp = 12345ns; @@ -53,7 +53,7 @@ TEST(Test_RpcSerdes, SimRpc_functioncall_response) SilKit::Core::MessageBuffer buffer; FunctionCallResponse in, out; - in.callUuid ={1234565, 0x789abcdf}; + in.callUuid = {1234565, 0x789abcdf}; in.data = referenceData; in.timestamp = 12345ns; diff --git a/SilKit/source/services/rpc/Test_RpcServer.cpp b/SilKit/source/services/rpc/Test_RpcServer.cpp old mode 100755 new mode 100644 index e805dd563..9bf667202 --- a/SilKit/source/services/rpc/Test_RpcServer.cpp +++ b/SilKit/source/services/rpc/Test_RpcServer.cpp @@ -56,11 +56,11 @@ TEST_F(Test_RpcServer, rpc_server_call_response_sends_message_with_timestamp_and }); EXPECT_CALL(participant->GetSilKitConnection(), Mock_SendMsg(testing::_, testing::A())) - .WillOnce( - [this, &fixedTimeProvider](const SilKit::Core::IServiceEndpoint* /*from*/, const FunctionCallResponse& msg) { - ASSERT_EQ(msg.timestamp, fixedTimeProvider.now); - ASSERT_EQ(msg.data, sampleData); - }); + .WillOnce([this, &fixedTimeProvider](const SilKit::Core::IServiceEndpoint* /*from*/, + const FunctionCallResponse& msg) { + ASSERT_EQ(msg.timestamp, fixedTimeProvider.now); + ASSERT_EQ(msg.data, sampleData); + }); IRpcClient* iRpcClient = CreateRpcClient(); diff --git a/SilKit/source/silkit.map b/SilKit/source/silkit.map new file mode 100644 index 000000000..834973e6e --- /dev/null +++ b/SilKit/source/silkit.map @@ -0,0 +1,38 @@ +/* + * SPDX-FileCopyrightText: 2024 Vector Informatik GmbH + * + * SPDX-License-Identifier: MIT + */ + + +/* This version script does not apply symbol versioning, it only changes symbol visibility! */ +{ + global: + SilKit_*; + + extern "C++" { + "SilKit::Config::ParticipantConfigurationFromString(std::__cxx11::basic_string, std::allocator > const&)"; + "SilKit::Config::ParticipantConfigurationFromFile(std::__cxx11::basic_string, std::allocator > const&)"; + + "SilKit::CreateParticipant(std::shared_ptr, std::__cxx11::basic_string, std::allocator > const&, std::__cxx11::basic_string, std::allocator > const&)"; + "SilKit::CreateParticipant(std::shared_ptr, std::__cxx11::basic_string, std::allocator > const&)"; + + "SilKit::Experimental::Participant::CreateSystemController(SilKit::IParticipant*)"; + + "SilKit::Experimental::Services::Lin::GetSlaveConfiguration(SilKit::Services::Lin::ILinController*)"; + "SilKit::Experimental::Services::Lin::AddLinSlaveConfigurationHandler(SilKit::Services::Lin::ILinController*, std::function)"; + "SilKit::Experimental::Services::Lin::RemoveLinSlaveConfigurationHandler(SilKit::Services::Lin::ILinController*, SilKit::Util::HandlerId)"; + + "SilKit::Vendor::Vector::CreateSilKitRegistry(std::shared_ptr)"; + + "SilKit::Version::Major()"; + "SilKit::Version::Minor()"; + "SilKit::Version::Patch()"; + "SilKit::Version::BuildNumber()"; + "SilKit::Version::String()"; + "SilKit::Version::VersionSuffix()"; + "SilKit::Version::GitHash()"; + }; + local: + *; +}; diff --git a/SilKit/source/tracing/IReplay.hpp b/SilKit/source/tracing/IReplay.hpp old mode 100755 new mode 100644 index 19225be5c..c9826824a --- a/SilKit/source/tracing/IReplay.hpp +++ b/SilKit/source/tracing/IReplay.hpp @@ -49,9 +49,8 @@ class IReplayDataProvider virtual ~IReplayDataProvider() = default; //!< Pass the config (containing search path hints), the actual file to open // and a logger to the extension. - virtual auto OpenFile(const SilKit::Config::ParticipantConfiguration& config, - const std::string& filePath, SilKit::Services::Logging::ILogger* logger) - -> std::shared_ptr = 0; + virtual auto OpenFile(const SilKit::Config::ParticipantConfiguration& config, const std::string& filePath, + SilKit::Services::Logging::ILogger* logger) -> std::shared_ptr = 0; }; class IReplayFile diff --git a/SilKit/source/tracing/ITraceMessageSink.hpp b/SilKit/source/tracing/ITraceMessageSink.hpp old mode 100755 new mode 100644 index 38026a7ff..8bfaeef19 --- a/SilKit/source/tracing/ITraceMessageSink.hpp +++ b/SilKit/source/tracing/ITraceMessageSink.hpp @@ -66,9 +66,8 @@ class ITraceMessageSinkFactory { public: virtual ~ITraceMessageSinkFactory() = default; - virtual auto Create(SilKit::Config::ParticipantConfiguration config, - SilKit::Services::Logging::ILogger* logger, std::string participantName, std::string sinkName) - -> std::unique_ptr = 0; + virtual auto Create(SilKit::Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, + std::string participantName, std::string sinkName) -> std::unique_ptr = 0; }; } // namespace SilKit diff --git a/SilKit/source/tracing/ITraceMessageSource.hpp b/SilKit/source/tracing/ITraceMessageSource.hpp old mode 100755 new mode 100644 index 1c695f669..e63287617 --- a/SilKit/source/tracing/ITraceMessageSource.hpp +++ b/SilKit/source/tracing/ITraceMessageSource.hpp @@ -76,8 +76,8 @@ class Tracer void Tracer::AddSink(const Core::ServiceDescriptor& serviceDescr, ITraceMessageSink& sink) { - auto sinkCallback = [serviceDescr, &sink](SilKit::Services::TransmitDirection direction, std::chrono::nanoseconds timestamp, - const TraceMessage& msg) { + auto sinkCallback = [serviceDescr, &sink](SilKit::Services::TransmitDirection direction, + std::chrono::nanoseconds timestamp, const TraceMessage& msg) { sink.Trace(direction, serviceDescr, timestamp, msg); }; _sinks.emplace_back(std::move(sinkCallback)); diff --git a/SilKit/source/tracing/PcapReplay.cpp b/SilKit/source/tracing/PcapReplay.cpp old mode 100755 new mode 100644 index 7fec65c18..69e8970a1 --- a/SilKit/source/tracing/PcapReplay.cpp +++ b/SilKit/source/tracing/PcapReplay.cpp @@ -52,15 +52,27 @@ class ReplayPcapChannel : public SilKit::IReplayChannel return SilKit::TraceMessageType::EthernetFrame; } - auto StartTime() const -> std::chrono::nanoseconds override { return _reader.StartTime(); } - auto EndTime() const -> std::chrono::nanoseconds override { return _reader.EndTime(); } - auto NumberOfMessages() const -> uint64_t override { return _reader.NumberOfMessages(); } + auto StartTime() const -> std::chrono::nanoseconds override + { + return _reader.StartTime(); + } + auto EndTime() const -> std::chrono::nanoseconds override + { + return _reader.EndTime(); + } + auto NumberOfMessages() const -> uint64_t override + { + return _reader.NumberOfMessages(); + } auto Name() const -> const std::string& override { // Pcap has no concept of channel, return hard coded. return _channelName; } - auto GetMetaInfos() const -> const std::map& override { return _reader.GetMetaInfos(); } + auto GetMetaInfos() const -> const std::map& override + { + return _reader.GetMetaInfos(); + } auto GetReader() -> std::shared_ptr override { // return a copy, which allows caching the internal data structures @@ -83,13 +95,28 @@ class ReplayPcapFile : public SilKit::IReplayFile _channels.emplace_back(std::move(channel)); } - auto FilePath() const -> const std::string& override { return _filePath; } - auto SilKitConfig() const -> std::string override { return {}; } + auto FilePath() const -> const std::string& override + { + return _filePath; + } + auto SilKitConfig() const -> std::string override + { + return {}; + } - FileType Type() const override { return IReplayFile::FileType::PcapFile; } + FileType Type() const override + { + return IReplayFile::FileType::PcapFile; + } - std::vector>::iterator begin() override { return _channels.begin(); } - std::vector>::iterator end() override { return _channels.end(); } + std::vector>::iterator begin() override + { + return _channels.begin(); + } + std::vector>::iterator end() override + { + return _channels.end(); + } private: std::string _filePath; @@ -101,8 +128,8 @@ class ReplayPcapFile : public SilKit::IReplayFile namespace SilKit { namespace Tracing { -auto PcapReplay::OpenFile(const SilKit::Config::ParticipantConfiguration&, const std::string& filePath, SilKit::Services::Logging::ILogger* logger) - -> std::shared_ptr +auto PcapReplay::OpenFile(const SilKit::Config::ParticipantConfiguration&, const std::string& filePath, + SilKit::Services::Logging::ILogger* logger) -> std::shared_ptr { return std::make_shared(filePath, logger); } diff --git a/SilKit/source/tracing/PcapReplay.hpp b/SilKit/source/tracing/PcapReplay.hpp old mode 100755 new mode 100644 index 6b724e93a..5e64c2ffd --- a/SilKit/source/tracing/PcapReplay.hpp +++ b/SilKit/source/tracing/PcapReplay.hpp @@ -32,8 +32,8 @@ namespace Tracing { class PcapReplay : public IReplayDataProvider { public: - auto OpenFile(const SilKit::Config::ParticipantConfiguration&, const std::string& filePath, SilKit::Services::Logging::ILogger* logger) - -> std::shared_ptr override; + auto OpenFile(const SilKit::Config::ParticipantConfiguration&, const std::string& filePath, + SilKit::Services::Logging::ILogger* logger) -> std::shared_ptr override; }; } // namespace Tracing diff --git a/SilKit/source/tracing/PcapSink.cpp b/SilKit/source/tracing/PcapSink.cpp old mode 100755 new mode 100644 index 797cb950d..c6be4c024 --- a/SilKit/source/tracing/PcapSink.cpp +++ b/SilKit/source/tracing/PcapSink.cpp @@ -71,7 +71,8 @@ void PcapSink::Open(SinkType outputType, const std::string& outputPath) _headerWritten = false; _outputPath = outputPath; break; - default: throw SilKitError("PcapSink::Open: specified SinkType not implemented"); + default: + throw SilKitError("PcapSink::Open: specified SinkType not implemented"); } } diff --git a/SilKit/source/tracing/ReplayScheduler.cpp b/SilKit/source/tracing/ReplayScheduler.cpp old mode 100755 new mode 100644 index ad7f41a25..902bc6c1d --- a/SilKit/source/tracing/ReplayScheduler.cpp +++ b/SilKit/source/tracing/ReplayScheduler.cpp @@ -47,12 +47,18 @@ TraceMessageType ToTraceMessageType(Config::NetworkType networkType) { switch (networkType) { - case Config::NetworkType::Ethernet: return TraceMessageType::EthernetFrame; - case Config::NetworkType::CAN: return TraceMessageType::CanFrameEvent; - case Config::NetworkType::LIN: return TraceMessageType::LinFrame; - case Config::NetworkType::FlexRay: return TraceMessageType::FlexrayFrameEvent; - case Config::NetworkType::Data: return TraceMessageType::DataMessageEvent; - default: throw SilKitError("Unknown channel Type"); + case Config::NetworkType::Ethernet: + return TraceMessageType::EthernetFrame; + case Config::NetworkType::CAN: + return TraceMessageType::CanFrameEvent; + case Config::NetworkType::LIN: + return TraceMessageType::LinFrame; + case Config::NetworkType::FlexRay: + return TraceMessageType::FlexrayFrameEvent; + case Config::NetworkType::Data: + return TraceMessageType::DataMessageEvent; + default: + throw SilKitError("Unknown channel Type"); } } @@ -81,17 +87,35 @@ class MetaInfos } // Meta data uses fixed terms from the MDF spec, see Config.hpp:MdfChannel and SilKitExtension_Mdf - value ChannelName() const { return Get("mdf/channel_name"); } + value ChannelName() const + { + return Get("mdf/channel_name"); + } - value ChannelSource() const { return Get("mdf/source_info_name"); } + value ChannelSource() const + { + return Get("mdf/source_info_name"); + } - value ChannelPath() const { return Get("mdf/source_info_path"); } + value ChannelPath() const + { + return Get("mdf/source_info_path"); + } - value GroupPath() const { return Get("mdf/channel_group_path"); } + value GroupPath() const + { + return Get("mdf/channel_group_path"); + } - value GroupSource() const { return Get("mdf/channel_group_name"); } + value GroupSource() const + { + return Get("mdf/channel_group_name"); + } - value GroupName() const { return Get("mdf/channel_group_acquisition_name"); } + value GroupName() const + { + return Get("mdf/channel_group_acquisition_name"); + } value Separator() const { @@ -116,14 +140,26 @@ class MetaInfos return std::chrono::nanoseconds{0}; } - value VirtualBusNumber() const { return Get("mdf/virtual_bus_number"); } + value VirtualBusNumber() const + { + return Get("mdf/virtual_bus_number"); + } - value PcapVersion() const { return Get("pcap/version"); } + value PcapVersion() const + { + return Get("pcap/version"); + } - value PcapGmtToLocal() const { return Get("pcap/gmt_to_local"); } + value PcapGmtToLocal() const + { + return Get("pcap/gmt_to_local"); + } private: - value Get(const std::string& name) const { return _metaInfos.at(name); } + value Get(const std::string& name) const + { + return _metaInfos.at(name); + } private: const std::map& _metaInfos; @@ -208,7 +244,6 @@ auto FindReplayChannel(SilKit::Services::Logging::ILogger* log, IReplayFile* rep const std::string& participantName, const std::string& networkName, const Config::NetworkType networkType) -> std::shared_ptr { - std::vector> channelList; const auto type = ToTraceMessageType(networkType); @@ -241,10 +276,9 @@ auto FindReplayChannel(SilKit::Services::Logging::ILogger* log, IReplayFile* rep } if (MatchSilKitChannel(channel, networkName, participantName, controllerName)) { - Services::Logging::Debug(log, "Replay: found channel '{}' from file '{}' for type {}", - channel->Name(), replayFile->FilePath(), to_string(channel->Type())); + Services::Logging::Debug(log, "Replay: found channel '{}' from file '{}' for type {}", channel->Name(), + replayFile->FilePath(), to_string(channel->Type())); channelList.emplace_back(std::move(channel)); - } } } @@ -285,9 +319,7 @@ void ReplayScheduler::ConfigureTimeProvider(Services::Orchestration::ITimeProvid _timeProvider = timeProvider; - _timeProvider->AddNextSimStepHandler([this](auto now, auto duration) { - ReplayMessages(now, duration); - }); + _timeProvider->AddNextSimStepHandler([this](auto now, auto duration) { ReplayMessages(now, duration); }); } void ReplayScheduler::ConfigureController(const std::string& controllerName, IReplayDataController* replayController, diff --git a/SilKit/source/tracing/ReplayScheduler.hpp b/SilKit/source/tracing/ReplayScheduler.hpp old mode 100755 new mode 100644 index c4ca5c25b..5845fcc8f --- a/SilKit/source/tracing/ReplayScheduler.hpp +++ b/SilKit/source/tracing/ReplayScheduler.hpp @@ -37,8 +37,7 @@ namespace Tracing { class ReplayScheduler { public: - ReplayScheduler(const Config::ParticipantConfiguration& participantConfig, - Core::IParticipantInternal* participant); + ReplayScheduler(const Config::ParticipantConfiguration& participantConfig, Core::IParticipantInternal* participant); ~ReplayScheduler(); @@ -47,6 +46,7 @@ class ReplayScheduler void ConfigureController(const std::string& controllerName, IReplayDataController* controller, const Config::Replay& replayConfig, const std::string& networkName, Config::NetworkType networkType); + private: // Methods diff --git a/SilKit/source/tracing/Test_EthernetReplay.cpp b/SilKit/source/tracing/Test_EthernetReplay.cpp old mode 100755 new mode 100644 index 26a955609..2429b1f84 --- a/SilKit/source/tracing/Test_EthernetReplay.cpp +++ b/SilKit/source/tracing/Test_EthernetReplay.cpp @@ -103,16 +103,31 @@ struct Callbacks struct MockReplayMessage : public IReplayMessage { - auto Timestamp() const -> std::chrono::nanoseconds override { return _timestamp; } - auto GetDirection() const -> SilKit::Services::TransmitDirection override { return _direction; } - auto ServiceDescriptorStr() const -> std::string override { return _serviceDescriptorStr; } - auto EndpointAddress() const -> SilKit::Core::EndpointAddress override { return _endpointAddress; } - auto Type() const -> TraceMessageType override { return _type; } + auto Timestamp() const -> std::chrono::nanoseconds override + { + return _timestamp; + } + auto GetDirection() const -> SilKit::Services::TransmitDirection override + { + return _direction; + } + auto ServiceDescriptorStr() const -> std::string override + { + return _serviceDescriptorStr; + } + auto EndpointAddress() const -> SilKit::Core::EndpointAddress override + { + return _endpointAddress; + } + auto Type() const -> TraceMessageType override + { + return _type; + } std::chrono::nanoseconds _timestamp{0}; SilKit::Services::TransmitDirection _direction{SilKit::Services::TransmitDirection::RX}; TraceMessageType _type{TraceMessageType::InvalidReplayData}; - std::string _serviceDescriptorStr{ "ServiceDescriptorString" }; + std::string _serviceDescriptorStr{"ServiceDescriptorString"}; SilKit::Core::EndpointAddress _endpointAddress; //! Deprecated }; @@ -135,8 +150,8 @@ struct MockEthFrame }; struct Test_EthernetReplay : public testing::Test { - ServiceDescriptor _serviceDescriptor{ "EthernetReplay", "Eth0", "EthController0", 2}; - ServiceDescriptor _otherServiceDescriptor{ "EthernetReplay2", "Eth1", "EthController2", 4 }; + ServiceDescriptor _serviceDescriptor{"EthernetReplay", "Eth0", "EthController0", 2}; + ServiceDescriptor _otherServiceDescriptor{"EthernetReplay2", "Eth1", "EthController2", 4}; }; TEST_F(Test_EthernetReplay, ethcontroller_replay_config_send) @@ -204,9 +219,9 @@ TEST_F(Test_EthernetReplay, ethcontroller_replay_config_receive) ON_CALL(callbacks, ReceiveMessage(A(), A())) .WillByDefault([](IEthernetController* controller, const EthernetFrameEvent& ethernetFrameEvent) { - SILKIT_UNUSED_ARG(controller); - SILKIT_UNUSED_ARG(ethernetFrameEvent); - }); + SILKIT_UNUSED_ARG(controller); + SILKIT_UNUSED_ARG(ethernetFrameEvent); + }); Config::EthernetController cfg{}; cfg.replay.useTraceSource = "ReplayTest.TraceSource"; @@ -220,7 +235,7 @@ TEST_F(Test_EthernetReplay, ethcontroller_replay_config_receive) cfg.replay.direction = Config::Replay::Direction::Receive; EthController controller{&participant, cfg, participant.GetTimeProvider()}; - controller.SetServiceDescriptor({ "p1","n1", "c1", 4 }); + controller.SetServiceDescriptor({"p1", "n1", "c1", 4}); controller.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessage)); EXPECT_CALL(callbacks, ReceiveMessage(A(), AnEthernetFrameEvent(msg))).Times(1); diff --git a/SilKit/source/tracing/Test_Replay.cpp b/SilKit/source/tracing/Test_Replay.cpp old mode 100755 new mode 100644 index bbe98f5b8..b71b94852 --- a/SilKit/source/tracing/Test_Replay.cpp +++ b/SilKit/source/tracing/Test_Replay.cpp @@ -53,30 +53,21 @@ using testing::An; auto ACanMessage(const CanMessage& msg) -> testing::Matcher { - using namespace testing; - return AllOf( - Field(&CanMessage::canId, Eq(msg.canId)) - , Field(&CanMessage::dataField, Eq(msg.dataField)) - , Field(&CanMessage::timestamp, Eq(msg.timestamp)) - ); + using namespace testing; + return AllOf(Field(&CanMessage::canId, Eq(msg.canId)), Field(&CanMessage::dataField, Eq(msg.dataField)), + Field(&CanMessage::timestamp, Eq(msg.timestamp))); } auto AService(const IServiceEndpoint* service) -> testing::Matcher { - using namespace testing; - return AllOf( - Property(&IServiceEndpoint::GetServiceDescriptor, Eq(service->GetServiceDescriptor())) - ); + using namespace testing; + return AllOf(Property(&IServiceEndpoint::GetServiceDescriptor, Eq(service->GetServiceDescriptor()))); } auto AnEthMessage(const EthernetFrame& msg) -> testing::Matcher { using namespace testing; - return Field(&EthernetFrameEvent::frame, - AllOf( - Field(&EthernetFrame::raw, ContainerEq(msg)) - ) - ); + return Field(&EthernetFrameEvent::frame, AllOf(Field(&EthernetFrame::raw, ContainerEq(msg)))); } @@ -88,7 +79,6 @@ auto AGenericMessage(const GenericMessage& msg) -> testing::Matcher std::chrono::nanoseconds override { @@ -168,18 +157,18 @@ struct MockReplayMessage } std::chrono::nanoseconds _timestamp{0}; - SilKit::Services::TransmitDirection _direction{ SilKit::Services::TransmitDirection::RX}; + SilKit::Services::TransmitDirection _direction{SilKit::Services::TransmitDirection::RX}; TraceMessageType _type{TraceMessageType::InvalidReplayData}; }; -struct MockEthFrame +struct MockEthFrame : public MockReplayMessage , public EthernetFrame { MockEthFrame() { - SetSourceMac(EthernetMac{1,2,3,4,5,6}); - SetDestinationMac(EthernetMac{7,8,9,0xa,0xb,0xc}); + SetSourceMac(EthernetMac{1, 2, 3, 4, 5, 6}); + SetDestinationMac(EthernetMac{7, 8, 9, 0xa, 0xb, 0xc}); _type = TraceMessageType::EthernetFrame; } }; @@ -199,8 +188,7 @@ TEST(Test_Replay, ethcontroller_replay_config_send) EthControllerReplay ctrl{&participant, cfg, participant.GetTimeProvider()}; ctrl.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, SendMsg_proxy(AService(&ctrl), AnEthMessage(msg))) - .Times(1); + EXPECT_CALL(participant, SendMsg_proxy(AService(&ctrl), AnEthMessage(msg))).Times(1); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); ctrl.ReplayMessage(&msg); } @@ -211,24 +199,21 @@ TEST(Test_Replay, ethcontroller_replay_config_send) cfg.replay.direction = Config::Replay::Direction::Both; EthControllerReplay ctrl{&participant, cfg, participant.GetTimeProvider()}; ctrl.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, SendMsg_proxy(AService(&ctrl), AnEthMessage(msg))) - .Times(1); + EXPECT_CALL(participant, SendMsg_proxy(AService(&ctrl), AnEthMessage(msg))).Times(1); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); ctrl.ReplayMessage(&msg); } - // Block Send + // Block Send { msg._direction = SilKit::Services::TransmitDirection::RX; cfg.replay.direction = Config::Replay::Direction::Send; EthControllerReplay ctrl{&participant, cfg, participant.GetTimeProvider()}; ctrl.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, SendMsg_proxy(AService(&ctrl), AnEthMessage(msg))) - .Times(0); + EXPECT_CALL(participant, SendMsg_proxy(AService(&ctrl), AnEthMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(0); ctrl.ReplayMessage(&msg); } - } @@ -242,7 +227,7 @@ TEST(Test_Replay, ethcontroller_replay_config_receive) MockEthFrame msg; - msg._address = {1,2}; + msg._address = {1, 2}; // Replay Receive / Receive @@ -250,10 +235,9 @@ TEST(Test_Replay, ethcontroller_replay_config_receive) msg._direction = SilKit::Services::TransmitDirection::RX; cfg.replay.direction = Config::Replay::Direction::Receive; EthControllerReplay controller{&participant, cfg, participant.GetTimeProvider()}; - controller.SetServiceDescriptor(from_endpointAddress({3,4})); + controller.SetServiceDescriptor(from_endpointAddress({3, 4})); controller.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessage)); - EXPECT_CALL(callbacks, ReceiveMessage(A(), AnEthMessage(msg))) - .Times(1); + EXPECT_CALL(callbacks, ReceiveMessage(A(), AnEthMessage(msg))).Times(1); controller.ReplayMessage(&msg); } @@ -262,21 +246,19 @@ TEST(Test_Replay, ethcontroller_replay_config_receive) msg._direction = SilKit::Services::TransmitDirection::RX; cfg.replay.direction = Config::Replay::Direction::Both; EthControllerReplay controller{&participant, cfg, participant.GetTimeProvider()}; - controller.SetServiceDescriptor(from_endpointAddress({3,4})); + controller.SetServiceDescriptor(from_endpointAddress({3, 4})); controller.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessage)); - EXPECT_CALL(callbacks, ReceiveMessage(A(), AnEthMessage(msg))) - .Times(1); + EXPECT_CALL(callbacks, ReceiveMessage(A(), AnEthMessage(msg))).Times(1); controller.ReplayMessage(&msg); } - // Block Receive + // Block Receive { msg._direction = SilKit::Services::TransmitDirection::TX; cfg.replay.direction = Config::Replay::Direction::Receive; EthControllerReplay controller{&participant, cfg, participant.GetTimeProvider()}; - controller.SetServiceDescriptor(from_endpointAddress({3,4})); + controller.SetServiceDescriptor(from_endpointAddress({3, 4})); controller.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessage)); - EXPECT_CALL(callbacks, ReceiveMessage(A(), AnEthMessage(msg))) - .Times(0); + EXPECT_CALL(callbacks, ReceiveMessage(A(), AnEthMessage(msg))).Times(0); controller.ReplayMessage(&msg); } } @@ -291,7 +273,7 @@ struct MockCanMessage { timestamp = std::chrono::nanoseconds{0}; canId = 0; - + dataField.resize(8); size_t i = 0u; for (auto& d : dataField) @@ -308,16 +290,15 @@ TEST(Test_Replay, DISABLED_cancontroller_replay_config_send) Config::CanController cfg{}; MockCanMessage msg; - msg._address = {1,2}; + msg._address = {1, 2}; // Replay Send / Send { msg._direction = SilKit::Services::TransmitDirection::TX; cfg.replay.direction = Config::Replay::Direction::Send; - + CanControllerReplay can{&participant, cfg, participant.GetTimeProvider()}; can.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))) - .Times(1); + EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))).Times(1); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); can.ReplayMessage(&msg); } @@ -325,11 +306,10 @@ TEST(Test_Replay, DISABLED_cancontroller_replay_config_send) { msg._direction = SilKit::Services::TransmitDirection::TX; cfg.replay.direction = Config::Replay::Direction::Both; - + CanControllerReplay can{&participant, cfg, participant.GetTimeProvider()}; can.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))) - .Times(1); + EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))).Times(1); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); can.ReplayMessage(&msg); } @@ -337,11 +317,10 @@ TEST(Test_Replay, DISABLED_cancontroller_replay_config_send) { msg._direction = SilKit::Services::TransmitDirection::TX; cfg.replay.direction = Config::Replay::Direction::Receive; - + CanControllerReplay can{&participant, cfg, participant.GetTimeProvider()}; can.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))) - .Times(0); + EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(0); can.ReplayMessage(&msg); } @@ -349,10 +328,9 @@ TEST(Test_Replay, DISABLED_cancontroller_replay_config_send) { msg._direction = SilKit::Services::TransmitDirection::RX; cfg.replay.direction = Config::Replay::Direction::Send; - + CanControllerReplay can{&participant, cfg, participant.GetTimeProvider()}; - EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))) - .Times(0); + EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(0); can.SetServiceDescriptor(from_endpointAddress(msg._address)); can.ReplayMessage(&msg); @@ -362,10 +340,9 @@ TEST(Test_Replay, DISABLED_cancontroller_replay_config_send) msg._direction = SilKit::Services::TransmitDirection::RX; cfg.replay.direction = Config::Replay::Direction::Receive; msg._address = tracing::ReplayEndpointAddress(); - + CanControllerReplay can{&participant, cfg, participant.GetTimeProvider()}; - EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))) - .Times(0); + EXPECT_CALL(participant, SendMsg_proxy(AService(&can), ACanMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); can.SetServiceDescriptor(from_endpointAddress(msg._address)); can.ReplayMessage(&msg); @@ -382,40 +359,37 @@ TEST(Test_Replay, DISABLED_cancontroller_replay_config_receive) MockCanMessage msg; - msg._address = {1,2}; + msg._address = {1, 2}; // Replay Receive / Receive { msg._direction = SilKit::Services::TransmitDirection::RX; cfg.replay.direction = Config::Replay::Direction::Receive; CanControllerReplay controller{&participant, cfg, participant.GetTimeProvider()}; - controller.SetServiceDescriptor(from_endpointAddress({3,4})); + controller.SetServiceDescriptor(from_endpointAddress({3, 4})); controller.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessageCan)); - EXPECT_CALL(callbacks, ReceiveMessageCan(A(), ACanMessage(msg))) - .Times(1); + EXPECT_CALL(callbacks, ReceiveMessageCan(A(), ACanMessage(msg))).Times(1); controller.ReplayMessage(&msg); } - + // Replay Receive / Both { msg._direction = SilKit::Services::TransmitDirection::RX; cfg.replay.direction = Config::Replay::Direction::Both; CanControllerReplay controller{&participant, cfg, participant.GetTimeProvider()}; - controller.SetServiceDescriptor(from_endpointAddress({3,4})); + controller.SetServiceDescriptor(from_endpointAddress({3, 4})); controller.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessageCan)); - EXPECT_CALL(callbacks, ReceiveMessageCan(A(), ACanMessage(msg))) - .Times(1); + EXPECT_CALL(callbacks, ReceiveMessageCan(A(), ACanMessage(msg))).Times(1); controller.ReplayMessage(&msg); } - // Block Receive + // Block Receive { msg._direction = SilKit::Services::TransmitDirection::TX; cfg.replay.direction = Config::Replay::Direction::Receive; CanControllerReplay controller{&participant, cfg, participant.GetTimeProvider()}; - controller.SetServiceDescriptor(from_endpointAddress({3,4})); + controller.SetServiceDescriptor(from_endpointAddress({3, 4})); controller.AddFrameHandler(SilKit::Util::bind_method(&callbacks, &Callbacks::ReceiveMessageCan)); - EXPECT_CALL(callbacks, ReceiveMessageCan(A(), ACanMessage(msg))) - .Times(0); + EXPECT_CALL(callbacks, ReceiveMessageCan(A(), ACanMessage(msg))).Times(0); controller.ReplayMessage(&msg); } } @@ -443,7 +417,7 @@ TEST(Test_Replay, genericpublisher_replay_config_send) Config::GenericPort cfg{}; MockGenericMessage msg; - msg._address = {1,2}; + msg._address = {1, 2}; // Replay Send / Send { @@ -452,8 +426,7 @@ TEST(Test_Replay, genericpublisher_replay_config_send) Services::generic::GenericPublisherReplay pub{&participant, cfg, participant.GetTimeProvider()}; pub.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, SendMsg_proxy(AService(&pub), AGenericMessage(msg))) - .Times(1); + EXPECT_CALL(participant, SendMsg_proxy(AService(&pub), AGenericMessage(msg))).Times(1); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); pub.ReplayMessage(&msg); } @@ -464,8 +437,7 @@ TEST(Test_Replay, genericpublisher_replay_config_send) Services::generic::GenericPublisherReplay pub{&participant, cfg, participant.GetTimeProvider()}; pub.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, SendMsg_proxy(AService(&pub), AGenericMessage(msg))) - .Times(1); + EXPECT_CALL(participant, SendMsg_proxy(AService(&pub), AGenericMessage(msg))).Times(1); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); pub.ReplayMessage(&msg); } @@ -475,8 +447,7 @@ TEST(Test_Replay, genericpublisher_replay_config_send) cfg.replay.direction = Config::Replay::Direction::Send; Services::generic::GenericPublisherReplay pub{&participant, cfg, participant.GetTimeProvider()}; - EXPECT_CALL(participant, SendMsg_proxy(AService(&pub), AGenericMessage(msg))) - .Times(0); + EXPECT_CALL(participant, SendMsg_proxy(AService(&pub), AGenericMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(0); pub.SetServiceDescriptor(from_endpointAddress(msg._address)); pub.ReplayMessage(&msg); @@ -487,8 +458,7 @@ TEST(Test_Replay, genericpublisher_replay_config_send) cfg.replay.direction = Config::Replay::Direction::Receive; Services::generic::GenericPublisherReplay pub{&participant, cfg, participant.GetTimeProvider()}; - EXPECT_CALL(participant, SendMsg_proxy(AService(&pub), AGenericMessage(msg))) - .Times(0); + EXPECT_CALL(participant, SendMsg_proxy(AService(&pub), AGenericMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(0); pub.SetServiceDescriptor(from_endpointAddress(msg._address)); pub.ReplayMessage(&msg); @@ -502,7 +472,7 @@ TEST(Test_Replay, genericsubscriber_replay_config_send) Config::GenericPort cfg{}; MockGenericMessage msg; - msg._address = {1,2}; + msg._address = {1, 2}; // Replay Send / Send { @@ -511,8 +481,7 @@ TEST(Test_Replay, genericsubscriber_replay_config_send) Services::generic::GenericSubscriberReplay sub{&participant, cfg, participant.GetTimeProvider()}; sub.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, ReceiveMsg(msg._address, AGenericMessage(msg))) - .Times(0); + EXPECT_CALL(participant, ReceiveMsg(msg._address, AGenericMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(0); sub.ReplayMessage(&msg); } @@ -523,8 +492,7 @@ TEST(Test_Replay, genericsubscriber_replay_config_send) Services::generic::GenericSubscriberReplay sub{&participant, cfg, participant.GetTimeProvider()}; sub.SetServiceDescriptor(from_endpointAddress(msg._address)); - EXPECT_CALL(participant, ReceiveMsg(msg._address, AGenericMessage(msg))) - .Times(0); + EXPECT_CALL(participant, ReceiveMsg(msg._address, AGenericMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(0); sub.ReplayMessage(&msg); } @@ -534,9 +502,8 @@ TEST(Test_Replay, genericsubscriber_replay_config_send) cfg.replay.direction = Config::Replay::Direction::Both; Services::generic::GenericSubscriberReplay sub{&participant, cfg, participant.GetTimeProvider()}; - sub.SetServiceDescriptor(from_endpointAddress({1,3})); - EXPECT_CALL(participant, ReceiveMsg(msg._address, AGenericMessage(msg))) - .Times(0); + sub.SetServiceDescriptor(from_endpointAddress({1, 3})); + EXPECT_CALL(participant, ReceiveMsg(msg._address, AGenericMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); sub.ReplayMessage(&msg); } @@ -546,9 +513,8 @@ TEST(Test_Replay, genericsubscriber_replay_config_send) cfg.replay.direction = Config::Replay::Direction::Receive; Services::generic::GenericSubscriberReplay sub{&participant, cfg, participant.GetTimeProvider()}; - sub.SetServiceDescriptor(from_endpointAddress({1,3})); - EXPECT_CALL(participant, ReceiveMsg(msg._address, AGenericMessage(msg))) - .Times(0); + sub.SetServiceDescriptor(from_endpointAddress({1, 3})); + EXPECT_CALL(participant, ReceiveMsg(msg._address, AGenericMessage(msg))).Times(0); EXPECT_CALL(participant.mockTimeProvider.mockTime, Now()).Times(1); sub.ReplayMessage(&msg); } diff --git a/SilKit/source/tracing/TraceMessage.hpp b/SilKit/source/tracing/TraceMessage.hpp old mode 100755 new mode 100644 index 0fc4fb959..59a930aea --- a/SilKit/source/tracing/TraceMessage.hpp +++ b/SilKit/source/tracing/TraceMessage.hpp @@ -84,7 +84,10 @@ class TraceMessage { } - TraceMessageType Type() const { return _type; } + TraceMessageType Type() const + { + return _type; + } template const MsgT& Get() const diff --git a/SilKit/source/tracing/Tracing.cpp b/SilKit/source/tracing/Tracing.cpp old mode 100755 new mode 100644 index b3b323b01..65be4f3d7 --- a/SilKit/source/tracing/Tracing.cpp +++ b/SilKit/source/tracing/Tracing.cpp @@ -77,7 +77,8 @@ auto CreateTraceMessageSinks(Services::Logging::ILogger* logger, { if (!sinkInUse(sinkCfg.name)) { - Services::Logging::Warn(logger, + Services::Logging::Warn( + logger, "Tracing: the trace sink '{}' on participant '{}' is not referenced in the config, creating anyway!", sinkCfg.name, participantConfig.participantName); } @@ -107,7 +108,8 @@ auto CreateTraceMessageSinks(Services::Logging::ILogger* logger, newSinks.emplace_back(std::move(sink)); break; } - default: throw SilKitError("Unknown Sink Type"); + default: + throw SilKitError("Unknown Sink Type"); } } @@ -137,7 +139,8 @@ auto CreateReplayFiles(Services::Logging::ILogger* logger, const Config::Partici break; } case Config::TraceSource::Type::Undefined: //[[fallthrough]] - default: throw SilKitError("CreateReplayFiles: unknown TraceSource::Type!"); + default: + throw SilKitError("CreateReplayFiles: unknown TraceSource::Type!"); } } diff --git a/SilKit/source/tracing/Tracing.hpp b/SilKit/source/tracing/Tracing.hpp old mode 100755 new mode 100644 index bd76b55e1..4d8349ca0 --- a/SilKit/source/tracing/Tracing.hpp +++ b/SilKit/source/tracing/Tracing.hpp @@ -52,7 +52,7 @@ auto CreateReplayFiles(Services::Logging::ILogger* logger, const Config::Partici // has a Replay config. bool HasReplayConfig(const Config::ParticipantConfiguration& config); -bool IsValidReplayConfig(const Config::Replay &config); +bool IsValidReplayConfig(const Config::Replay& config); } // namespace Tracing } // namespace SilKit diff --git a/SilKit/source/tracing/detail/NamedPipeWin.cpp b/SilKit/source/tracing/detail/NamedPipeWin.cpp old mode 100755 new mode 100644 index d6d0a9e07..a9de0e58a --- a/SilKit/source/tracing/detail/NamedPipeWin.cpp +++ b/SilKit/source/tracing/detail/NamedPipeWin.cpp @@ -35,15 +35,14 @@ static std::string GetPipeError() { LPVOID lpMsgBuf; - auto msgSize = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR)& lpMsgBuf, 0, NULL); + auto msgSize = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); if (msgSize == 0) { return "FromMessageA failed!"; } - std::string rv(reinterpret_cast(lpMsgBuf)); + std::string rv(reinterpret_cast(lpMsgBuf)); LocalFree(lpMsgBuf); return rv; } @@ -53,18 +52,15 @@ NamedPipeWin::NamedPipeWin(const std::string& name) std::stringstream ss; ss << "\\\\.\\pipe\\" << name; - _pipeHandle = CreateNamedPipe( - ss.str().c_str(), - PIPE_ACCESS_OUTBOUND, - //we use message buffering, in a blocking manner - PIPE_TYPE_MESSAGE | PIPE_WAIT, - //single instance only - 1, - //allow for very large messages - 65536, 65536, - //raise the default 50ms timeout, just in case - 300, - NULL); + _pipeHandle = CreateNamedPipe(ss.str().c_str(), PIPE_ACCESS_OUTBOUND, + //we use message buffering, in a blocking manner + PIPE_TYPE_MESSAGE | PIPE_WAIT, + //single instance only + 1, + //allow for very large messages + 65536, 65536, + //raise the default 50ms timeout, just in case + 300, NULL); if (!isValid()) { throw SilKitError(GetPipeError()); @@ -74,7 +70,8 @@ NamedPipeWin::NamedPipeWin(const std::string& name) NamedPipeWin::~NamedPipeWin() { - try { + try + { Close(); } catch (...) @@ -98,7 +95,8 @@ bool NamedPipeWin::Write(const char* buffer, size_t size) } DWORD cbWritten = 0; - if (size == 0) return false; + if (size == 0) + return false; if (isValid()) { auto ok = WriteFile(_pipeHandle, buffer, static_cast(size), &cbWritten, NULL); diff --git a/SilKit/source/tracing/detail/NamedPipeWin.hpp b/SilKit/source/tracing/detail/NamedPipeWin.hpp old mode 100755 new mode 100644 index 56f4769dc..5dce0c482 --- a/SilKit/source/tracing/detail/NamedPipeWin.hpp +++ b/SilKit/source/tracing/detail/NamedPipeWin.hpp @@ -44,6 +44,7 @@ class NamedPipeWin : public NamedPipe // Public interface methods bool Write(const char* buffer, size_t size) override; void Close() override; + private: // ---------------------------------------- // private members @@ -52,7 +53,10 @@ class NamedPipeWin : public NamedPipe private: // ---------------------------------------- // private methods - bool isValid() const { return _pipeHandle != INVALID_HANDLE_VALUE; } + bool isValid() const + { + return _pipeHandle != INVALID_HANDLE_VALUE; + } bool _isConnected{false}; std::string _name; diff --git a/SilKit/source/tracing/mock/MockTraceSink.hpp b/SilKit/source/tracing/mock/MockTraceSink.hpp old mode 100755 new mode 100644 index c4a205ffa..38fa3b30d --- a/SilKit/source/tracing/mock/MockTraceSink.hpp +++ b/SilKit/source/tracing/mock/MockTraceSink.hpp @@ -34,20 +34,25 @@ class MockTraceSink : public ITraceMessageSink public: MOCK_METHOD(void, Open, (SinkType type, const std::string& outputPath), (override)); MOCK_METHOD(void, Close, (), (override)); - MOCK_METHOD(void, Trace, (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, - std::chrono::nanoseconds timestamp, const SilKit::Services::Can::CanFrameEvent& message)); - MOCK_METHOD(void, Trace, (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, - std::chrono::nanoseconds timestamp, const SilKit::Services::Ethernet::EthernetFrame& message)); - MOCK_METHOD(void, Trace, (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, - std::chrono::nanoseconds timestamp, const SilKit::Services::Lin::LinFrame& message)); - MOCK_METHOD(void, Trace, (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, - std::chrono::nanoseconds timestamp, const SilKit::Services::PubSub::DataMessageEvent& message)); - MOCK_METHOD(void, Trace, (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, - std::chrono::nanoseconds timestamp, const SilKit::Services::Flexray::FlexrayFrameEvent& message)); + MOCK_METHOD(void, Trace, + (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, + std::chrono::nanoseconds timestamp, const SilKit::Services::Can::CanFrameEvent& message)); + MOCK_METHOD(void, Trace, + (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, + std::chrono::nanoseconds timestamp, const SilKit::Services::Ethernet::EthernetFrame& message)); + MOCK_METHOD(void, Trace, + (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, + std::chrono::nanoseconds timestamp, const SilKit::Services::Lin::LinFrame& message)); + MOCK_METHOD(void, Trace, + (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, + std::chrono::nanoseconds timestamp, const SilKit::Services::PubSub::DataMessageEvent& message)); + MOCK_METHOD(void, Trace, + (SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, + std::chrono::nanoseconds timestamp, const SilKit::Services::Flexray::FlexrayFrameEvent& message)); //! \brief This works around TraceMessage not being copyable for use in Matchers void Trace(SilKit::Services::TransmitDirection dir, const ServiceDescriptor& address, - std::chrono::nanoseconds timestamp, const TraceMessage& message) override + std::chrono::nanoseconds timestamp, const TraceMessage& message) override { switch (message.Type()) { @@ -69,7 +74,6 @@ class MockTraceSink : public ITraceMessageSink } - auto GetLogger() const -> Services::Logging::ILogger* override { return nullptr; diff --git a/SilKit/source/tracing/string_utils.hpp b/SilKit/source/tracing/string_utils.hpp old mode 100755 new mode 100644 index f2f3869a5..1921d2009 --- a/SilKit/source/tracing/string_utils.hpp +++ b/SilKit/source/tracing/string_utils.hpp @@ -58,12 +58,18 @@ std::string to_string(TraceMessageType type) { switch (type) { - case TraceMessageType::EthernetFrame: return "EthernetFrame"; - case TraceMessageType::CanFrameEvent: return "CanFrameEvent"; - case TraceMessageType::LinFrame: return "LinFrame"; - case TraceMessageType::DataMessageEvent: return "DataMessageEvent"; - case TraceMessageType::FlexrayFrameEvent: return "FlaxrayFrameEvent"; - default: throw SilKitError("Unknown TraceMessage::Type in operator< + //! \brief Declare a new argument + template auto& Add(Args&&... args) { _arguments.push_back(std::make_unique(std::forward(args)...)); @@ -49,7 +49,7 @@ class CommandlineParser /*! \brief Retrieve a commandline argument by its name * \throw SilKit::SilKitError when argument does not exist or is of a different kind */ - template + template auto Get(std::string name) -> TArgument& { auto* argument = GetByName(name); @@ -67,14 +67,16 @@ class CommandlineParser out << "Usage: " << executableName; for (auto& argument : _arguments) { - if (argument->IsHidden()) continue; + if (argument->IsHidden()) + continue; out << " " << argument->Usage(); } out << std::endl; out << "Arguments:" << std::endl; for (auto& argument : _arguments) { - if (argument->IsHidden()) continue; + if (argument->IsHidden()) + continue; out << argument->Description() << std::endl; } } @@ -84,14 +86,15 @@ class CommandlineParser */ void ParseArguments(int argc, char** argv) { - auto positionalArgumentIt = std::find_if(_arguments.begin(), _arguments.end(), [](const auto& el) - { return el->Kind() == ArgumentKind::Positional || el->Kind() == ArgumentKind::PositionalList; }); + auto positionalArgumentIt = std::find_if(_arguments.begin(), _arguments.end(), [](const auto& el) { + return el->Kind() == ArgumentKind::Positional || el->Kind() == ArgumentKind::PositionalList; + }); for (auto i = 1; i < argc; ++i) { - std::string argument{ argv[i] }; + std::string argument{argv[i]}; - auto arg{ argument }; - auto isShortForm{ false }; + auto arg{argument}; + auto isShortForm{false}; if (arg.length() >= 3 && arg.substr(0, 2) == "--") { arg.erase(0, 2); @@ -107,8 +110,9 @@ class CommandlineParser { auto* positionalArgument = static_cast(positionalArgumentIt->get()); positionalArgument->_value = std::move(arg); - positionalArgumentIt = std::find_if(++positionalArgumentIt, _arguments.end(), [](const auto& el) - { return el->Kind() == ArgumentKind::Positional || el->Kind() == ArgumentKind::PositionalList; }); + positionalArgumentIt = std::find_if(++positionalArgumentIt, _arguments.end(), [](const auto& el) { + return el->Kind() == ArgumentKind::Positional || el->Kind() == ArgumentKind::PositionalList; + }); } else { @@ -127,8 +131,8 @@ class CommandlineParser auto splitPos = std::find(arg.begin(), arg.end(), '='); if (splitPos != arg.end()) { - std::string name = { arg.begin(), splitPos }; - std::string value = { splitPos + 1, arg.end() }; + std::string name = {arg.begin(), splitPos}; + std::string value = {splitPos + 1, arg.end()}; auto* option = isShortForm ? GetByShortName