├── CMakeLists.txt ├── LICENSE ├── README.md ├── cmake ├── Config.cmake.in └── p3comConfig.cmake ├── doc ├── CycloneDDS.md └── cyclone_dds.patch ├── include └── p3com │ ├── gateway │ ├── cmd_line.hpp │ ├── gateway.hpp │ ├── gateway_app.hpp │ ├── gateway_config.hpp │ ├── iox_to_transport.hpp │ └── transport_to_iox.hpp │ ├── generic │ ├── config.hpp │ ├── data_reader.hpp │ ├── data_writer.hpp │ ├── discovery.hpp │ ├── pending_messages.hpp │ ├── segmented_messages.hpp │ ├── serialization.hpp │ ├── transport_forwarder.hpp │ └── types.hpp │ ├── internal │ ├── gateway │ │ └── gateway.inl │ ├── log │ │ └── logging.hpp │ └── utility │ │ └── vector_map.inl │ ├── introspection │ ├── gw_introspection.hpp │ └── gw_introspection_types.hpp │ ├── transport │ ├── tcp │ │ ├── tcp_client_transport_session.hpp │ │ ├── tcp_server_transport_session.hpp │ │ ├── tcp_transport.hpp │ │ └── tcp_transport_session.hpp │ ├── transport.hpp │ ├── transport_info.hpp │ ├── transport_type.hpp │ └── udp │ │ ├── udp_transport.hpp │ │ └── udp_transport_broadcast.hpp │ └── utility │ ├── helper_functions.hpp │ └── vector_map.hpp ├── p3com.toml └── source ├── p3com ├── gateway │ ├── cmd_line.cpp │ ├── gateway_app.cpp │ ├── gateway_config.cpp │ ├── iox_to_transport.cpp │ ├── main.cpp │ └── transport_to_iox.cpp ├── generic │ ├── data_reader.cpp │ ├── data_writer.cpp │ ├── discovery.cpp │ ├── pending_messages.cpp │ ├── segmented_messages.cpp │ ├── serialization.cpp │ └── transport_forwarder.cpp ├── introspection │ └── gw_introspection.cpp ├── log │ └── logging.cpp └── transport │ └── transport_info.cpp ├── tcp ├── tcp_client_transport_session.cpp ├── tcp_server_transport_session.cpp ├── tcp_transport.cpp └── tcp_transport_session.cpp └── udp ├── udp_transport.cpp └── udp_transport_broadcast.cpp /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. 2 | # Copyright (c) 2020 - 2021 by Apex.AI Inc. All rights reserved. 3 | # Copyright (c) 2022 NXP. All rights reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # SPDX-License-Identifier: Apache-2.0 18 | 19 | ############################################################################## 20 | # Modifications by NXP 2022 21 | ############################################################################## 22 | 23 | cmake_minimum_required(VERSION 3.11) 24 | 25 | set(IOX_VERSION_STRING "2.0.2") 26 | 27 | project(p3com VERSION ${IOX_VERSION_STRING}) 28 | 29 | find_package(iceoryx_hoofs REQUIRED) 30 | find_package(iceoryx_posh REQUIRED) 31 | 32 | include(IceoryxPackageHelper) 33 | include(IceoryxPlatform) 34 | 35 | #option(PCIE_TRANSPORT "Builds the iceoryx PCIe transport - enables internode communication via PCIe" OFF) 36 | option(UDP_TRANSPORT "Builds the iceoryx UDP transport - enables internode communication via UDP" ON) 37 | option(TCP_TRANSPORT "Builds the iceoryx TCP transport - enables internode communication via TCP" OFF) 38 | 39 | # 40 | ########## set variables for export ########## 41 | # 42 | setup_package_name_and_create_files( 43 | NAME ${PROJECT_NAME} 44 | NAMESPACE p3com 45 | PROJECT_PREFIX ${PREFIX} 46 | ) 47 | 48 | # 49 | ########## find_package in source tree ########## 50 | # 51 | set(${PROJECT_NAME}_DIR ${CMAKE_CURRENT_LIST_DIR}/cmake 52 | CACHE FILEPATH 53 | "${PROJECT_NAME}Config.cmake to make find_package(${PROJECT_NAME}) work in source tree!" 54 | FORCE 55 | ) 56 | 57 | # 58 | ########## build building-block library ########## 59 | # 60 | if(PCIE_TRANSPORT OR UDP_TRANSPORT OR TCP_TRANSPORT) 61 | add_library(p3com STATIC) 62 | add_library(${PROJECT_NAMESPACE}::p3com ALIAS p3com) 63 | 64 | set_target_properties(p3com PROPERTIES 65 | CXX_STANDARD_REQUIRED ON 66 | CXX_STANDARD ${ICEORYX_CXX_STANDARD} 67 | POSITION_INDEPENDENT_CODE ON 68 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" 69 | ) 70 | 71 | target_include_directories(p3com 72 | PUBLIC 73 | $ 74 | $ 75 | $ 76 | ) 77 | 78 | if(FREERTOS) 79 | find_package(Threads REQUIRED) 80 | find_package(arm32m7_sdk REQUIRED 81 | COMPONENTS 82 | runtime_core0 83 | std++_freertos 84 | freertos 85 | ) 86 | 87 | target_link_libraries(p3com 88 | PUBLIC 89 | arm32m7_sdk::runtime_core0 90 | arm32m7_sdk::std++_freertos 91 | Threads::Threads 92 | arm32m7_sdk::freertos 93 | ) 94 | 95 | target_sources(p3com 96 | PRIVATE 97 | $ENV{OVSP_ROOT}/arm32m7_sdk/modules/runtime/sys_common/sys.cpp 98 | $ENV{OVSP_ROOT}/arm32m7_sdk/modules/runtime/sys_common/FreeRTOS_memory.cpp 99 | ) 100 | 101 | else() 102 | add_executable(p3com-gw 103 | source/p3com/gateway/main.cpp 104 | ) 105 | 106 | set_target_properties(p3com-gw PROPERTIES 107 | CXX_STANDARD_REQUIRED ON 108 | CXX_STANDARD ${ICEORYX_CXX_STANDARD} 109 | ) 110 | 111 | target_compile_options(p3com-gw 112 | PRIVATE 113 | ${ICEORYX_WARNINGS} 114 | ${ICEORYX_SANITIZER_FLAGS} 115 | ) 116 | 117 | target_link_libraries(p3com-gw PRIVATE p3com::p3com) 118 | 119 | target_include_directories(p3com-gw 120 | PRIVATE 121 | $ 122 | ) 123 | 124 | setup_install_directories_and_export_package( 125 | TARGETS p3com-gw 126 | INCLUDE_DIRECTORY include/ 127 | ) 128 | endif() 129 | 130 | target_link_libraries(p3com 131 | PUBLIC 132 | iceoryx_posh::iceoryx_posh 133 | iceoryx_hoofs::iceoryx_hoofs 134 | ) 135 | 136 | target_sources(p3com 137 | PRIVATE 138 | source/p3com/generic/data_reader.cpp 139 | source/p3com/generic/data_writer.cpp 140 | source/p3com/generic/discovery.cpp 141 | source/p3com/generic/serialization.cpp 142 | source/p3com/generic/pending_messages.cpp 143 | source/p3com/generic/segmented_messages.cpp 144 | source/p3com/generic/transport_forwarder.cpp 145 | source/p3com/gateway/iox_to_transport.cpp 146 | source/p3com/gateway/transport_to_iox.cpp 147 | source/p3com/gateway/gateway_config.cpp 148 | source/p3com/gateway/cmd_line.cpp 149 | source/p3com/gateway/gateway_app.cpp 150 | source/p3com/transport/transport_info.cpp 151 | source/p3com/log/logging.cpp 152 | source/p3com/introspection/gw_introspection.cpp 153 | ) 154 | 155 | target_compile_options(p3com 156 | PRIVATE 157 | ${ICEORYX_WARNINGS} 158 | ${ICEORYX_SANITIZER_FLAGS} 159 | ) 160 | 161 | if(TOML_CONFIG) 162 | find_package(cpptoml REQUIRED) 163 | 164 | target_link_libraries(p3com 165 | PUBLIC 166 | iceoryx_posh::iceoryx_posh_config 167 | cpptoml 168 | ) 169 | 170 | target_compile_definitions(p3com 171 | PRIVATE 172 | TOML_CONFIG 173 | ) 174 | 175 | install(FILES roudi_config.toml DESTINATION ${CMAKE_SYSROOT}/etc/iceoryx) 176 | endif() 177 | 178 | setup_install_directories_and_export_package( 179 | TARGETS p3com 180 | INCLUDE_DIRECTORY include/ 181 | ) 182 | endif() 183 | 184 | if(PCIE_TRANSPORT) 185 | set(PCIE_BB_TYPE "RC" CACHE STRING "Compiling for EP or RC.") 186 | if(PCIE_BB_TYPE STREQUAL "RC") 187 | set(PCIE_DEFS "PCIEBB_RC") 188 | find_package(lx2_sdk REQUIRED 189 | COMPONENTS 190 | pcie-bb-rc 191 | pcie-bb-dmalib-rc) 192 | target_link_libraries(p3com 193 | PUBLIC 194 | lx2_sdk::pcie-bb-rc 195 | lx2_sdk::pcie-bb-dmalib-rc) 196 | else() 197 | set(PCIE_DEFS "PCIEBB_EP") 198 | if(NOT FREERTOS) 199 | find_package(s32g_sdk REQUIRED 200 | COMPONENTS 201 | pcie-bb-ep 202 | pcie-bb-dmalib-ep) 203 | target_link_libraries(p3com 204 | PUBLIC 205 | s32g_sdk::pcie-bb-ep 206 | s32g_sdk::pcie-bb-dmalib-ep) 207 | endif() 208 | endif() 209 | 210 | 211 | target_sources(p3com 212 | PRIVATE 213 | source/pcie/pcie_transport.cpp 214 | ) 215 | 216 | target_compile_definitions(p3com 217 | PUBLIC 218 | PCIE_TRANSPORT 219 | ${PCIE_DEFS} 220 | ) 221 | endif() 222 | 223 | if(UDP_TRANSPORT) 224 | target_sources(p3com 225 | PRIVATE 226 | source/udp/udp_transport.cpp 227 | source/udp/udp_transport_broadcast.cpp 228 | ) 229 | 230 | target_compile_definitions(p3com 231 | PUBLIC 232 | UDP_TRANSPORT 233 | ) 234 | endif() 235 | 236 | if(TCP_TRANSPORT) 237 | target_sources(p3com 238 | PRIVATE 239 | source/tcp/tcp_transport.cpp 240 | source/tcp/tcp_transport_session.cpp 241 | source/tcp/tcp_client_transport_session.cpp 242 | source/tcp/tcp_server_transport_session.cpp 243 | source/udp/udp_transport_broadcast.cpp 244 | ) 245 | 246 | target_compile_definitions(p3com 247 | PUBLIC 248 | TCP_TRANSPORT 249 | ) 250 | endif() 251 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Robert Bosch GmbH 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Eclipse p3com - portable pluggable publish/subscribe communication 2 | 3 | ## Introduction 4 | 5 | **Eclipse p3com enables middleware libraries to leverage the performance of 6 | platform-specific interfaces.** This is in contrast to ethernet-based 7 | networking, which is the default data exchange mechanism in all established 8 | implementations of middleware protocols such DDS, SOME/IP or MQTT. 9 | 10 | Eclipse p3com is also an extension of the [Eclipse 11 | iceoryx](https://github.com/eclipse-iceoryx/iceoryx) middleware that enables it 12 | to work over PCI Express, UDP, TCP and other transport layers/protocols, apart 13 | from the default inter-process-communication (IPC) that iceoryx supports. It 14 | could also be said that p3com provides the infrastructure for writing iceoryx 15 | gateways. 16 | 17 | Eclipse p3com consists of: 18 | * platform-agnostic infrastructure (e.g., discovery system, generic gateway endpoints) 19 | * platform-specific transport layers (useful as is, or as examples for new transport layer for other platforms) 20 | 21 | *Warning: Currently, the source code in this repository is the initial 22 | contribution to the p3com project. It is in an experimental stage, probably 23 | with many issues and bugs. It only contains the UDP and TCP transport layers, 24 | mostly intended for debug purposes. In future contributions, the PCI Express 25 | driver stack for the NXP BlueBox3 development platform will be contributed, 26 | along with the PCIe transport layer implementation in p3com. This PCIe 27 | transport layer will truly demonstrate the strength of p3com and the full 28 | features available. Furthermore, useful examples and demos will also be 29 | gradually contributed over time.* 30 | 31 | ## Features 32 | 33 | ### p3com gateway 34 | 35 | Eclipse iceoryx has the concept of a **gateway**. In general, it is a daemon 36 | process that forwards all local inter-process-communication (between user 37 | applications using the iceoryx API) over a particular channel (such as an 38 | ethernet bus) to a different device, where it is received by a corresponding 39 | gateway process and published into its local iceoryx system. In other words, it 40 | mirrors all the iceoryx traffic between multiple devices, thus enabling that 41 | user publishers and subscribers can communicate even if they are running on 42 | different devices (nodes). Gateway implementations can use the iceoryx 43 | introspection mechanism to dynamically discover local user publishers and 44 | subscribers. 45 | 46 | Eclipse p3com is essentially a **iceoryx gateway implementation**. This gateway 47 | contains a custom device- and service-discovery system and a modular 48 | transport layer architecture supporting the following layers: 49 | * PCI Express via an NXP-internal Linux PCIe driver stack 50 | * UDP/IP via the ASIO networking library 51 | * TCP/IP via the ASIO networking library 52 | 53 | ### Discovery system 54 | 55 | Instances of the p3com gateway (running on each device) keep track of: 56 | * Iceoryx publishers and subscribers in user applications on the local device 57 | (node) 58 | * Remote p3com gateway instances and their enabled transport types 59 | * Iceoryx subscribers in user applications in the remote gateway instances' 60 | devices (nodes) 61 | 62 | The local discovery data is obtained via the iceoryx introspection 63 | functionality. Remote discovery of other running gateways and their associated 64 | subscribers is achieved via a custom discovery protocol over the enabled 65 | transport layer. 66 | 67 | This discovery information is then used when a user publisher publishes a 68 | sample. This sample is received by a corresponding subscriber in the local 69 | gateway and then it is forwarded (over the appropriate transport layer) to all 70 | remote gateway instances which register at least one user subscriber with a 71 | matching service description. Finally, these remote gateways will publish the 72 | received sample with their own associated publisher. This way, the sample gets 73 | to all relevant user subscribers. 74 | 75 | #### Forwarding mechanism 76 | 77 | The discovery system also includes support for forwarding between different 78 | transport layers. 79 | 80 | Here is an example setup: Consider three devices A, B and C. Device A is 81 | running the p3com gateway with only PCIe transport enabled, device B is running 82 | the p3com gateway with both PCIe and UDP transports enabled and device C is 83 | running the p3com gateway with only the UDP transport enabled. Furhermore, the 84 | p3com gateway on device B is configured to forward the relevant service. In 85 | this case, a publisher on device A can communicate with a matching subscriber 86 | on device C (and vice versa), because the gateway on device B will forward all 87 | traffic between the PCIe and UDP interfaces. 88 | 89 | The configuration of p3com gateway on device C has to be done statically with 90 | the gateway configuration file, as described below. 91 | 92 | #### Gateway introspection API 93 | 94 | The p3com gateway discovery mechanism has a certain necessary lag to register 95 | a new user publisher and share the new discovery state to other devices after 96 | each user publisher is created and offered. The p3com library therefore exposes 97 | a pair of API functions `hasGwRegistered` and `waitForGwRegistration` which 98 | make it possible to wait for the gateway registration, either synchronously or 99 | asynchronously. 100 | 101 | Futhermore, an additional API function `isGwRunning` is provided, which can be 102 | used to query whether the p3com gateway daemon is currently running on the 103 | device. 104 | 105 | ### Automatic transport switching on failure 106 | 107 | The p3com project is developed in an automotive context, therefore we have 108 | safety in mind. It is possible that a transport interface might fail during the 109 | runtime of the gateway. In this case, the gateway application will not crash, 110 | but simply disable the faulty transport layer and continue forwarding 111 | (and receiving) the iceoryx traffic over the other enabled transport layers. 112 | 113 | Note that this feature has only been tested for UDP transport failures, in 114 | particular by switching off the used ethernet interface, for example with 115 | `ifconfig eth0 down`. Issues with the PCIe transport are much more difficult to 116 | recover from, and are currently not supported. 117 | 118 | ### PCIe DMA acceleration 119 | 120 | The PCI Express transport layer has a special capability to use the DMA engine 121 | embedded in the PCIe controller. If the sample size exceeds a certain treshold, 122 | provisionally set to 4kB, the DMA controller is used to execute the copy of the 123 | sample payload between the devices, instead of the usual PCIe BAR-window-based 124 | messaging protocol. Moreover, thanks to a sophisticated userspace buffer DMA 125 | support in the BlueBox3 PCIe stack, the DMA engine directly operates on the 126 | iceoryx memory pool buffers, avoiding any redundant copy. This technique can 127 | achieve extremely high-throughput data-sharing performance. 128 | 129 | ### FreeRTOS support 130 | 131 | TODO in future contributions. 132 | 133 | ## Integration to Cyclone DDS 134 | 135 | Please refer to [CycloneDDS.md](./doc/CycloneDDS.md) for instructions how to 136 | build and run Cyclone DDS with p3com. 137 | 138 | ## Build and install 139 | 140 | ### Dependencies 141 | 142 | Eclipse p3com depends on Eclipse iceoryx v2.0.3. It is recommended to build it 143 | from source and install it. 144 | 145 | The UDP and TCP transport layers depend on the open-source ASIO library. You 146 | can install it via these commands on Ubuntu: 147 | ``` 148 | cd /tmp && wget https://sourceforge.net/projects/asio/files/asio/1.24.0%20%28Stable%29/asio-1.24.0.tar.gz/download -O asio-1.24.0.tar.gz 149 | cd /tmp && tar xf asio-1.24.0.tar.gz 150 | cp -r /tmp/asio-1.24.0/include/asio* /usr/include 151 | ``` 152 | 153 | ### CMake options 154 | 155 | The p3com fork adds the following top-level CMake options: 156 | 157 | * `PCIE_TRANSPORT`, enables the PCIe transport layer in the p3com gateway. 158 | * `UDP_TRANSPORT`, enables the UDP transport layer in the p3com gateway. 159 | * `TCP_TRANSPORT`, enables the TCP transport layer in the p3com gateway. 160 | 161 | The p3com gateway application is built if at least one of the `PCIE_TRANSPORT`, 162 | `UDP_TRANSPORT` and `TCP_TRANSPORT` options are enabled. Only one of 163 | `UDP_TRANSPORT` and `TCP_TRANSPORT` can be enabled at the same time. 164 | 165 | 166 | 167 | ## Usage 168 | 169 | ### Gateway command line options 170 | 171 | Since the p3com gateway is just another iceoryx application, it requires the 172 | RouDi daemon running in the background. 173 | 174 | You can see the command line options of the p3com gateway by supplying the `-h` 175 | flag: 176 | 177 | ``` 178 | p3com gateway application 179 | usage: ./p3com-gw [options] 180 | options: 181 | -h, --help Print help and exit 182 | -l, --log-level Set log level 183 | -p, --pcie Enable PCIe transport 184 | -u, --udp Enable UDP transport 185 | -t, --tcp Enable TCP transport 186 | -c, --config-file Path to the gateway config file 187 | ``` 188 | 189 | If no transport options (i.e., `-p` and `-u`) are specified, all 190 | available transport layers will be enabled. Also, note that only the transport 191 | layers enabled during the build of the gateway binary (with CMake options) are 192 | available for enabling. 193 | 194 | ### Usage as daemon 195 | 196 | It is recommended to run the p3com gateway after boot as a daemon process on 197 | all devices in the system. This way, all local iceoryx communication is 198 | automatically forwarded between the nodes. 199 | 200 | ### Configuration file 201 | 202 | The p3com gateway can load some configuration settings from a configuration 203 | file in the TOML format. The default path of the configuration file is 204 | `/etc/iceoryx/p3com.toml`, but it is also possible to set a custom path via the 205 | `--config-file` option when running the gateway application. 206 | 207 | There are currently two supported options in the configuration file. The first 208 | one is `preferred-transport` which lets the user select the transport layer 209 | which should be used when possible. This can be useful when multiple transport 210 | layers should be enabled in the running p3com gateway for communication with 211 | various device supporting various interfaces, but a single transport layer 212 | should be preferred. By default, the PCIE transport layer is preferred over UDP 213 | and TCP. 214 | 215 | The second supported options is an array of tables `forwarded-service`, where 216 | each table contains the keys `service`, `instance` and `event`. These are the 217 | description of services to forward by the gateway. 218 | 219 | You can find a sample of this file [here](./p3com.toml). 220 | 221 | ## Limitations 222 | 223 | There are some limitations that should be kept in mind when using the p3com 224 | gateway to achieve inter-device communication. 225 | 226 | ### The `hasSubscribers` method 227 | 228 | The `iox::popo::BasePublisher::hasSubscribers` method might behave unexpectedly 229 | in a system with the p3com gateway running. The gateway maintains a set of 230 | internal publishers and subscribers for all active services on the system. So, 231 | a user application publisher might appear to have matched subscribers, but 232 | those are only the gateway-internal subscribers, instead of the expected 233 | same-service subscribers in a remote user application. 234 | 235 | ### The UDP and TCP transport layers are not optimized 236 | 237 | The p3com gateway support for the UDP and TCP transports is mostly experimental 238 | and for debugging purposes. We are not aiming to optimize this feature, because 239 | there exist many middleware solutions for networking communication, such as the 240 | plenty DDS (e.g., Eclipse Cycloned DDS, FastDDS) or MQTT (e.g., Eclipse 241 | Mosquitto) protocols implementations. 242 | 243 | ## Future work 244 | 245 | ### Support request-response model 246 | 247 | With the Eclipse iceoryx 2.0.0 release, a new request-response API model was 248 | added to complement the default publish-subscribe model. This is mostly about 249 | the `Client` and `Server` types. Currently, p3com does not support forwarding 250 | communication with this model, but it should be reasonably easy to implement 251 | it. 252 | 253 | ### Improve configurability 254 | 255 | It would be good to be able to configure further things in the p3com gateway, 256 | in particular: 257 | 258 | * Blocking behaviour of gateway-internal publishers and subscribers. This 259 | concerns the `iox::popo::SubscriberTooSlowPolicy` and 260 | `iox::popo::QueueFullPolicy` policies. 261 | * Timeout durations. For example, there is a timeout specified when sending 262 | data over the transport layers. 263 | * PCIe DMA treshold. The PCIe transport has an empirically obtained treshold 264 | number to be used for the decision whether to use the PCIe BAR windows for 265 | message transfer or rather PCIe DMA engine. It could be useful if this can 266 | configured by the user. 267 | * Behaviour when gateway drops a sample. Most frequently, this concerns the 268 | situation that the gateway received a sample over a transport layer, but it is 269 | not able to publish it into the local iceoryx system, because the memory pool 270 | is exhausted. It might try to wait, but this will block all receiving from that 271 | transport layer. Alternatively, it can report this error in some way to the 272 | user. 273 | 274 | ### Improve automatic transport switching on failure 275 | 276 | There should be a mechanism to support the restoration of a failed transport 277 | layer. For now, the failed transport is simply disabled forever and never used 278 | again (until the gateway application is restarted). 279 | 280 | ### Add Github actions CI 281 | 282 | As the title says. 283 | -------------------------------------------------------------------------------- /cmake/Config.cmake.in: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. 2 | # Copyright (c) 2022 by NXP. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # SPDX-License-Identifier: Apache-2.0 17 | 18 | ############################################################################## 19 | # Modifications by NXP 2022 20 | ############################################################################## 21 | 22 | @PACKAGE_INIT@ 23 | 24 | include(CMakeFindDependencyMacro) 25 | 26 | find_dependency(iceoryx_hoofs) 27 | find_dependency(iceoryx_posh) 28 | 29 | if(NOT "@FREERTOS@") 30 | find_dependency(cpptoml) 31 | 32 | if(@PCIE_GATEWAY@) 33 | if("@PCIE_BB_TYPE@" STREQUAL "RC") 34 | find_dependency(lx2_sdk COMPONENTS 35 | pcie-bb-rc pcie-bb-dmalib-rc 36 | ) 37 | elseif("@PCIE_BB_TYPE@" STREQUAL "EP") 38 | find_dependency(s32g_sdk COMPONENTS 39 | pcie-bb-ep pcie-bb-dmalib-ep 40 | ) 41 | endif() 42 | endif() 43 | endif() 44 | 45 | include("${CMAKE_CURRENT_LIST_DIR}/@TARGETS_EXPORT_NAME@.cmake") 46 | list(APPEND CMAKE_MODULE_PATH "@CMAKE_INSTALL_PREFIX@/@DESTINATION_CONFIGDIR@") 47 | check_required_components("@PROJECT_NAME@") 48 | -------------------------------------------------------------------------------- /cmake/p3comConfig.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. 2 | # Copyright (c) 2022 by Apex.AI Inc. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # SPDX-License-Identifier: Apache-2.0 17 | 18 | ########## dummyConfig.cmake to be able to use find_package with the source tree ########## 19 | # 20 | 21 | if(NOT ${CMAKE_FIND_PACKAGE_NAME}_FOUND_PRINTED) 22 | message(STATUS "The package '${CMAKE_FIND_PACKAGE_NAME}' is used in source code version.") 23 | set(${CMAKE_FIND_PACKAGE_NAME}_FOUND_PRINTED true CACHE INTERNAL "") 24 | endif() 25 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) 26 | -------------------------------------------------------------------------------- /doc/CycloneDDS.md: -------------------------------------------------------------------------------- 1 | # Integration to Eclipse Cyclone DDS 2 | 3 | Eclipse Cyclone DDS implements optional shared memory communication based on 4 | iceoryx. More information is available on the [Cyclone DDS documentation 5 | website](https://cyclonedds.io/docs/cyclonedds/latest/shared_memory.html) 6 | 7 | To run Cyclone DDS shared memory communication over the p3com gateway with full 8 | performance benefits, you need to apply a patch to Cyclone DDS source code 9 | which disables using network for user data. This is necessary, because Cyclone 10 | DDS will otherwise use the usual network path to reach subscribers on remote 11 | devices, it doesnt understand that iceoryx will deliver data to them. The patch 12 | file is [cyclone_dds.patch][./cyclone_dds.patch). 13 | 14 | After you have applied the patch, you need to re-build the Cyclone DDS library 15 | `libddsc` with the standard build procedure. 16 | 17 | ## Run example 18 | 19 | Now, we can try to run the `ShmThroughtput` example, which tests the throughput 20 | of Cyclone DDS over shared memory, but now it will be also be running over p3com: 21 | 22 | 1) Copy the binaries `ShmThroughputSubscriber`, `ShmThroughputPublisher` and 23 | `libddsc.so.0` to the target devices. 24 | 2) Set the `LD_LIBRARY_PATH` variable to point to the directory with `libddsc.so.0`. 25 | 3) According to the instructions 26 | [here](https://cyclonedds.io/docs/cyclonedds/latest/shared_memory.html#developer-hints), 27 | create the XML file `cyclonedds.xml` with the content: 28 | ```xml 29 | 30 | 33 | 34 | 35 | true 36 | fatal 37 | 38 | 39 | 40 | ``` 41 | 4) Export the environment variable `CYCLONEDDS_URI` to point to the XML file: 42 | `export CYCLONEDDS_URI=/cyclonedds.xml` 43 | 5) Run the shared memory demo, perhaps with 1 MB messages: 44 | `./ShmThroughputPublisher 1048576 0 1 0 "Topic"` on one device and 45 | `./ShmThroughputSubscriber 0 0 "Topic" 1048576` on another device. Note that 46 | you might get a lot of output warnings in the form `Mempool [m_chunkSize = 47 | 16552, numberOfChunks = 100, used_chunks = 100 ] has no more space left`. That 48 | is because the demo is trying to publish samples as fast as possible, which 49 | will exhaust the iceoryx memory pool and some messages are thus discarded. 50 | 51 | All limitations that apply to to shared memory usage in Cyclone DDS over 52 | iceoryx also apply for p3com. In particular, the user should be aware of the 53 | strict requirements on the QoS policies and data types that are needed to 54 | enable shared memory transfers. These are described 55 | [here](https://cyclonedds.io/docs/cyclonedds/latest/shared_memory.html#limitations). 56 | 57 | ### Limitations and future work 58 | 59 | It would be very nice to enable a "hybrid" p3com acceleration of Cyclone DDS, 60 | where DDS topics would have a QoS configuration property setting whether their 61 | data sharing should be accelerated with p3com or rather the default networking 62 | mechanism should be used. This would be useful to leverage the high throughput 63 | of p3com on large-payload topics, while keeping the low latency of the 64 | networking stack for small-payload topics. 65 | -------------------------------------------------------------------------------- /doc/cyclone_dds.patch: -------------------------------------------------------------------------------- 1 | From b7013c64674f37a831a1e7329ce4d7342a3feed4 Mon Sep 17 00:00:00 2001 2 | From: Jakub Sosnovec 3 | Date: Mon, 16 Jan 2023 16:48:25 +0100 4 | Subject: [PATCH] Only SHM exchange, fix ShmThroughput demo 5 | 6 | --- 7 | examples/shm_throughput/shmpublisher.c | 7 ++++++- 8 | src/core/ddsc/src/dds_write.c | 5 ++++- 9 | 2 files changed, 10 insertions(+), 2 deletions(-) 10 | 11 | diff --git a/examples/shm_throughput/shmpublisher.c b/examples/shm_throughput/shmpublisher.c 12 | index 93208aee..9dc21ca0 100644 13 | --- a/examples/shm_throughput/shmpublisher.c 14 | +++ b/examples/shm_throughput/shmpublisher.c 15 | @@ -347,7 +347,12 @@ static void start_writing( 16 | void *loaned_sample; 17 | 18 | if ((status = dds_loan_sample(writer, &loaned_sample)) < 0) 19 | - DDS_FATAL("dds_loan_sample: %s\n", dds_strretcode(-status)); 20 | + { 21 | + /* Dont abort, this might just mean that iceoryx ran out of chunks in 22 | + * the shared memory pool */ 23 | + printf("dds_loan_sample: %s\n", dds_strretcode(-status)); 24 | + continue; 25 | + } 26 | memcpy(loaned_sample, sample, payloadSize); 27 | status = dds_write (writer, loaned_sample); 28 | if (status == DDS_RETCODE_TIMEOUT) 29 | diff --git a/src/core/ddsc/src/dds_write.c b/src/core/ddsc/src/dds_write.c 30 | index 766a7742..2c114ef1 100644 31 | --- a/src/core/ddsc/src/dds_write.c 32 | +++ b/src/core/ddsc/src/dds_write.c 33 | @@ -469,7 +469,10 @@ static dds_return_t dds_write_impl_iox (dds_writer *wr, struct ddsi_writer *ddsi 34 | // The alternative is to block new fast path connections entirely (by holding 35 | // the mutex) until data delivery is complete. 36 | const bool use_only_iceoryx = 37 | - no_network_readers && 38 | + // Just completely ignore network readers, deliver all data via iceoryx 39 | + // only, if the QoS policy is suitable and all local readers are 40 | + // also using iceoryx. 41 | + //no_network_readers && 42 | ddsi_wr->xqos->durability.kind == DDS_DURABILITY_VOLATILE && 43 | num_fast_path_readers == 0; 44 | 45 | -- 46 | 2.25.1 47 | 48 | -------------------------------------------------------------------------------- /include/p3com/gateway/cmd_line.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_CMD_CONFIG_HPP 4 | #define P3COM_CMD_CONFIG_HPP 5 | 6 | #include "p3com/generic/types.hpp" 7 | 8 | namespace iox 9 | { 10 | namespace p3com 11 | { 12 | struct CmdLineArgs_t 13 | { 14 | iox::log::LogLevel logLevel{log::LogLevel::kWarn}; 15 | std::array enabledTransports{}; 16 | bool enabledTransportSpecified{false}; 17 | roudi::ConfigFilePathString_t configFile{}; 18 | bool run{true}; 19 | }; 20 | 21 | class CmdLineParser 22 | { 23 | public: 24 | static CmdLineArgs_t parse(int argc, char** argv) noexcept; 25 | }; 26 | 27 | } // namespace p3com 28 | } // namespace iox 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /include/p3com/gateway/gateway.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_GATEWAY_HPP 4 | #define P3COM_GATEWAY_HPP 5 | 6 | #include "p3com/generic/config.hpp" 7 | #include "p3com/generic/types.hpp" 8 | #include "p3com/utility/vector_map.hpp" 9 | 10 | #include "iceoryx_posh/capro/service_description.hpp" 11 | #include "iceoryx_hoofs/cxx/optional.hpp" 12 | #include "iceoryx_hoofs/cxx/function_ref.hpp" 13 | 14 | #include 15 | #include 16 | 17 | namespace iox 18 | { 19 | namespace p3com 20 | { 21 | template 22 | class Gateway 23 | { 24 | protected: 25 | /** 26 | * @brief Update channels to match the given list of services 27 | * 28 | * @param services 29 | * @param setupFn 30 | * @param deleteFn 31 | */ 32 | void updateChannelsInternal(const ServiceVector_t& services, 33 | cxx::function_ref setupFn, 34 | cxx::function_ref deleteFn) noexcept; 35 | 36 | /** 37 | * @brief Function to be executed *after* the channel creation 38 | * 39 | * @tparam PubSubOptions 40 | * @param service 41 | * @param options 42 | * @param f 43 | */ 44 | template 45 | void addChannel(const capro::ServiceDescription& service, 46 | const PubSubOptions& options, 47 | cxx::function_ref f) noexcept; 48 | 49 | /** 50 | * @brief Function to be executed *before* the channel deletion 51 | * 52 | * @param service 53 | * @param f 54 | */ 55 | void discardChannel(const capro::ServiceDescription& service, cxx::function_ref f) noexcept; 56 | 57 | /** 58 | * @brief Execute a function for a particular endpoint 59 | * 60 | * @param hash 61 | * @param f 62 | */ 63 | void doForChannel(capro::ServiceDescription::ClassHash hash, cxx::function_ref f) noexcept; 64 | 65 | /** 66 | * @brief Get endpoints mutex 67 | * 68 | * @return 69 | */ 70 | std::mutex& endpointsMutex() noexcept; 71 | 72 | private: 73 | /** 74 | * @brief Mutex protecting m_endpoints. 75 | */ 76 | std::mutex m_endpointsMutex; 77 | 78 | /** 79 | * @brief Vector of endpoints 80 | * @note We have to use std::unique_ptr since popo::UntypedPublisher and 81 | * popo::UntypedSubscriber dont have move ctor and move assignment 82 | * operator. 83 | */ 84 | cxx::vector_map, MAX_TOPICS> m_endpoints; 85 | }; 86 | 87 | } // namespace p3com 88 | } // namespace iox 89 | 90 | #include "p3com/internal/gateway/gateway.inl" 91 | 92 | #endif 93 | -------------------------------------------------------------------------------- /include/p3com/gateway/gateway_app.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_GATEWAY_APP_HPP 4 | #define P3COM_GATEWAY_APP_HPP 5 | 6 | #include "p3com/gateway/gateway_config.hpp" 7 | #include "p3com/gateway/cmd_line.hpp" 8 | 9 | namespace iox 10 | { 11 | namespace p3com 12 | { 13 | class GatewayApp 14 | { 15 | public: 16 | GatewayApp(const CmdLineArgs_t& cmdLineArgs, const GatewayConfig_t& gwConfig) noexcept; 17 | 18 | GatewayApp(const GatewayApp&) = delete; 19 | GatewayApp(GatewayApp&&) = delete; 20 | GatewayApp& operator=(const GatewayApp&) = delete; 21 | GatewayApp& operator=(GatewayApp&&) = delete; 22 | 23 | ~GatewayApp(); 24 | 25 | void run() noexcept; 26 | 27 | private: 28 | void enableTransports() noexcept; 29 | 30 | CmdLineArgs_t m_cmdLineArgs; 31 | GatewayConfig_t m_gwConfig; 32 | }; 33 | 34 | } // namespace p3com 35 | } // namespace iox 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /include/p3com/gateway/gateway_config.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_GATEWAY_CONFIG_HPP 4 | #define P3COM_GATEWAY_CONFIG_HPP 5 | 6 | #include "p3com/generic/types.hpp" 7 | 8 | namespace iox 9 | { 10 | namespace p3com 11 | { 12 | struct GatewayConfig_t 13 | { 14 | TransportType preferredTransport{TransportType::NONE}; 15 | cxx::vector forwardedServices; 16 | }; 17 | 18 | class TomlGatewayConfigParser 19 | { 20 | public: 21 | static GatewayConfig_t parse(roudi::ConfigFilePathString_t path) noexcept; 22 | }; 23 | 24 | } // namespace p3com 25 | } // namespace iox 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /include/p3com/gateway/iox_to_transport.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_IOX_TO_TRANSPORT_HPP 4 | #define P3COM_IOX_TO_TRANSPORT_HPP 5 | 6 | #include "iceoryx_posh/popo/untyped_subscriber.hpp" 7 | #include "iceoryx_posh/popo/wait_set.hpp" 8 | 9 | #include "p3com/generic/config.hpp" 10 | #include "p3com/gateway/gateway.hpp" 11 | #include "p3com/generic/types.hpp" 12 | #include "p3com/generic/pending_messages.hpp" 13 | #include "p3com/generic/data_writer.hpp" 14 | #include "p3com/generic/discovery.hpp" 15 | #include "p3com/transport/transport.hpp" 16 | #include "p3com/utility/vector_map.hpp" 17 | 18 | namespace iox 19 | { 20 | namespace p3com 21 | { 22 | /// 23 | /// @brief p3com gateway implementation for the iceoryx to transport direction. 24 | /// 25 | class Iceoryx2Transport : public Gateway 26 | { 27 | public: 28 | explicit Iceoryx2Transport(DiscoveryManager& discovery, PendingMessageManager& pendingMessageManager) noexcept; 29 | 30 | void updateChannels(const ServiceVector_t& services) noexcept; 31 | 32 | void join() noexcept; 33 | 34 | private: 35 | void setupChannel(const capro::ServiceDescription& service) noexcept; 36 | void deleteChannel(const capro::ServiceDescription& service) noexcept; 37 | 38 | void waitsetLoop() noexcept; 39 | 40 | DiscoveryManager& m_discovery; 41 | PendingMessageManager& m_pendingMessageManager; 42 | 43 | std::mutex m_waitsetMutex; 44 | popo::WaitSet m_waitset; 45 | 46 | std::atomic m_terminateFlag; 47 | std::atomic m_suspendFlag; 48 | std::thread m_waitsetThread; 49 | }; 50 | 51 | } // namespace p3com 52 | } // namespace iox 53 | 54 | #endif // P3COM_IOX_TO_TRANSPORT_HPP 55 | -------------------------------------------------------------------------------- /include/p3com/gateway/transport_to_iox.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_TRANSPORT_TO_IOX_HPP 4 | #define P3COM_TRANSPORT_TO_IOX_HPP 5 | 6 | #include "iceoryx_posh/popo/untyped_publisher.hpp" 7 | 8 | #include "p3com/gateway/gateway.hpp" 9 | #include "p3com/generic/data_reader.hpp" 10 | #include "p3com/generic/discovery.hpp" 11 | #include "p3com/generic/segmented_messages.hpp" 12 | #include "p3com/generic/transport_forwarder.hpp" 13 | #include "p3com/generic/types.hpp" 14 | #include "p3com/transport/transport.hpp" 15 | #include "p3com/utility/vector_map.hpp" 16 | 17 | #include 18 | 19 | namespace iox 20 | { 21 | namespace p3com 22 | { 23 | /// 24 | /// @brief p3com gateway implementation for the transport to iceoryx direction. 25 | /// 26 | class Transport2Iceoryx : public Gateway 27 | { 28 | public: 29 | explicit Transport2Iceoryx(DiscoveryManager& discovery, 30 | TransportForwarder& transportForwarder, 31 | SegmentedMessageManager& segmentedMessageManager) noexcept; 32 | 33 | void updateChannels(const ServiceVector_t& services) noexcept; 34 | 35 | private: 36 | void setupChannel(const capro::ServiceDescription& service) noexcept; 37 | void deleteChannel(const capro::ServiceDescription& service) noexcept; 38 | 39 | void receive(const void* receivedUserPayload, size_t size, DeviceIndex_t deviceIndex) noexcept; 40 | void* loanBuffer(const void* serializedDatagramHeader, size_t size) noexcept; 41 | void releaseBuffer(const void* serializedDatagramHeader, 42 | size_t size, 43 | bool shoudRelease, 44 | DeviceIndex_t deviceIndex) noexcept; 45 | 46 | DiscoveryManager& m_discovery; 47 | TransportForwarder& m_transportForwarder; 48 | SegmentedMessageManager& m_segmentedMessageManager; 49 | }; 50 | 51 | } // namespace p3com 52 | } // namespace iox 53 | 54 | #endif // P3COM_TRANSPORT_TO_IOX_HPP 55 | -------------------------------------------------------------------------------- /include/p3com/generic/config.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_CONFIG_HPP 4 | #define P3COM_CONFIG_HPP 5 | 6 | #include "iceoryx_posh/capro/service_description.hpp" 7 | #include "iceoryx_posh/iceoryx_posh_types.hpp" 8 | 9 | #include 10 | 11 | namespace iox 12 | { 13 | namespace p3com 14 | { 15 | constexpr std::chrono::milliseconds DISCOVERY_PERIOD{200U}; 16 | constexpr std::chrono::milliseconds BROADCAST_SEND_TIMEOUT{50U}; 17 | constexpr std::chrono::milliseconds LOSSY_TRANSPORT_DISCOVERY_PERIOD{500U}; 18 | 19 | const RuntimeName_t IOX_GW_RUNTIME_NAME{"p3com-gw"}; 20 | const NodeName_t IOX_GW_NODE_NAME{"p3com-gw"}; 21 | 22 | #if defined(__FREERTOS__) 23 | constexpr uint32_t MAX_TOPICS{6U}; 24 | #else 25 | constexpr uint32_t MAX_TOPICS{32U}; 26 | #endif 27 | 28 | constexpr uint32_t TRANSPORT_TYPE_COUNT{4U}; 29 | 30 | #if defined(__FREERTOS___) 31 | constexpr uint32_t MAX_DEVICE_COUNT{2U}; 32 | constexpr uint32_t MAX_FORWARDED_SERVICES{0U}; 33 | #else 34 | constexpr uint32_t MAX_DEVICE_COUNT{10U}; 35 | constexpr uint32_t MAX_FORWARDED_SERVICES{8U}; 36 | #endif 37 | 38 | constexpr uint32_t USER_HEADER_ALIGNMENT{8U}; 39 | constexpr uint32_t MAX_NETWORK_IFACE_COUNT{10U}; 40 | 41 | } // namespace p3com 42 | } // namespace iox 43 | 44 | #endif // P3COM_CONFIG_HPP 45 | -------------------------------------------------------------------------------- /include/p3com/generic/data_reader.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_DATA_READER_HPP 4 | #define P3COM_DATA_READER_HPP 5 | 6 | #include "p3com/generic/types.hpp" 7 | 8 | namespace iox 9 | { 10 | namespace p3com 11 | { 12 | /** 13 | * @brief Take the next available sample 14 | * 15 | * @param datagramHeader 16 | * @param data 17 | * @param userHeaderBuffer 18 | * @param userPayloadBuffer 19 | */ 20 | void takeNext(const IoxChunkDatagramHeader_t& datagramHeader, 21 | const void* data, 22 | uint8_t* userHeaderBuffer, 23 | uint8_t* userPayloadBuffer) noexcept; 24 | 25 | } // namespace p3com 26 | } // namespace iox 27 | 28 | #endif // P3COM_DATA_READER_HPP 29 | -------------------------------------------------------------------------------- /include/p3com/generic/data_writer.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_DATA_WRITER_HPP 4 | #define P3COM_DATA_WRITER_HPP 5 | 6 | #include "p3com/generic/pending_messages.hpp" 7 | #include "p3com/generic/types.hpp" 8 | 9 | #include "iceoryx_posh/mepoo/chunk_header.hpp" 10 | 11 | namespace iox 12 | { 13 | namespace p3com 14 | { 15 | /** 16 | * @brief Write the user message over all enabled transport layers. 17 | * 18 | * @param datagramHeader 19 | * @param chunkHeader 20 | * @param deviceIndices 21 | * @param pendingMessageManager 22 | * @param subscriber 23 | * 24 | * @return 25 | */ 26 | void writeSegmented(IoxChunkDatagramHeader_t& datagramHeader, 27 | const mepoo::ChunkHeader& chunkHeader, 28 | const cxx::vector& deviceIndices, 29 | PendingMessageManager& pendingMessageManager, 30 | std::mutex& mutex, 31 | popo::UntypedSubscriber& subscriber) noexcept; 32 | 33 | } // namespace p3com 34 | } // namespace iox 35 | 36 | #endif // P3COM_DATA_WRITER_HPP 37 | -------------------------------------------------------------------------------- /include/p3com/generic/discovery.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_DISCOVERY_HPP 4 | #define P3COM_DISCOVERY_HPP 5 | 6 | #include "iceoryx_posh/popo/wait_set.hpp" 7 | #include "iceoryx_posh/roudi/introspection_types.hpp" 8 | #include "iceoryx_posh/capro/service_description.hpp" 9 | #include "iceoryx_posh/popo/subscriber.hpp" 10 | #include "iceoryx_posh/popo/publisher.hpp" 11 | 12 | #include "p3com/generic/types.hpp" 13 | #include "p3com/introspection/gw_introspection_types.hpp" 14 | #include "p3com/gateway/gateway_config.hpp" 15 | #include "p3com/utility/vector_map.hpp" 16 | #include "p3com/transport/transport.hpp" 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | namespace iox 23 | { 24 | namespace p3com 25 | { 26 | struct LocalState_t 27 | { 28 | ServiceVector_t userPublishers; 29 | ServiceVector_t userSubscribers; 30 | cxx::vector userPublisherPorts; 31 | }; 32 | 33 | struct DeviceRecord_t 34 | { 35 | PubSubInfo_t info; 36 | cxx::vector deviceIndices; 37 | }; 38 | 39 | using DeviceIndexVector_t = cxx::vector; 40 | 41 | struct RemoteState_t 42 | { 43 | cxx::vector records; 44 | cxx::vector_map deviceIndicesCache; 45 | }; 46 | 47 | class DiscoveryManager 48 | { 49 | public: 50 | explicit DiscoveryManager(const GatewayConfig_t& config) noexcept; 51 | ~DiscoveryManager() = default; 52 | 53 | DiscoveryManager(const DiscoveryManager&) = delete; 54 | DiscoveryManager(DiscoveryManager&&) = delete; 55 | DiscoveryManager& operator=(const DiscoveryManager&) = delete; 56 | DiscoveryManager& operator=(DiscoveryManager&&) = delete; 57 | 58 | void initialize(cxx::function_ref updateCallback) noexcept; 59 | void deinitialize() noexcept; 60 | 61 | void addGatewayPublisher(const popo::UniquePortId& uid) noexcept; 62 | void discardGatewayPublisher(const popo::UniquePortId& uid) noexcept; 63 | 64 | const DeviceIndexVector_t& generateDeviceIndices(const popo::UniquePortId& uid, 65 | const capro::ServiceDescription::ClassHash& serviceHash) noexcept; 66 | 67 | DeviceIndexVector_t generateDeviceIndicesForwarding(const capro::ServiceDescription::ClassHash& serviceHash, 68 | DeviceIndex_t fromDeviceIndex) noexcept; 69 | 70 | void resendDiscoveryInfoToTransport(TransportType type) noexcept; 71 | 72 | private: 73 | DeviceIndexVector_t computeDeviceIndices(const capro::ServiceDescription::ClassHash& serviceHash) const 74 | noexcept; 75 | 76 | PubSubInfo_t generateDiscoveryInfo() noexcept; 77 | static void sendDiscoveryInfo(const PubSubInfo_t& info) noexcept; 78 | 79 | void waitsetLoop() noexcept; 80 | void readPortSubscriber() noexcept; 81 | 82 | void receiveRemoteDiscoveryInfo(const void* serializedData, size_t size, DeviceIndex_t deviceIndex) noexcept; 83 | ServiceVector_t updateNeededChannels() const noexcept; 84 | 85 | const hash_t m_gatewayHash; 86 | const TransportType m_preferredType; 87 | 88 | mutable std::recursive_mutex m_mutex; 89 | cxx::function_ref m_updateCallback; 90 | 91 | popo::Subscriber m_portSubscriber; 92 | 93 | popo::Publisher m_gwIntrospectionPublisher; 94 | 95 | RemoteState_t m_remoteState; 96 | LocalState_t m_localState; 97 | 98 | // Store local gateway publisher UIDs 99 | cxx::vector m_gatewayPublisherUids; 100 | // Store last sent discovery info 101 | PubSubInfo_t m_lastSentDiscoveryInfo; 102 | 103 | popo::WaitSet<1U> m_waitset; 104 | std::atomic m_terminateFlag; 105 | std::thread m_waitsetThread; 106 | }; 107 | 108 | } // namespace p3com 109 | } // namespace iox 110 | 111 | #endif // P3COM_DISCOVERY_HPP 112 | -------------------------------------------------------------------------------- /include/p3com/generic/pending_messages.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_PENDING_MESSAGES_HPP 4 | #define P3COM_PENDING_MESSAGES_HPP 5 | 6 | #include "p3com/utility/vector_map.hpp" 7 | 8 | #include "iceoryx_posh/popo/untyped_subscriber.hpp" 9 | 10 | namespace iox 11 | { 12 | namespace p3com 13 | { 14 | class PendingMessageManager 15 | { 16 | public: 17 | PendingMessageManager() noexcept; 18 | 19 | PendingMessageManager(const PendingMessageManager&) = delete; 20 | PendingMessageManager(PendingMessageManager&&) = delete; 21 | PendingMessageManager& operator=(const PendingMessageManager&) = delete; 22 | PendingMessageManager& operator=(PendingMessageManager&&) = delete; 23 | ~PendingMessageManager() = default; 24 | 25 | bool push(const void* userPayload, std::mutex& mutex, popo::UntypedSubscriber& subscriber) noexcept; 26 | 27 | bool anyPending(popo::UntypedSubscriber& subscriber) noexcept; 28 | 29 | void release(const void* userPayload) noexcept; 30 | 31 | private: 32 | struct PendingMessage_t 33 | { 34 | uint32_t counter; 35 | std::mutex* mutex; 36 | popo::UntypedSubscriber* subscriber; 37 | }; 38 | 39 | std::mutex m_mutex; 40 | #if defined(__FREERTOS__) 41 | static constexpr uint32_t MAX_PENDING_MESSAGE_COUNT = 4U; 42 | #else 43 | static constexpr uint32_t MAX_PENDING_MESSAGE_COUNT = 512U; 44 | #endif 45 | cxx::vector_map m_pendingMessages; 46 | }; 47 | 48 | } // namespace p3com 49 | } // namespace iox 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /include/p3com/generic/segmented_messages.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_SEGMENTED_MESSAGES_HPP 4 | #define P3COM_SEGMENTED_MESSAGES_HPP 5 | 6 | #include "p3com/utility/vector_map.hpp" 7 | #include "p3com/generic/types.hpp" 8 | 9 | #include "iceoryx_posh/popo/untyped_publisher.hpp" 10 | 11 | namespace iox 12 | { 13 | namespace p3com 14 | { 15 | class SegmentedMessageManager 16 | { 17 | public: 18 | SegmentedMessageManager() noexcept = default; 19 | 20 | SegmentedMessageManager(const SegmentedMessageManager&) = delete; 21 | SegmentedMessageManager(SegmentedMessageManager&&) = delete; 22 | SegmentedMessageManager& operator=(const SegmentedMessageManager&) = delete; 23 | SegmentedMessageManager& operator=(SegmentedMessageManager&&) = delete; 24 | ~SegmentedMessageManager() = default; 25 | 26 | void push(hash_t messageHash, 27 | uint32_t remainingSegments, 28 | void* userHeader, 29 | void* userPayload, 30 | std::mutex& mutex, 31 | popo::UntypedPublisher& publisher, 32 | std::chrono::steady_clock::time_point deadline) noexcept; 33 | 34 | bool find(hash_t messageHash, void*& userHeader, void*& userPayload) noexcept; 35 | bool findAndDecrement(hash_t messageHash, void*& userHeader, void*& userPayload, bool& shouldPublish) noexcept; 36 | 37 | void release(hash_t messageHash) noexcept; 38 | void releaseAll(popo::UntypedPublisher& publisher) noexcept; 39 | 40 | void checkSegmentedMessages() noexcept; 41 | 42 | private: 43 | void release(const void* userPayload) noexcept; 44 | 45 | struct SegmentedMessage_t 46 | { 47 | uint32_t remainingSegments; 48 | void* userHeader; 49 | void* userPayload; 50 | std::mutex* mutex; 51 | iox::popo::UntypedPublisher* publisher; 52 | std::chrono::steady_clock::time_point deadline; 53 | }; 54 | 55 | std::mutex m_mutex; 56 | #if defined(__FREERTOS__) 57 | static constexpr uint32_t MAX_SEGMENTED_MESSAGE_COUNT = 4U; 58 | #else 59 | static constexpr uint32_t MAX_SEGMENTED_MESSAGE_COUNT = 64U; 60 | #endif 61 | cxx::vector_map m_segmentedMessages; 62 | }; 63 | 64 | } // namespace p3com 65 | } // namespace iox 66 | 67 | #endif 68 | -------------------------------------------------------------------------------- /include/p3com/generic/serialization.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_SERIALIZATION_HPP 4 | #define P3COM_SERIALIZATION_HPP 5 | 6 | #include "p3com/generic/types.hpp" 7 | 8 | namespace iox 9 | { 10 | namespace p3com 11 | { 12 | constexpr inline uint32_t maxPubSubInfoSerializationSize() noexcept 13 | { 14 | size_t total_size = 0U; 15 | 16 | total_size += sizeof(uint64_t); // Number of topics for userSubscribers 17 | 18 | // Each string is serialized as its c_str, with null-character 19 | constexpr uint32_t SERVICE_DESCRIPTION_SER_SIZE = 3 * (capro::IdString_t::capacity() + 1); 20 | total_size += MAX_TOPICS * SERVICE_DESCRIPTION_SER_SIZE; 21 | 22 | total_size += sizeof(bitset_t); // gatewayBitset 23 | total_size += sizeof(hash_t); // gatewayHash 24 | total_size += sizeof(hash_t); // infoHash 25 | total_size += sizeof(bool); // isTermination 26 | 27 | return static_cast(total_size); 28 | } 29 | 30 | constexpr inline uint32_t maxIoxChunkDatagramHeaderSerializationSize() noexcept 31 | { 32 | size_t total_size = 0U; 33 | 34 | total_size += capro::CLASS_HASH_ELEMENT_COUNT * sizeof(uint32_t); // serviceHash 35 | total_size += sizeof(hash_t); // messageHash 36 | total_size += sizeof(uint32_t); // submessageCount 37 | total_size += sizeof(uint32_t); // submessageOffset 38 | total_size += sizeof(uint32_t); // submessageSize 39 | total_size += sizeof(uint32_t); // userPayloadSize 40 | total_size += sizeof(uint32_t); // userPayloadAlignment 41 | total_size += sizeof(uint32_t); // userHeaderSize 42 | 43 | return static_cast(total_size); 44 | } 45 | 46 | 47 | uint32_t serialize(const PubSubInfo_t& info, char* ptr) noexcept; 48 | uint32_t deserialize(PubSubInfo_t& info, const char* ptr, size_t size) noexcept; 49 | 50 | uint32_t serialize(const IoxChunkDatagramHeader_t& datagramHeader, char* ptr) noexcept; 51 | uint32_t deserialize(IoxChunkDatagramHeader_t& datagramHeader, const char* ptr, size_t size) noexcept; 52 | 53 | } // namespace p3com 54 | } // namespace iox 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /include/p3com/generic/transport_forwarder.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_TRANSPORT_FORWARDER_HPP 4 | #define P3COM_TRANSPORT_FORWARDER_HPP 5 | 6 | #include "p3com/generic/config.hpp" 7 | #include "p3com/generic/discovery.hpp" 8 | #include "p3com/generic/pending_messages.hpp" 9 | #include "p3com/utility/vector_map.hpp" 10 | 11 | #include "iceoryx_posh/capro/service_description.hpp" 12 | 13 | namespace iox 14 | { 15 | namespace p3com 16 | { 17 | class TransportForwarder 18 | { 19 | public: 20 | TransportForwarder( 21 | DiscoveryManager& discovery, 22 | PendingMessageManager& pendingMessageManager, 23 | const cxx::vector& forwardedServices) noexcept; 24 | 25 | TransportForwarder(const TransportForwarder&) = delete; 26 | TransportForwarder(TransportForwarder&&) = delete; 27 | TransportForwarder& operator=(const TransportForwarder&) = delete; 28 | TransportForwarder& operator=(TransportForwarder&&) = delete; 29 | ~TransportForwarder() = default; 30 | 31 | void push(const void* userPayload, capro::ServiceDescription::ClassHash hash, DeviceIndex_t deviceIndex) noexcept; 32 | 33 | void join() noexcept; 34 | 35 | private: 36 | void waitsetLoop() noexcept; 37 | 38 | DiscoveryManager& m_discovery; 39 | PendingMessageManager& m_pendingMessageManager; 40 | 41 | cxx::vector m_forwardedServiceHashes; 42 | 43 | std::mutex m_forwardedServiceSubscribersMutex; 44 | cxx::vector m_forwardedServiceSubscribers; 45 | 46 | std::mutex m_messagesToForwardMutex; 47 | cxx::vector_map m_messagesToForward; 48 | 49 | popo::WaitSet m_waitset; 50 | 51 | std::atomic m_terminateFlag; 52 | std::thread m_waitsetThread; 53 | }; 54 | 55 | } // namespace p3com 56 | } // namespace iox 57 | 58 | #endif 59 | -------------------------------------------------------------------------------- /include/p3com/generic/types.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_TYPES_HPP 4 | #define P3COM_TYPES_HPP 5 | 6 | #include "iceoryx_hoofs/cxx/optional.hpp" 7 | #include "iceoryx_hoofs/cxx/vector.hpp" 8 | #include "iceoryx_posh/capro/service_description.hpp" 9 | #include "iceoryx_posh/iceoryx_posh_types.hpp" 10 | 11 | #include "p3com/generic/config.hpp" 12 | #include "p3com/transport/transport_type.hpp" 13 | 14 | #include 15 | #include 16 | 17 | namespace iox 18 | { 19 | namespace p3com 20 | { 21 | using hash_t = uint32_t; 22 | using bitset_t = std::bitset<64U>; // Force 64 bits even though we only need TRANSPORT_TYPE_COUNT, to be consistent 23 | // between 32bit and 64bit platforms 24 | static_assert(sizeof(bitset_t) == 8U, ""); 25 | 26 | // List of service 27 | using ServiceVector_t = cxx::vector; 28 | 29 | /** 30 | * @brief Device index 31 | */ 32 | struct DeviceIndex_t 33 | { 34 | // Type of transport 35 | TransportType type; 36 | // Device number 37 | uint32_t device; 38 | }; 39 | 40 | /** 41 | * @brief Information of publisher and subscriber 42 | */ 43 | struct PubSubInfo_t 44 | { 45 | // Vector service of user subscribers 46 | ServiceVector_t userSubscribers; 47 | // Gateway bitset 48 | bitset_t gatewayBitset; 49 | // Gateway hash 50 | hash_t gatewayHash; 51 | // Information of hash 52 | hash_t infoHash; 53 | // Status termination 54 | bool isTermination; 55 | }; 56 | 57 | /** 58 | * @brief Save data of header for a iox chunk 59 | */ 60 | struct IoxChunkDatagramHeader_t 61 | { 62 | // Service hash 63 | capro::ServiceDescription::ClassHash serviceHash; 64 | // Unique hash of this message, used to group submessages into messages 65 | hash_t messageHash; 66 | // Number of submessages that this message consists of 67 | uint32_t submessageCount; 68 | // Offset into the data that this message carries 69 | uint32_t submessageOffset; 70 | // Data size of this particular submessage 71 | uint32_t submessageSize; 72 | // Total payload size of this whole message 73 | uint32_t userPayloadSize; 74 | // User payload alignment 75 | uint32_t userPayloadAlignment; 76 | // User header size 77 | uint32_t userHeaderSize; 78 | }; 79 | 80 | } // namespace p3com 81 | } // namespace iox 82 | 83 | #endif // P3COM_TYPES_HPP 84 | -------------------------------------------------------------------------------- /include/p3com/internal/gateway/gateway.inl: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_INTERNAL_GATEWAY_HPP 4 | #define P3COM_INTERNAL_GATEWAY_HPP 5 | 6 | #include "p3com/utility/helper_functions.hpp" 7 | #include "p3com/internal/log/logging.hpp" 8 | 9 | template 10 | inline void iox::p3com::Gateway::updateChannelsInternal( 11 | const iox::p3com::ServiceVector_t& services, 12 | iox::cxx::function_ref setupFn, 13 | iox::cxx::function_ref deleteFn) noexcept 14 | { 15 | iox::p3com::ServiceVector_t servicesToDelete; 16 | iox::p3com::ServiceVector_t servicesToSetup; 17 | 18 | std::lock_guard lock{m_endpointsMutex}; 19 | 20 | for (const auto& endpoint : m_endpoints) 21 | { 22 | const auto service = endpoint->getServiceDescription(); 23 | if (!iox::p3com::containsElement(services, service)) 24 | { 25 | servicesToDelete.push_back(service); 26 | } 27 | } 28 | 29 | for (const auto& service : services) 30 | { 31 | const auto hash = service.getClassHash(); 32 | auto it = m_endpoints.find(hash); 33 | 34 | if (it == m_endpoints.end()) 35 | { 36 | servicesToSetup.push_back(service); 37 | } 38 | } 39 | 40 | for (const auto& service : servicesToDelete) 41 | { 42 | deleteFn(service); 43 | } 44 | for (const auto& service : servicesToSetup) 45 | { 46 | setupFn(service); 47 | } 48 | } 49 | 50 | template 51 | template 52 | inline void iox::p3com::Gateway::addChannel(const iox::capro::ServiceDescription& service, 53 | const PubSubOptions& options, 54 | iox::cxx::function_ref f) noexcept 55 | { 56 | const bool emplaced = m_endpoints.emplace(service.getClassHash(), std::make_unique(service, options)); 57 | if (!emplaced) 58 | { 59 | iox::p3com::LogError() << "[Gateway] Could not add new channel for service: " << service; 60 | } 61 | else 62 | { 63 | f(*m_endpoints.back()); 64 | } 65 | } 66 | 67 | 68 | template 69 | inline void iox::p3com::Gateway::discardChannel(const iox::capro::ServiceDescription& service, 70 | iox::cxx::function_ref f) noexcept 71 | { 72 | auto it = m_endpoints.find(service.getClassHash()); 73 | if (it == m_endpoints.end()) 74 | { 75 | iox::p3com::LogError() << "[Gateway] Could not discard channel for service: " << service; 76 | } 77 | else 78 | { 79 | f(**it); 80 | m_endpoints.erase(it); 81 | } 82 | } 83 | 84 | template 85 | inline void iox::p3com::Gateway::doForChannel(iox::capro::ServiceDescription::ClassHash hash, 86 | iox::cxx::function_ref f) noexcept 87 | { 88 | std::lock_guard lock{m_endpointsMutex}; 89 | 90 | auto it = m_endpoints.find(hash); 91 | if (it != m_endpoints.end()) 92 | { 93 | f(**it); 94 | } 95 | } 96 | 97 | template 98 | inline std::mutex& iox::p3com::Gateway::endpointsMutex() noexcept 99 | { 100 | return m_endpointsMutex; 101 | } 102 | 103 | #endif 104 | -------------------------------------------------------------------------------- /include/p3com/internal/log/logging.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | // SPDX-License-Identifier: Apache-2.0 16 | 17 | /* Modifications by NXP 2023 */ 18 | 19 | #ifndef P3COM_LOGGING_HPP 20 | #define P3COM_LOGGING_HPP 21 | 22 | #include "iceoryx_hoofs/log/logging_free_function_building_block.hpp" 23 | 24 | namespace iox 25 | { 26 | namespace p3com 27 | { 28 | /** 29 | * @brief Log component 30 | * 31 | */ 32 | struct P3comLoggingComponent 33 | { 34 | // Ctx 35 | static constexpr char Ctx[]{"p3com"}; 36 | // Description 37 | static constexpr char Description[]{"Log context of the p3com module."}; 38 | }; 39 | 40 | static constexpr auto LogFatal = iox::log::ffbb::LogFatal; 41 | static constexpr auto LogError = iox::log::ffbb::LogError; 42 | static constexpr auto LogWarn = iox::log::ffbb::LogWarn; 43 | static constexpr auto LogInfo = iox::log::ffbb::LogInfo; 44 | static constexpr auto LogDebug = iox::log::ffbb::LogDebug; 45 | static constexpr auto LogVerbose = iox::log::ffbb::LogVerbose; 46 | 47 | } // namespace p3com 48 | } // namespace iox 49 | 50 | #endif // P3COM_LOGGING_HPP 51 | -------------------------------------------------------------------------------- /include/p3com/internal/utility/vector_map.inl: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_UTILITY_VECTOR_MAP_INL 4 | #define P3COM_UTILITY_VECTOR_MAP_INL 5 | 6 | template 7 | inline typename iox::cxx::vector_map::const_iterator 8 | iox::cxx::vector_map::find(const Key& key) const noexcept 9 | { 10 | const auto it = std::find(m_keys.begin(), m_keys.end(), key); 11 | if (it == m_keys.end()) 12 | { 13 | return end(); 14 | } 15 | 16 | const auto index = std::distance(m_keys.begin(), it); 17 | return begin() + index; 18 | } 19 | 20 | template 21 | inline typename iox::cxx::vector_map::iterator 22 | iox::cxx::vector_map::find(const Key& key) noexcept 23 | { 24 | const auto it = std::find(m_keys.begin(), m_keys.end(), key); 25 | if (it == m_keys.end()) 26 | { 27 | return end(); 28 | } 29 | 30 | const auto index = std::distance(m_keys.begin(), it); 31 | return begin() + index; 32 | } 33 | 34 | template 35 | template 36 | inline bool iox::cxx::vector_map::emplace(const Key& key, Targs&&... args) noexcept 37 | { 38 | const bool emplaced = m_keys.push_back(key) && m_elems.emplace_back(std::forward(args)...); 39 | return emplaced; 40 | } 41 | 42 | template 43 | inline void iox::cxx::vector_map::erase(iterator it) noexcept 44 | { 45 | const auto index = std::distance(m_elems.begin(), it); 46 | m_keys.erase(m_keys.begin() + index); 47 | m_elems.erase(m_elems.begin() + index); 48 | } 49 | 50 | template 51 | inline void iox::cxx::vector_map::clear() noexcept 52 | { 53 | m_keys.clear(); 54 | m_elems.clear(); 55 | } 56 | 57 | template 58 | inline typename iox::cxx::vector_map::iterator 59 | iox::cxx::vector_map::begin() noexcept 60 | { 61 | return m_elems.begin(); 62 | } 63 | 64 | template 65 | inline typename iox::cxx::vector_map::iterator iox::cxx::vector_map::end() noexcept 66 | { 67 | return m_elems.end(); 68 | } 69 | 70 | template 71 | inline typename iox::cxx::vector_map::const_iterator 72 | iox::cxx::vector_map::begin() const noexcept 73 | { 74 | return m_elems.begin(); 75 | } 76 | 77 | template 78 | inline typename iox::cxx::vector_map::const_iterator 79 | iox::cxx::vector_map::end() const noexcept 80 | { 81 | return m_elems.end(); 82 | } 83 | 84 | template 85 | inline typename iox::cxx::vector_map::mapped_type& 86 | iox::cxx::vector_map::front() noexcept 87 | { 88 | return m_elems.front(); 89 | } 90 | 91 | template 92 | inline typename iox::cxx::vector_map::mapped_type& 93 | iox::cxx::vector_map::back() noexcept 94 | { 95 | return m_elems.back(); 96 | } 97 | 98 | template 99 | inline const typename iox::cxx::vector_map::mapped_type& 100 | iox::cxx::vector_map::front() const noexcept 101 | { 102 | return m_elems.front(); 103 | } 104 | 105 | template 106 | inline const typename iox::cxx::vector_map::mapped_type& 107 | iox::cxx::vector_map::back() const noexcept 108 | { 109 | return m_elems.back(); 110 | } 111 | 112 | template 113 | inline uint64_t iox::cxx::vector_map::size() const noexcept 114 | { 115 | return m_elems.size(); 116 | } 117 | 118 | #endif 119 | -------------------------------------------------------------------------------- /include/p3com/introspection/gw_introspection.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_GW_INTROSPECTION_HPP 4 | #define P3COM_GW_INTROSPECTION_HPP 5 | 6 | #include 7 | 8 | #include "iceoryx_posh/capro/service_description.hpp" 9 | #include "iceoryx_posh/popo/publisher.hpp" 10 | #include "iceoryx_hoofs/internal/units/duration.hpp" 11 | 12 | namespace iox 13 | { 14 | namespace p3com 15 | { 16 | bool isGwRunning() noexcept; 17 | 18 | bool hasGwRegistered(popo::uid_t publisherUid) noexcept; 19 | 20 | bool waitForGwRegistration(popo::uid_t publisherUid, units::Duration timeout = units::Duration::max()) noexcept; 21 | 22 | bool hasServiceRegistered(const capro::ServiceDescription& service) noexcept; 23 | 24 | bool waitForServiceRegistration(const capro::ServiceDescription& service, 25 | units::Duration timeout = units::Duration::max()) noexcept; 26 | 27 | } // namespace p3com 28 | } // namespace iox 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /include/p3com/introspection/gw_introspection_types.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_GW_INTROSPECTION_TYPES_HPP 4 | #define P3COM_GW_INTROSPECTION_TYPES_HPP 5 | 6 | #include "iceoryx_posh/capro/service_description.hpp" 7 | #include "iceoryx_posh/roudi/introspection_types.hpp" 8 | #include "p3com/generic/config.hpp" 9 | 10 | namespace iox 11 | { 12 | namespace p3com 13 | { 14 | /** 15 | * @brief List of publisher IDs that are registered with the p3com gateway 16 | */ 17 | using GwRegisteredPublisherPortData = cxx::vector; 18 | using GwRegisteredSubscriberServicesData = cxx::vector; 19 | 20 | struct GwRegisteredData 21 | { 22 | GwRegisteredPublisherPortData publisherUids; 23 | GwRegisteredSubscriberServicesData subscriberServices; 24 | }; 25 | 26 | const capro::ServiceDescription 27 | IntrospectionGwService(roudi::INTROSPECTION_SERVICE_ID, "RouDi_ID", "RegisteredPublishers"); 28 | 29 | } // namespace p3com 30 | } // namespace iox 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /include/p3com/transport/tcp/tcp_client_transport_session.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef IOX_TCP_CLIENT_TRANSPORT_SESSION_HPP 4 | #define IOX_TCP_CLIENT_TRANSPORT_SESSION_HPP 5 | 6 | #include "p3com/internal/log/logging.hpp" 7 | #include "p3com/transport/tcp/tcp_transport_session.hpp" 8 | 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | namespace iox 15 | { 16 | namespace p3com 17 | { 18 | namespace tcp 19 | { 20 | class TCPClientTransportSession : public TCPTransportSession 21 | { 22 | public: 23 | using sessionOpenCallback_t = std::function; 24 | 25 | TCPClientTransportSession(asio::io_service& io_service, 26 | const dataCallback_t& dataCallbackHandler, 27 | const sessionClosedCallback_t& sessionClosedHandler, 28 | const sessionOpenCallback_t& sessionOpenHandler, 29 | asio::ip::tcp::endpoint remote_endpoint = asio::ip::tcp::endpoint(), 30 | int max_reconnection_attempts = 3) noexcept; 31 | 32 | asio::ip::tcp::endpoint remoteEndpoint() noexcept override; 33 | void start() noexcept override; 34 | 35 | private: 36 | static constexpr std::chrono::seconds M_RETRY_TIMEOUT{1}; 37 | 38 | asio::ip::tcp::resolver m_resolver; 39 | asio::ip::tcp::endpoint m_remoteEndpoint; 40 | int m_retriesLeft; 41 | asio::steady_timer m_retryTimer; 42 | const sessionOpenCallback_t m_sessionOpenCallback; 43 | 44 | void connectToEndpoint() noexcept; 45 | void connectionFailedHandler() noexcept; 46 | }; 47 | 48 | } // namespace tcp 49 | } // namespace p3com 50 | } // namespace iox 51 | 52 | #endif // IOX_TCP_CLIENT_TRANSPORT_SESSION_HPP 53 | -------------------------------------------------------------------------------- /include/p3com/transport/tcp/tcp_server_transport_session.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef IOX_TCP_SERVER_TRANSPORT_SESSION_HPP 4 | #define IOX_TCP_SERVER_TRANSPORT_SESSION_HPP 5 | 6 | #include "p3com/transport/tcp/tcp_transport_session.hpp" 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | namespace iox 14 | { 15 | namespace p3com 16 | { 17 | namespace tcp 18 | { 19 | class TCPServerTransportSession : public TCPTransportSession 20 | { 21 | public: 22 | TCPServerTransportSession(asio::io_service& io_service, 23 | const dataCallback_t& dataCallbackHandler, 24 | const sessionClosedCallback_t& sessionClosedHandler) noexcept; 25 | 26 | asio::ip::tcp::endpoint remoteEndpoint() noexcept override; 27 | void start() noexcept override; 28 | 29 | private: 30 | asio::ip::tcp::endpoint m_remoteEndpoint; 31 | }; 32 | 33 | } // namespace tcp 34 | } // namespace p3com 35 | } // namespace iox 36 | 37 | #endif // IOX_TCP_SERVER_TRANSPORT_SESSION_HPP 38 | -------------------------------------------------------------------------------- /include/p3com/transport/tcp/tcp_transport.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef IOX_TCP_TRANSPORT_HPP 4 | #define IOX_TCP_TRANSPORT_HPP 5 | 6 | #include "p3com/transport/tcp/tcp_transport_session.hpp" 7 | #include "p3com/transport/tcp/tcp_client_transport_session.hpp" 8 | #include "p3com/transport/transport.hpp" 9 | #include "p3com/transport/udp/udp_transport_broadcast.hpp" 10 | #include "p3com/generic/serialization.hpp" 11 | 12 | #include 13 | 14 | #include 15 | 16 | namespace iox 17 | { 18 | namespace p3com 19 | { 20 | namespace tcp 21 | { 22 | class TCPTransport : public TransportLayer 23 | { 24 | public: 25 | TCPTransport() noexcept; 26 | TCPTransport(const TCPTransport&) = delete; 27 | TCPTransport(TCPTransport&&) = delete; 28 | TCPTransport& operator=(const TCPTransport&) = delete; 29 | TCPTransport& operator=(TCPTransport&&) = delete; 30 | 31 | ~TCPTransport() override; 32 | 33 | void registerDiscoveryCallback(remoteDiscoveryCallback_t callback) noexcept override; 34 | void registerUserDataCallback(userDataCallback_t callback) noexcept override; 35 | 36 | void sendBroadcast(const void* data, size_t size) noexcept override; 37 | bool sendUserData( 38 | const void* data1, size_t size1, const void* data2, size_t size2, uint32_t deviceIndex) noexcept override; 39 | 40 | size_t maxMessageSize() const noexcept override; 41 | TransportType getType() const noexcept override; 42 | 43 | private: 44 | static constexpr uint16_t DATA_PORT = 9333U; 45 | 46 | asio::io_service m_context; 47 | cxx::optional m_work; 48 | std::thread m_thread; 49 | 50 | asio::ip::tcp::acceptor m_dataAcceptor; 51 | udp::UDPBroadcast m_broadcast; 52 | mutable std::mutex m_transportSessionsMutex; 53 | 54 | cxx::vector, MAX_DEVICE_COUNT> m_transportSessions; 55 | cxx::vector>, 56 | MAX_DEVICE_COUNT> 57 | m_infoToReport; 58 | std::unique_ptr m_serverListeningSession; 59 | 60 | userDataCallback_t m_userDataCallback; 61 | remoteDiscoveryCallback_t m_remoteDiscoveryCallback; 62 | 63 | void startAccept() noexcept; 64 | void addSession() noexcept; 65 | void addSession(asio::ip::tcp::endpoint& endpoint) noexcept; 66 | 67 | void udpDiscoveryCallback(const void* epIter, size_t size, DeviceIndex_t deviceIndex) noexcept; 68 | void remoteDiscoveryHandler(const void* data, size_t size, const uint32_t device) const noexcept; 69 | 70 | static TCPTransportSession::dataCallback_t handleUserDataCallback(TCPTransport* self) noexcept; 71 | static TCPTransportSession::sessionClosedCallback_t handleSessionClose(TCPTransport* self) noexcept; 72 | static TCPClientTransportSession::sessionOpenCallback_t handleSessionOpen(TCPTransport* self) noexcept; 73 | std::unique_ptr* findSession(const asio::ip::tcp::endpoint& endpoint) noexcept; 74 | }; 75 | 76 | } // namespace tcp 77 | } // namespace p3com 78 | } // namespace iox 79 | 80 | #endif // IOX_TCP_TRANSPORT_HPP 81 | -------------------------------------------------------------------------------- /include/p3com/transport/tcp/tcp_transport_session.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef IOX_TCP_TRANSPORT_SESSION_HPP 4 | #define IOX_TCP_TRANSPORT_SESSION_HPP 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | namespace iox 12 | { 13 | namespace p3com 14 | { 15 | namespace tcp 16 | { 17 | class TCPTransportSession 18 | { 19 | public: 20 | using dataCallback_t = std::function; 21 | using sessionClosedCallback_t = std::function; 22 | 23 | TCPTransportSession(asio::io_service& io_service, 24 | const dataCallback_t& dataCallbackHandler, 25 | const sessionClosedCallback_t& sessionClosedHandler) noexcept; 26 | 27 | // Copy 28 | TCPTransportSession(const TCPTransportSession&) = delete; 29 | TCPTransportSession& operator=(const TCPTransportSession&) = delete; 30 | 31 | // Move 32 | TCPTransportSession& operator=(TCPTransportSession&&) = delete; 33 | TCPTransportSession(TCPTransportSession&&) = delete; 34 | 35 | virtual ~TCPTransportSession(); 36 | 37 | virtual asio::ip::tcp::endpoint remoteEndpoint() noexcept = 0; 38 | virtual void start() noexcept = 0; 39 | 40 | asio::ip::tcp::socket& getSocket() noexcept; 41 | std::string endpointToString() noexcept; 42 | std::string remoteEndpointToString() noexcept; 43 | bool sendData(const void* data1, size_t size1, const void* data2, size_t size2) noexcept; 44 | 45 | static constexpr size_t MAX_PACKET_SIZE = 65535U; // 64 kB 46 | 47 | private: 48 | const sessionClosedCallback_t m_sessionClosedCallback; 49 | const dataCallback_t m_dataCallback; 50 | asio::ip::tcp::socket m_dataSocket; 51 | size_t m_readBufferSize; 52 | std::array m_readBuffer; 53 | 54 | protected: 55 | void receiveTcpData() noexcept; 56 | void sessionClosedHandler() noexcept; 57 | }; 58 | 59 | } // namespace tcp 60 | } // namespace p3com 61 | } // namespace iox 62 | 63 | #endif // IOX_TCP_TRANSPORT_SESSION_HPP 64 | -------------------------------------------------------------------------------- /include/p3com/transport/transport.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef IOX_TRANSPORT_HPP 4 | #define IOX_TRANSPORT_HPP 5 | 6 | #include "p3com/generic/types.hpp" 7 | #include "p3com/transport/transport_type.hpp" 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | namespace iox 14 | { 15 | namespace p3com 16 | { 17 | /** 18 | * @brief Transport layer status 19 | */ 20 | enum struct TransportStatus 21 | { 22 | /** 23 | * @brief Status "good" means that the transport layer is working as expected. 24 | */ 25 | GOOD = 0, 26 | /** 27 | * @brief Status "failed" means that there was an unrecoverable failure in the transport layer but it hasnt been 28 | * disabled yet. This status is usually achieved when the transport layer implementation calls the `setFailed` 29 | * protected member function, which should be done in the case of unrecoverable failure such as an exception when 30 | * opening a network socket. When a transport layer is in the "failed" status, it will be automatically disabled by 31 | * the p3com gateway infrastructure after the transport layer method returns. 32 | */ 33 | FAILED = 1, 34 | /** 35 | * @brief Status "disabled" means that the transport layer is now disabled and shouldnt be used anymore. 36 | */ 37 | DISABLED = 2 38 | }; 39 | 40 | /** 41 | * @note A message is "pending" if it cannot be released immediately after sending with the `sendUserData` method of a 42 | * transport layer, but it can only be released after the corresponding "buffer sent callback" (i.e., with the matching 43 | * message payload pointer) has been called. Such postponing of releasing the buffer is needed for example in the PCIe 44 | * transport layer, when a DMA is triggered asynchronously. 45 | */ 46 | 47 | /** 48 | * @brief To be called when a discovery message is received from the transport. 49 | * 50 | * @note First argument is the received serialized datagram header followed by the payload, second argument is the size 51 | * of the received message (the sum of the serialized datagram header size and the payload size) and third argument is 52 | * the index of the device that sent the message. 53 | * 54 | * @note Has to be implemented by every transport layer. 55 | */ 56 | using remoteDiscoveryCallback_t = std::function; 57 | 58 | /** 59 | * @brief To be called when user data message is received from the transport. 60 | * 61 | * @note First argument is the received serialized datagram header followed by the payload, second argument is the size 62 | * of the received message (the sum of the serialized datagram header size and the payload size) and third argument is 63 | * the index of the device that sent the message. 64 | * 65 | * @note Has to be implemented by every transport layer. 66 | */ 67 | using userDataCallback_t = std::function; 68 | 69 | /** 70 | * @brief To be called when loaning a buffer is needed before a message can be received. 71 | * 72 | * @note The first argument is the serialized datagram header, the second argument is the serialized datagram header 73 | * size. 74 | * 75 | * @note Should return a valid pointer to the loaned buffer or `nullptr` in the case that a buffer of this size cannot 76 | * be loaned for some reason. 77 | * 78 | * @note Currently only used in PCIe transport to implement DMA data transfers. 79 | */ 80 | using bufferNeededCallback_t = std::function; 81 | 82 | /** 83 | * @brief To be called when a buffer that was previously loaned via the bufferNeededCallback callback has now been 84 | * filled and can be either published or released. 85 | * 86 | * @note The first parameter is the serialized datagram header, the second argument is the serialized datagram header 87 | * size, the third argument is whether the buffer should be published and the fourth argument is the index of the device 88 | * that sent the message. 89 | * 90 | * @note Currently only used in PCIe transport to implement DMA data transfers. 91 | */ 92 | using bufferReleasedCallback_t = std::function; 93 | 94 | /** 95 | * @brief To be called when a pending buffer that was previously sent with the `sendUserData` method has now finished 96 | * sending and can be released. 97 | * 98 | * @note The first parameter is the payload of the message that can now be released. 99 | * 100 | * @note Currently only used in PCIe transport to implement DMA data transfers. 101 | */ 102 | using bufferSentCallback_t = std::function; 103 | 104 | /** 105 | * @brief Transport layer base class 106 | */ 107 | class TransportLayerBase 108 | { 109 | public: 110 | /** 111 | * @brief Is this transport layer alright? 112 | * 113 | * @return 114 | */ 115 | bool isGood() const noexcept 116 | { 117 | return m_status.load() == TransportStatus::GOOD; 118 | } 119 | 120 | /** 121 | * @brief If the transport layer failed, set the status to disabled. 122 | * 123 | * @return 124 | */ 125 | bool hasFailedSetDisabled() noexcept 126 | { 127 | // Atomically test whether it is FAILED, if so, set to DISABLED. Otherwise, do nothing. 128 | TransportStatus expected{TransportStatus::FAILED}; 129 | return m_status.compare_exchange_strong(expected, TransportStatus::DISABLED); 130 | } 131 | 132 | protected: 133 | /** 134 | * @brief Set the status to failed. 135 | */ 136 | void setFailed() noexcept 137 | { 138 | // Atomically test whether it is still GOOD, if so, set to FAILED. Otherwise, do nothing. 139 | TransportStatus expected{TransportStatus::GOOD}; 140 | m_status.compare_exchange_strong(expected, TransportStatus::FAILED); 141 | } 142 | 143 | private: 144 | std::atomic m_status{TransportStatus::GOOD}; 145 | }; 146 | 147 | /** 148 | * @brief Transport layer discovery functionality 149 | */ 150 | class TransportLayerDiscovery : virtual public TransportLayerBase 151 | { 152 | public: 153 | /** 154 | * @brief Register the remote discovery callback. 155 | * 156 | * @param remoteDiscoveryCallback_t 157 | */ 158 | virtual void registerDiscoveryCallback(remoteDiscoveryCallback_t) noexcept = 0; 159 | 160 | /** 161 | * @brief Send broadcast to all connected devices with the given discovery info. 162 | * 163 | * @param serializedDiscoveryData 164 | * @param serializedDiscoveryDataSize 165 | */ 166 | virtual void sendBroadcast(const void* serializedDiscoveryData, size_t serializedDiscoveryDataSize) noexcept = 0; 167 | }; 168 | 169 | /** 170 | * @brief Transport layer user data functionality 171 | */ 172 | class TransportLayerUserData : virtual public TransportLayerBase 173 | { 174 | public: 175 | /** 176 | * @brief Register the user data received callback. 177 | * 178 | * @param userDataCallback_t 179 | */ 180 | virtual void registerUserDataCallback(userDataCallback_t) noexcept = 0; 181 | 182 | /** 183 | * @brief Register the buffer needed callback. 184 | * 185 | * @param bufferNeededCallback_t 186 | * 187 | * @note Currently only used in PCIe transport to implement DMA data transfers. 188 | */ 189 | virtual void registerBufferNeededCallback(bufferNeededCallback_t) noexcept 190 | { 191 | } 192 | 193 | /** 194 | * @brief Register the buffer sent callback. 195 | * 196 | * @param bufferSentCallback_t 197 | * 198 | * @note Currently only used in PCIe transport to implement DMA data transfers. 199 | */ 200 | virtual void registerBufferSentCallback(bufferSentCallback_t) noexcept 201 | { 202 | } 203 | 204 | /** 205 | * @brief Register the buffer released callback. 206 | * 207 | * @param bufferReleasedCallback_t 208 | * 209 | * @note Currently only used in PCIe transport to implement DMA data transfers. 210 | */ 211 | virtual void registerBufferReleasedCallback(bufferReleasedCallback_t) noexcept 212 | { 213 | } 214 | 215 | /** 216 | * @brief Send a user data message. 217 | * In a normal case, the user payload data should be copied into the user payload right after the serialized 218 | * datagram header data. Since the seralized datagram header contains information about its size, the receiving size 219 | * is able to separate them. In case of pending message, the serialized datagram header needs to be sent along with 220 | * the buffer loaning request so that loaning with the corresponding subscriber on the destination buffer can be 221 | * done. 222 | * 223 | * @param serializedDatagramHeader 224 | * @param serializedDatagramHeaderSize 225 | * @param userPayload 226 | * @param userPayloadSize 227 | * @param deviceIndex 228 | * 229 | * @return True if the message is pending, so it shouldnt be released yet. False otherwise. 230 | * 231 | * @note If you dont implement the "buffer needed", "buffer sent" and "buffer released" callbacks, you should always 232 | * return false from this function. 233 | */ 234 | virtual bool sendUserData(const void* serializedDatagramHeader, 235 | size_t serializedDatagramHeaderSize, 236 | const void* userPayload, 237 | size_t userPayloadSize, 238 | uint32_t deviceIndex) noexcept = 0; 239 | 240 | /** 241 | * @brief Will a message with this size be pending? 242 | * 243 | * @param size_t 244 | * 245 | * @return 246 | */ 247 | virtual bool willBePending(size_t userPayloadSize) const noexcept 248 | { 249 | static_cast(userPayloadSize); 250 | return false; 251 | } 252 | 253 | /** 254 | * @brief Maximum single message size possible to send with this transport. 255 | * 256 | * @return size 257 | */ 258 | virtual size_t maxMessageSize() const noexcept = 0; 259 | }; 260 | 261 | /** 262 | * @brief Transport layer 263 | */ 264 | class TransportLayer : public TransportLayerUserData, public TransportLayerDiscovery 265 | { 266 | public: 267 | TransportLayer() = default; 268 | TransportLayer(const TransportLayer&) = default; 269 | TransportLayer(TransportLayer&&) = default; 270 | 271 | TransportLayer& operator=(const TransportLayer&) = delete; 272 | TransportLayer& operator=(TransportLayer&&) = delete; 273 | 274 | virtual ~TransportLayer() = default; 275 | 276 | /** 277 | * @brief Gateway type enumeration of this transport. 278 | * 279 | * @return type 280 | */ 281 | virtual TransportType getType() const noexcept = 0; 282 | }; 283 | 284 | } // namespace p3com 285 | } // namespace iox 286 | 287 | #endif // IOX_TRANSPORT_HPP 288 | -------------------------------------------------------------------------------- /include/p3com/transport/transport_info.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef IOX_TRANSPORT_INFO_HPP 4 | #define IOX_TRANSPORT_INFO_HPP 5 | 6 | #include "iceoryx_hoofs/cxx/vector.hpp" 7 | 8 | #include "p3com/generic/types.hpp" 9 | #include "p3com/transport/transport.hpp" 10 | #include "p3com/transport/transport_type.hpp" 11 | #include "p3com/internal/log/logging.hpp" 12 | 13 | #if defined(PCIE_GATEWAY) 14 | #include "p3com/transport/pcie/pcie_transport.hpp" 15 | #endif 16 | #if defined(UDP_GATEWAY) 17 | #include "p3com/transport/udp/udp_transport.hpp" 18 | #endif 19 | #if defined(TCP_GATEWAY) 20 | #include "p3com/transport/tcp/tcp_transport.hpp" 21 | #endif 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | namespace iox 29 | { 30 | namespace p3com 31 | { 32 | constexpr auto PCIE_FLAG = "--pcie"; 33 | constexpr auto PCIE_FLAG_SHORT = "-p"; 34 | constexpr auto UDP_FLAG = "--udp"; 35 | constexpr auto UDP_FLAG_SHORT = "-u"; 36 | constexpr auto TCP_FLAG = "--tcp"; 37 | constexpr auto TCP_FLAG_SHORT = "-t"; 38 | 39 | class TransportInfo 40 | { 41 | public: 42 | using transportFailCallback_t = std::function; 43 | 44 | static void enable(TransportType type) noexcept; 45 | static void enableAll() noexcept; 46 | 47 | static void registerTransportFailCallback(transportFailCallback_t callback) noexcept; 48 | 49 | template 50 | static void doFor(TransportType type, F&& fn) noexcept 51 | { 52 | auto& t = s_transports[index(type)]; 53 | if (t && t->isGood()) 54 | { 55 | fn(*t); 56 | } 57 | 58 | if (t && t->hasFailedSetDisabled()) 59 | { 60 | disable(t->getType()); 61 | if (s_failCallback) 62 | { 63 | s_failCallback(); 64 | } 65 | } 66 | } 67 | 68 | template 69 | static void doForAllEnabled(F&& fn) noexcept 70 | { 71 | for (auto& t : s_transports) 72 | { 73 | if (t && t->isGood()) 74 | { 75 | fn(*t); 76 | } 77 | } 78 | 79 | for (auto& t : s_transports) 80 | { 81 | if (t && t->hasFailedSetDisabled()) 82 | { 83 | disable(t->getType()); 84 | if (s_failCallback) 85 | { 86 | s_failCallback(); 87 | } 88 | } 89 | } 90 | } 91 | 92 | static TransportType findMatchingType(bitset_t remoteBitset, TransportType preferredType) noexcept 93 | { 94 | const auto preferredTypeIndex = index(preferredType); 95 | if (preferredType != TransportType::NONE && remoteBitset[preferredTypeIndex] && s_bitset[preferredTypeIndex]) 96 | { 97 | return preferredType; 98 | } 99 | 100 | for (auto& t : s_transports) 101 | { 102 | if (t && t->isGood()) 103 | { 104 | const auto type = t->getType(); 105 | if (remoteBitset[index(type)]) 106 | { 107 | return type; 108 | } 109 | } 110 | } 111 | 112 | return TransportType::NONE; 113 | } 114 | 115 | static bitset_t bitset() noexcept 116 | { 117 | return s_bitset; 118 | } 119 | 120 | static void terminate() noexcept 121 | { 122 | for (auto& t : s_transports) 123 | { 124 | t.reset(); 125 | } 126 | } 127 | 128 | private: 129 | static void disable(TransportType type) noexcept; 130 | 131 | static std::array, TRANSPORT_TYPE_COUNT> s_transports; 132 | static bitset_t s_bitset; 133 | static transportFailCallback_t s_failCallback; 134 | }; 135 | 136 | } // namespace p3com 137 | } // namespace iox 138 | 139 | #endif // IOX_TRANSPORT_INFO_HPP 140 | -------------------------------------------------------------------------------- /include/p3com/transport/transport_type.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_TRANSPORT_TYPE_HPP 4 | #define P3COM_TRANSPORT_TYPE_HPP 5 | 6 | #include "p3com/generic/config.hpp" 7 | 8 | #include 9 | 10 | namespace iox 11 | { 12 | namespace p3com 13 | { 14 | /** 15 | * @brief Transport type 16 | * 17 | */ 18 | enum struct TransportType 19 | { 20 | // PCIe transport layer 21 | PCIE = 1, 22 | // UDP transport layer 23 | UDP = 2, 24 | // TCP transport layer 25 | TCP = 3, 26 | // None 27 | NONE = 4 28 | }; 29 | 30 | static_assert(static_cast(TransportType::NONE) == TRANSPORT_TYPE_COUNT, ""); 31 | 32 | /** 33 | * @brief Get index of transport 34 | * 35 | * @param typeTransport 36 | * @return uint32_t 37 | */ 38 | inline uint32_t index(const TransportType typeTransport) noexcept 39 | { 40 | return static_cast(typeTransport); 41 | } 42 | 43 | /** 44 | * @brief Get type of transport 45 | * 46 | * @param index 47 | * @return TransportType 48 | */ 49 | inline TransportType type(const uint32_t index) noexcept 50 | { 51 | return static_cast(index); 52 | } 53 | 54 | constexpr std::array TRANSPORT_TYPE_NAMES{{"PCIE", "UDP", "TCP"}}; 55 | 56 | // List of gateway types which have the potential to lose messages during transfer 57 | constexpr std::array LOSSY_TRANSPORT_TYPES{TransportType::UDP, TransportType::TCP}; 58 | 59 | } // namespace p3com 60 | } // namespace iox 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /include/p3com/transport/udp/udp_transport.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef IOX_UDP_TRANSPORT_HPP 4 | #define IOX_UDP_TRANSPORT_HPP 5 | 6 | #include "iceoryx_hoofs/cxx/optional.hpp" 7 | #include "iceoryx_hoofs/cxx/vector.hpp" 8 | 9 | #include "p3com/generic/config.hpp" 10 | #include "p3com/generic/types.hpp" 11 | #include "p3com/transport/transport.hpp" 12 | #include "p3com/transport/udp/udp_transport_broadcast.hpp" 13 | 14 | #include 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | namespace iox 22 | { 23 | namespace p3com 24 | { 25 | namespace udp 26 | { 27 | class UDPTransport : public TransportLayer 28 | { 29 | public: 30 | UDPTransport() noexcept; 31 | ~UDPTransport() override; 32 | 33 | UDPTransport(const UDPTransport&) = delete; 34 | UDPTransport& operator=(const UDPTransport&) = delete; 35 | UDPTransport(UDPTransport&&) = delete; 36 | UDPTransport& operator=(UDPTransport&&) = delete; 37 | 38 | void registerDiscoveryCallback(remoteDiscoveryCallback_t callback) noexcept override; 39 | void registerUserDataCallback(userDataCallback_t callback) noexcept override; 40 | 41 | void sendBroadcast(const void* data, size_t size) noexcept override; 42 | bool sendUserData( 43 | const void* data1, size_t size1, const void* data2, size_t size2, uint32_t deviceIndex) noexcept override; 44 | 45 | size_t maxMessageSize() const noexcept override; 46 | TransportType getType() const noexcept override; 47 | 48 | private: 49 | static constexpr uint16_t DATA_PORT = 9333U; 50 | static constexpr size_t MAX_DATAGRAM_SIZE = 32768U; // 32 kB 51 | 52 | void dataSocketCallback(asio::error_code ec, size_t bytes) noexcept; 53 | void dataAsyncReceive() noexcept; 54 | 55 | asio::io_service m_context; 56 | cxx::optional m_work; 57 | std::thread m_thread; 58 | 59 | std::mutex m_socketMutex; 60 | asio::ip::udp::socket m_dataSocket; 61 | UDPBroadcast m_broadcast; 62 | 63 | std::array m_outputBuffer; 64 | asio::ip::udp::endpoint m_outputEndpoint; 65 | 66 | userDataCallback_t m_userDataCallback; 67 | }; 68 | 69 | } // namespace udp 70 | } // namespace p3com 71 | } // namespace iox 72 | 73 | #endif // IOX_UDP_TRANSPORT_HPP 74 | -------------------------------------------------------------------------------- /include/p3com/transport/udp/udp_transport_broadcast.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef IOX_UDP_TRANSPORT_BROADCAST_HPP 4 | #define IOX_UDP_TRANSPORT_BROADCAST_HPP 5 | 6 | #include "p3com/generic/config.hpp" 7 | #include "p3com/transport/transport.hpp" 8 | 9 | #include 10 | 11 | #include 12 | 13 | namespace iox 14 | { 15 | namespace p3com 16 | { 17 | namespace udp 18 | { 19 | class UDPBroadcast : public TransportLayerDiscovery 20 | { 21 | public: 22 | explicit UDPBroadcast(asio::io_service& context) noexcept; 23 | 24 | UDPBroadcast(const UDPBroadcast&) = delete; 25 | UDPBroadcast& operator=(const UDPBroadcast&) = delete; 26 | UDPBroadcast(UDPBroadcast&&) = delete; 27 | UDPBroadcast& operator=(UDPBroadcast&&) = delete; 28 | ~UDPBroadcast() = default; 29 | 30 | void registerDiscoveryCallback(remoteDiscoveryCallback_t callback) noexcept override; 31 | void sendBroadcast(const void* data, size_t size) noexcept override; 32 | 33 | uint64_t discoveredEndpoints() const noexcept; 34 | asio::ip::udp::endpoint getEndpoint(uint32_t deviceIndex) noexcept; 35 | cxx::optional getIndex(asio::ip::address address) const noexcept; 36 | 37 | private: 38 | static constexpr uint16_t DISCOVERY_PORT = 9332U; 39 | static constexpr uint32_t MAX_DATAGRAM_SIZE = 32768U; // 32 kB 40 | 41 | static uint32_t sockAddrToUint32(struct sockaddr* address) noexcept; 42 | static std::string inetNtoA(uint32_t addr) noexcept; 43 | 44 | void discoverySocketCallback(asio::error_code ec, size_t bytes) noexcept; 45 | void discoveryAsyncReceive() noexcept; 46 | void discoverBroadcastAddresses() noexcept; 47 | 48 | asio::ip::udp::socket m_discoverySocket; 49 | cxx::vector m_interfaceEndpoints; 50 | cxx::vector m_broadcastEndpoints; 51 | std::array m_outputBuffer; 52 | asio::ip::udp::endpoint m_outputEndpoint; 53 | remoteDiscoveryCallback_t m_remoteDiscoveryCallback; 54 | cxx::vector m_devices; 55 | }; 56 | 57 | } // namespace udp 58 | } // namespace p3com 59 | } // namespace iox 60 | 61 | #endif // IOX_UDP_TRANSPORT_BROADCAST_HPP 62 | -------------------------------------------------------------------------------- /include/p3com/utility/helper_functions.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_HELPER_FUNCTIONS_HPP 4 | #define P3COM_HELPER_FUNCTIONS_HPP 5 | 6 | #include "iceoryx_posh/capro/service_description.hpp" 7 | 8 | #include "p3com/generic/types.hpp" 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | namespace iox 16 | { 17 | namespace p3com 18 | { 19 | inline bool operator==(const iox::p3com::DeviceIndex_t& left, const iox::p3com::DeviceIndex_t& right) noexcept 20 | { 21 | return left.type == right.type && left.device == right.device; 22 | } 23 | 24 | /** 25 | * @brief delete an element in container 26 | * 27 | * @tparam Container 28 | * @tparam Element 29 | * @param container 30 | * @param element 31 | */ 32 | template 33 | inline void deleteElement(Container& container, Element element) noexcept 34 | { 35 | auto it = std::find(container.begin(), container.end(), element); 36 | if (it != container.end()) 37 | { 38 | container.erase(it); 39 | } 40 | } 41 | 42 | /** 43 | * @brief Check element existed in vector 44 | * 45 | * @tparam Container 46 | * @tparam Element 47 | * @param container 48 | * @param element 49 | * @return true 50 | * @return false 51 | */ 52 | template 53 | inline bool containsElement(const Container& container, const Element& element) noexcept 54 | { 55 | auto it = std::find(container.begin(), container.end(), element); 56 | return it != container.end(); 57 | } 58 | 59 | /** 60 | * @brief Check element existed in vector 61 | * 62 | * @tparam 63 | * @param container 64 | * @param element 65 | * @return true 66 | * @return false 67 | */ 68 | template<> 69 | inline bool containsElement( 70 | const ServiceVector_t& container, const capro::ServiceDescription::ClassHash& element) noexcept 71 | { 72 | const auto* it = std::find_if(container.begin(), container.end(), [&element](const capro::ServiceDescription& s) { 73 | return s.getClassHash() == element; 74 | }); 75 | return it != container.end(); 76 | } 77 | 78 | /** 79 | * @brief Delete all element in a container in other container 80 | * 81 | * @tparam Container 82 | * @param a 83 | * @param b 84 | */ 85 | template 86 | inline void deleteElements(Container& a, const Container& b) noexcept 87 | { 88 | for (const auto& elem : b) 89 | { 90 | deleteElement(a, elem); 91 | } 92 | } 93 | 94 | /** 95 | * @brief Copy from a source container into a destination container the elements 96 | * which are not already in the destination container. 97 | * 98 | * @tparam Container 99 | * @param a 100 | * @param b 101 | */ 102 | template 103 | inline void pushUnique(Container& a, const Container& b) noexcept 104 | { 105 | for (const auto& elem : b) 106 | { 107 | if(!containsElement(a, elem)) 108 | { 109 | a.push_back(elem); 110 | } 111 | } 112 | } 113 | 114 | /** 115 | * @brief Generate hash 116 | * 117 | * @return hash_t 118 | */ 119 | inline hash_t generateHash() noexcept 120 | { 121 | static std::random_device dev; 122 | static std::uniform_int_distribution dist; 123 | return dist(dev); 124 | } 125 | 126 | /** 127 | * @brief Neon supports one command to process multiple data, increase speed copy data 128 | * 129 | * @param destination 130 | * @param source 131 | * @param size 132 | */ 133 | #if defined(__ARM_NEON) || defined(__ARM_NEON__) 134 | inline void neonMemcpy(void* destination, const void* source, const uint64_t size) noexcept 135 | { 136 | constexpr uint64_t ITERATION_SIZE{64U}; 137 | if (size >= ITERATION_SIZE) 138 | { 139 | uint64_t iterations{size / ITERATION_SIZE}; 140 | 141 | // Volatile has to be used in inline assembly. 142 | // coverity[autosar_cpp14_a2_11_1_violation] 143 | // coverity[autosar_cpp14_a7_4_1_violation] 144 | __asm volatile("neon_memcpy_loop%=: \n\t" 145 | "LD1 {V0.16B, V1.16B, V2.16B, V3.16B}, [%[src_local]], #64 \n\t" 146 | "ST1 {V0.16B, V1.16B, V2.16B, V3.16B}, [%[dst_local]], #64 \n\t" 147 | 148 | "subs %[iterations],%[iterations],#1 \n\t" 149 | "bne neon_memcpy_loop%= \n\t" 150 | 151 | : [src_local] "+r"(source), [dst_local] "+r"(destination), [iterations] "+r"(iterations) 152 | :); 153 | } 154 | 155 | const uint64_t remainingSize{size % ITERATION_SIZE}; 156 | if (remainingSize != 0U) 157 | { 158 | std::memcpy(destination, source, remainingSize); 159 | } 160 | } 161 | #else 162 | 163 | inline void neonMemcpy(void* destination, const void* source, const uint64_t size) noexcept 164 | { 165 | std::memcpy(destination, source, size); 166 | } 167 | #endif 168 | 169 | } // namespace p3com 170 | } // namespace iox 171 | 172 | #endif 173 | -------------------------------------------------------------------------------- /include/p3com/utility/vector_map.hpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #ifndef P3COM_UTILITY_VECTOR_MAP_HPP 4 | #define P3COM_UTILITY_VECTOR_MAP_HPP 5 | 6 | #include "iceoryx_hoofs/cxx/vector.hpp" 7 | 8 | namespace iox 9 | { 10 | namespace cxx 11 | { 12 | /** 13 | * @brief A minimal map implementation with static allocation. Useful when you need a `std::map`-like functionality 14 | * without the overhead, both in terms of boilerplate code and performance. A few things to keep in mind: 15 | * 16 | * 1) Keys are kept in a static vector and always linearly scanned when searching for a value. So, you dont need to 17 | * implement `std::hash` (like for `std::unordered_map`) or even `std::less` (like for `std::map`). 18 | * 19 | * 2) Since the keys are kept in a container separate from the values, they have very good spatial locality. 20 | * 21 | * 3) Especially if the key type is small and the number of keys is not too big, the linear scan can be faster than a 22 | * normal map lookup. 23 | */ 24 | template 25 | class vector_map 26 | { 27 | public: 28 | using key_type = Key; 29 | using mapped_type = T; 30 | using size_type = uint64_t; 31 | 32 | using iterator = mapped_type*; 33 | using const_iterator = const mapped_type*; 34 | 35 | iterator begin() noexcept; 36 | iterator end() noexcept; 37 | 38 | const_iterator begin() const noexcept; 39 | const_iterator end() const noexcept; 40 | 41 | mapped_type& front() noexcept; 42 | mapped_type& back() noexcept; 43 | 44 | const mapped_type& front() const noexcept; 45 | const mapped_type& back() const noexcept; 46 | 47 | iterator find(const Key& key) noexcept; 48 | const_iterator find(const Key& key) const noexcept; 49 | 50 | template 51 | bool emplace(const Key& key, Targs&&... args) noexcept; 52 | 53 | void erase(iterator it) noexcept; 54 | void clear() noexcept; 55 | 56 | uint64_t size() const noexcept; 57 | 58 | private: 59 | iox::cxx::vector m_keys; 60 | iox::cxx::vector m_elems; 61 | }; 62 | 63 | } // namespace cxx 64 | } // namespace iox 65 | 66 | #include "p3com/internal/utility/vector_map.inl" 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /p3com.toml: -------------------------------------------------------------------------------- 1 | # This configuration file can be named /etc/iceoryx/p3com.toml 2 | 3 | # Possible values for the preferred-transport item are PCIE, TCP, UDP or NONE 4 | preferred-transport = "UDP" 5 | 6 | # Array of tables, each a service description of services to forward across transports 7 | # This example works with the iceoryx icehello demo: 8 | [[forwarded-service]] 9 | service = "Radar" 10 | instance = "FrontLeft" 11 | event = "Object" 12 | -------------------------------------------------------------------------------- /source/p3com/gateway/cmd_line.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "iceoryx_hoofs/platform/getopt.hpp" 4 | 5 | #include "p3com/gateway/cmd_line.hpp" 6 | #include "p3com/internal/log/logging.hpp" 7 | 8 | namespace 9 | { 10 | void printHelp() noexcept 11 | { 12 | std::cout << "p3com gateway application\n" 13 | << "usage: ./p3com-gw [options]\n" 14 | << " options:\n" 15 | << " -h, --help Print help and exit\n" 16 | << " -l, --log-level Set log level\n" 17 | #if defined(PCIE_GATEWAY) 18 | << " -p, --pcie Enable PCIe transport\n" 19 | #endif 20 | #if defined(UDP_GATEWAY) 21 | << " -u, --udp Enable UDP transport\n" 22 | #endif 23 | #if defined(TCP_GATEWAY) 24 | << " -t, --tcp Enable TCP transport\n" 25 | #endif 26 | << " -c, --config-file Path to the gateway config file\n"; 27 | } 28 | 29 | } 30 | 31 | iox::p3com::CmdLineArgs_t iox::p3com::CmdLineParser::parse(int argc, char** argv) noexcept 32 | { 33 | iox::p3com::CmdLineArgs_t config; 34 | constexpr option LONG_OPTIONS[] = {{"help", no_argument, nullptr, 'h'}, 35 | {"pcie", no_argument, nullptr, 'p'}, 36 | {"udp", no_argument, nullptr, 'u'}, 37 | {"tcp", no_argument, nullptr, 't'}, 38 | {"log-level", required_argument, nullptr, 'l'}, 39 | {"config", required_argument, nullptr, 'c'}, 40 | {nullptr, 0, nullptr, 0}}; 41 | 42 | // colon after shortOption means it requires an argument, two colons mean optional argument 43 | constexpr const char* SHORT_OPTIONS = "hpuitLl:c:"; 44 | int32_t index; 45 | int32_t opt{-1}; 46 | 47 | bool wasUdp = false; 48 | bool wasTcp = false; 49 | while ((opt = getopt_long(argc, argv, SHORT_OPTIONS, LONG_OPTIONS, &index), opt != -1)) 50 | { 51 | switch (opt) 52 | { 53 | case 'h': 54 | printHelp(); 55 | config.run = false; 56 | break; 57 | case 'p': 58 | config.enabledTransports[iox::p3com::index(iox::p3com::TransportType::PCIE)] = true; 59 | config.enabledTransportSpecified = true; 60 | break; 61 | case 'u': 62 | if (wasTcp) 63 | { 64 | iox::p3com::LogError() << "[TransportInfo] UDP & TCP flags can't be used together, choose only one."; 65 | config.run = false; 66 | break; 67 | } 68 | config.enabledTransports[iox::p3com::index(iox::p3com::TransportType::UDP)] = true; 69 | config.enabledTransportSpecified = true; 70 | wasUdp = true; 71 | break; 72 | case 't': 73 | if (wasUdp) 74 | { 75 | iox::p3com::LogError() << "[TransportInfo] UDP & TCP flags can't be used together, choose only one."; 76 | config.run = false; 77 | break; 78 | } 79 | config.enabledTransports[iox::p3com::index(iox::p3com::TransportType::TCP)] = true; 80 | config.enabledTransportSpecified = true; 81 | wasTcp = true; 82 | break; 83 | case 'l': 84 | if (strcmp(optarg, "off") == 0) 85 | { 86 | config.logLevel = iox::log::LogLevel::kOff; 87 | } 88 | else if (strcmp(optarg, "fatal") == 0) 89 | { 90 | config.logLevel = iox::log::LogLevel::kFatal; 91 | } 92 | else if (strcmp(optarg, "error") == 0) 93 | { 94 | config.logLevel = iox::log::LogLevel::kError; 95 | } 96 | else if (strcmp(optarg, "warning") == 0) 97 | { 98 | config.logLevel = iox::log::LogLevel::kWarn; 99 | } 100 | else if (strcmp(optarg, "info") == 0) 101 | { 102 | config.logLevel = iox::log::LogLevel::kInfo; 103 | } 104 | else if (strcmp(optarg, "debug") == 0) 105 | { 106 | config.logLevel = iox::log::LogLevel::kDebug; 107 | } 108 | else if (strcmp(optarg, "verbose") == 0) 109 | { 110 | config.logLevel = iox::log::LogLevel::kVerbose; 111 | } 112 | else 113 | { 114 | config.run = false; 115 | iox::p3com::LogError() << "Options for log-level are 'off', 'fatal', 'error', 'warning', 'info', 'debug' and " 116 | "'verbose'!"; 117 | } 118 | break; 119 | case 'L': 120 | // Legacy, keep the -L flag to mean '-l info' 121 | config.logLevel = iox::log::LogLevel::kInfo; 122 | break; 123 | case 'c': 124 | config.configFile = iox::roudi::ConfigFilePathString_t{iox::cxx::TruncateToCapacity, optarg}; 125 | break; 126 | default: 127 | config.run = false; 128 | break; 129 | } 130 | } 131 | return config; 132 | } 133 | 134 | -------------------------------------------------------------------------------- /source/p3com/gateway/gateway_app.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "iceoryx_hoofs/log/logmanager.hpp" 4 | #include "iceoryx_hoofs/posix_wrapper/signal_watcher.hpp" 5 | #include "p3com/transport/transport_type.hpp" 6 | #include "iceoryx_posh/runtime/posh_runtime.hpp" 7 | 8 | #include "p3com/generic/config.hpp" 9 | #include "p3com/generic/pending_messages.hpp" 10 | #include "p3com/generic/segmented_messages.hpp" 11 | #include "p3com/generic/transport_forwarder.hpp" 12 | #include "p3com/gateway/gateway_app.hpp" 13 | #include "p3com/gateway/iox_to_transport.hpp" 14 | #include "p3com/gateway/transport_to_iox.hpp" 15 | #include "p3com/transport/transport.hpp" 16 | #include "p3com/transport/transport_info.hpp" 17 | 18 | iox::p3com::GatewayApp::GatewayApp(const CmdLineArgs_t& cmdLineArgs, const GatewayConfig_t& gwConfig) noexcept 19 | : m_cmdLineArgs(cmdLineArgs) 20 | , m_gwConfig(gwConfig) 21 | { 22 | // Set log level 23 | iox::log::LogManager::GetLogManager().SetDefaultLogLevel(m_cmdLineArgs.logLevel, 24 | iox::log::LogLevelOutput::kHideLogLevel); 25 | 26 | // Enable transports 27 | enableTransports(); 28 | 29 | // Verify config 30 | if (m_gwConfig.preferredTransport != iox::p3com::TransportType::NONE 31 | && !iox::p3com::TransportInfo::bitset()[iox::p3com::index(m_gwConfig.preferredTransport)]) 32 | { 33 | iox::p3com::LogWarn() << "[p3comGateway] Preferred transport type is not enabled!"; 34 | m_gwConfig.preferredTransport = iox::p3com::TransportType::NONE; 35 | } 36 | } 37 | 38 | iox::p3com::GatewayApp::~GatewayApp() 39 | { 40 | } 41 | 42 | void iox::p3com::GatewayApp::enableTransports() noexcept 43 | { 44 | if (m_cmdLineArgs.enabledTransportSpecified) 45 | { 46 | for (uint32_t i = 0U; i < iox::p3com::TRANSPORT_TYPE_COUNT; ++i) 47 | { 48 | if (m_cmdLineArgs.enabledTransports[i]) 49 | { 50 | iox::p3com::TransportInfo::enable(iox::p3com::type(i)); 51 | } 52 | } 53 | } 54 | else 55 | { 56 | iox::p3com::TransportInfo::enableAll(); 57 | } 58 | } 59 | 60 | void iox::p3com::GatewayApp::run() noexcept 61 | { 62 | // Allocate dynamically to avoid a stack overflow 63 | auto discovery = std::make_unique(m_gwConfig); 64 | auto pendingMessageManager = std::make_unique(); 65 | auto segmentedMessageManager = std::make_unique(); 66 | auto transportForwarder = std::make_unique( 67 | *discovery, *pendingMessageManager, m_gwConfig.forwardedServices); 68 | 69 | // Initialize gateways in both directions 70 | iox::p3com::Transport2Iceoryx tr2iox(*discovery, *transportForwarder, *segmentedMessageManager); 71 | iox::p3com::Iceoryx2Transport iox2tr(*discovery, *pendingMessageManager); 72 | 73 | // Initialize discovery system 74 | auto updateCallback = [&](const iox::p3com::ServiceVector_t& neededChannels) { 75 | tr2iox.updateChannels(neededChannels); 76 | iox2tr.updateChannels(neededChannels); 77 | }; 78 | discovery->initialize(updateCallback); 79 | 80 | // Run thread that monitors periodic updates 81 | std::chrono::steady_clock::time_point lastLossyDiscovery{std::chrono::steady_clock::now()}; 82 | #if defined(__FREERTOS__) 83 | while (true) 84 | #else 85 | while (!iox::posix::hasTerminationRequested()) 86 | #endif 87 | { 88 | // Check the currently saved segmented messages for timeouts 89 | segmentedMessageManager->checkSegmentedMessages(); 90 | 91 | // Send the discovery information to lossy transports, with certain period 92 | const auto now = std::chrono::steady_clock::now(); 93 | if (now > (lastLossyDiscovery + iox::p3com::LOSSY_TRANSPORT_DISCOVERY_PERIOD)) 94 | { 95 | for (auto type : iox::p3com::LOSSY_TRANSPORT_TYPES) 96 | { 97 | discovery->resendDiscoveryInfoToTransport(type); 98 | } 99 | lastLossyDiscovery = now; 100 | } 101 | 102 | std::this_thread::sleep_for(iox::p3com::DISCOVERY_PERIOD); 103 | } 104 | 105 | // Need to deinitialize early, to make sure that local discovery events 106 | // dont trigger updates to iox2tr or tr2iox, which are destructed before 107 | // the discovery manager. 108 | discovery->deinitialize(); 109 | 110 | // The only remaining places which can instigate sending over transport 111 | // layers are iox2tr and transportForwarder. We need to disable them now 112 | // so that we can destruct transport layers then. 113 | iox2tr.join(); 114 | transportForwarder->join(); 115 | 116 | // Now, no additional transport messages should be sent, so it is safe to 117 | // terminate transport layers. 118 | iox::p3com::TransportInfo::terminate(); 119 | } 120 | -------------------------------------------------------------------------------- /source/p3com/gateway/gateway_config.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/gateway/gateway_config.hpp" 4 | #include "iceoryx_hoofs/cxx/string.hpp" 5 | 6 | #if defined(TOML_CONFIG) 7 | #include "p3com/internal/log/logging.hpp" 8 | #include "iceoryx_hoofs/internal/file_reader/file_reader.hpp" 9 | 10 | #include 11 | #include 12 | #endif 13 | 14 | iox::p3com::GatewayConfig_t 15 | iox::p3com::TomlGatewayConfigParser::parse(roudi::ConfigFilePathString_t path) noexcept 16 | { 17 | iox::p3com::GatewayConfig_t config; 18 | static_cast(path); // Unused 19 | #if defined(TOML_CONFIG) 20 | 21 | bool wasEmpty = false; 22 | // Set defaults if no path provided. 23 | if (path.size() == 0) 24 | { 25 | constexpr const char DEFAULT_CONFIG_FILE_PATH[] = "/etc/iceoryx/p3com.toml"; 26 | path = DEFAULT_CONFIG_FILE_PATH; 27 | wasEmpty = true; 28 | } 29 | 30 | iox::cxx::FileReader configFile(path, "", cxx::FileReader::ErrorMode::Ignore); 31 | if (!configFile.isOpen()) 32 | { 33 | (wasEmpty ? iox::p3com::LogInfo() : iox::p3com::LogError()) 34 | << "[GatewayConfig] p3com gateway config file not found at: '" << path 35 | << "'. Falling back to default config."; 36 | return config; 37 | } 38 | 39 | iox::p3com::LogInfo() << "[GatewayConfig] Using gateway config at: " << path; 40 | 41 | std::shared_ptr parsedToml{nullptr}; 42 | try 43 | { 44 | // Load the file 45 | parsedToml = cpptoml::parse_file(path.c_str()); 46 | } 47 | catch (const std::exception& parserException) 48 | { 49 | iox::p3com::LogWarn() << "[GatewayConfig] TOML parsing failed with error: " << parserException.what() 50 | << ". Falling back to default config."; 51 | return config; 52 | } 53 | 54 | constexpr const char PREFERRED_TRANSPORT_KEY[] = "preferred-transport"; 55 | auto preferredTransport = parsedToml->get_as(PREFERRED_TRANSPORT_KEY); 56 | if (preferredTransport) 57 | { 58 | const auto it = std::find( 59 | iox::p3com::TRANSPORT_TYPE_NAMES.begin(), iox::p3com::TRANSPORT_TYPE_NAMES.end(), *preferredTransport); 60 | if (it != iox::p3com::TRANSPORT_TYPE_NAMES.end()) 61 | { 62 | const auto index = std::distance(iox::p3com::TRANSPORT_TYPE_NAMES.begin(), it); 63 | config.preferredTransport = iox::p3com::type(static_cast(index)); 64 | iox::p3com::LogInfo() << "[GatewayConfig] Read preferred gateway transport: " << *preferredTransport; 65 | } 66 | } 67 | 68 | constexpr const char FORWARDED_SERVICE_KEY[] = "forwarded-service"; 69 | auto forwardedServices = parsedToml->get_table_array(FORWARDED_SERVICE_KEY); 70 | if (forwardedServices) 71 | { 72 | for (const auto& service : *forwardedServices) 73 | { 74 | constexpr const char SERVICE_KEY[] = "service"; 75 | constexpr const char INSTANCE_KEY[] = "instance"; 76 | constexpr const char EVENT_KEY[] = "event"; 77 | const capro::IdString_t serviceValue{cxx::TruncateToCapacity, *service->get_as(SERVICE_KEY)}; 78 | const capro::IdString_t instanceValue{cxx::TruncateToCapacity, *service->get_as(INSTANCE_KEY)}; 79 | const capro::IdString_t eventValue{cxx::TruncateToCapacity, *service->get_as(EVENT_KEY)}; 80 | config.forwardedServices.push_back({serviceValue, instanceValue, eventValue}); 81 | } 82 | } 83 | #endif 84 | 85 | return config; 86 | } 87 | -------------------------------------------------------------------------------- /source/p3com/gateway/iox_to_transport.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "iceoryx_posh/capro/service_description.hpp" 4 | #include "iceoryx_posh/internal/popo/building_blocks/chunk_receiver.hpp" 5 | #include "iceoryx_posh/mepoo/chunk_header.hpp" 6 | #include "iceoryx_posh/roudi/introspection_types.hpp" 7 | 8 | #include "p3com/gateway/iox_to_transport.hpp" 9 | #include "p3com/generic/config.hpp" 10 | #include "p3com/generic/types.hpp" 11 | #include "p3com/transport/transport_info.hpp" 12 | #include "p3com/internal/log/logging.hpp" 13 | 14 | iox::p3com::Iceoryx2Transport::Iceoryx2Transport(iox::p3com::DiscoveryManager& discovery, 15 | iox::p3com::PendingMessageManager& pendingMessageManager) noexcept 16 | : m_discovery(discovery) 17 | , m_pendingMessageManager(pendingMessageManager) 18 | , m_terminateFlag(false) 19 | , m_suspendFlag(false) 20 | , m_waitsetThread(&Iceoryx2Transport::waitsetLoop, this) 21 | { 22 | } 23 | 24 | void iox::p3com::Iceoryx2Transport::join() noexcept 25 | { 26 | m_terminateFlag.store(true); 27 | if (m_waitsetThread.joinable()) 28 | { 29 | m_waitsetThread.join(); 30 | } 31 | } 32 | 33 | void iox::p3com::Iceoryx2Transport::updateChannels(const iox::p3com::ServiceVector_t& services) noexcept 34 | { 35 | updateChannelsInternal(services, 36 | [this](const iox::capro::ServiceDescription& service) { setupChannel(service); }, 37 | [this](const iox::capro::ServiceDescription& service) { deleteChannel(service); }); 38 | } 39 | 40 | void iox::p3com::Iceoryx2Transport::setupChannel(const iox::capro::ServiceDescription& service) noexcept 41 | { 42 | iox::popo::SubscriberOptions options; 43 | options.nodeName = IOX_GW_NODE_NAME; 44 | addChannel(service, options, [this](iox::popo::UntypedSubscriber& subscriber) { 45 | m_suspendFlag.store(true); 46 | std::lock_guard lock{m_waitsetMutex}; 47 | m_waitset.attachState(subscriber, iox::popo::SubscriberState::HAS_DATA).or_else([](auto& error) { 48 | iox::p3com::LogError() << "[Iceoryx2Transport] Could not attach subscriber callback!" 49 | << " Error code: " << static_cast(error); 50 | }); 51 | m_suspendFlag.store(false); 52 | }); 53 | 54 | iox::p3com::LogInfo() << "[Iceoryx2Transport] Set up channel for service: " << service; 55 | } 56 | 57 | void 58 | iox::p3com::Iceoryx2Transport::deleteChannel(const iox::capro::ServiceDescription& service) noexcept 59 | { 60 | discardChannel(service, [this](iox::popo::UntypedSubscriber& subscriber) { 61 | { 62 | m_suspendFlag.store(true); 63 | std::lock_guard lock{m_waitsetMutex}; 64 | m_waitset.detachState(subscriber, iox::popo::SubscriberState::HAS_DATA); 65 | m_suspendFlag.store(false); 66 | } 67 | subscriber.unsubscribe(); 68 | 69 | // Wait until all associated pending messages are finished. 70 | while(true) 71 | { 72 | if (m_pendingMessageManager.anyPending(subscriber)) 73 | { 74 | std::this_thread::yield(); 75 | } 76 | else 77 | { 78 | break; 79 | } 80 | } 81 | }); 82 | 83 | iox::p3com::LogInfo() << "[Iceoryx2Transport] Discarded channel for service: " << service; 84 | } 85 | 86 | void iox::p3com::Iceoryx2Transport::waitsetLoop() noexcept 87 | { 88 | constexpr iox::units::Duration WAITSET_TIMEOUT{iox::units::Duration::fromMilliseconds(50)}; 89 | while(!m_terminateFlag.load()) 90 | { 91 | decltype(m_waitset)::NotificationInfoVector notificationVector; 92 | { 93 | std::lock_guard lock{m_waitsetMutex}; 94 | notificationVector = m_waitset.timedWait(WAITSET_TIMEOUT); 95 | } 96 | while(m_suspendFlag.load()) 97 | { 98 | std::this_thread::yield(); 99 | } 100 | 101 | for (auto& notification : notificationVector) 102 | { 103 | iox::popo::UntypedSubscriber& subscriber = *notification->getOrigin(); 104 | 105 | const void* userPayload = nullptr; 106 | { 107 | std::lock_guard lock{endpointsMutex()}; 108 | subscriber.take().and_then([&userPayload](const void* p) { userPayload = p; }).or_else([](auto& error) { 109 | switch (error) 110 | { 111 | case iox::popo::ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL: 112 | iox::p3com::LogError() 113 | << "[Iceoryx2Transport] Gateway subscriber failed because too many chunks " 114 | "are held in parallel!"; 115 | break; 116 | case iox::popo::ChunkReceiveResult::NO_CHUNK_AVAILABLE: 117 | break; // This is fine, it just means there are currently no messages to take 118 | } 119 | }); 120 | } 121 | 122 | if (userPayload != nullptr) 123 | { 124 | const auto chunkHeader = iox::mepoo::ChunkHeader::fromUserPayload(userPayload); 125 | const auto serviceDescription = subscriber.getServiceDescription(); 126 | const auto hash = serviceDescription.getClassHash(); 127 | 128 | const auto deviceIndices = m_discovery.generateDeviceIndices(chunkHeader->originId(), hash); 129 | if (deviceIndices.empty()) 130 | { 131 | std::lock_guard lock{endpointsMutex()}; 132 | subscriber.release(userPayload); 133 | } 134 | else 135 | { 136 | iox::p3com::LogInfo() << "[Iceoryx2Transport] Forwarding user message from publisher ID " 137 | << static_cast(chunkHeader->originId()) 138 | << " for service: " << serviceDescription; 139 | 140 | iox::p3com::IoxChunkDatagramHeader_t datagramHeader; 141 | datagramHeader.serviceHash = hash; 142 | datagramHeader.messageHash = iox::p3com::generateHash(); 143 | datagramHeader.userPayloadSize = chunkHeader->userPayloadSize(); 144 | datagramHeader.userPayloadAlignment = chunkHeader->userPayloadAlignment(); 145 | datagramHeader.userHeaderSize = 146 | (chunkHeader->userHeaderId() == iox::mepoo::ChunkHeader::NO_USER_HEADER) 147 | ? 0U 148 | : chunkHeader->userHeaderSize(); 149 | // m_submessage* fields will be filled for every submessage individually inside writeSegmented 150 | 151 | iox::p3com::writeSegmented(datagramHeader, 152 | *chunkHeader, 153 | deviceIndices, 154 | m_pendingMessageManager, 155 | endpointsMutex(), 156 | subscriber); 157 | } 158 | } 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /source/p3com/gateway/main.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "iceoryx_posh/runtime/posh_runtime.hpp" 4 | 5 | #include "p3com/gateway/gateway_app.hpp" 6 | #include "p3com/gateway/gateway_config.hpp" 7 | #include "p3com/gateway/cmd_line.hpp" 8 | 9 | int main(int argc, char** argv) 10 | { 11 | const iox::p3com::CmdLineArgs_t cmdLineArgs{iox::p3com::CmdLineParser::parse(argc, argv)}; 12 | if (cmdLineArgs.run) 13 | { 14 | // Set log level to avoid output from starting posh runtime 15 | iox::log::LogManager::GetLogManager().SetDefaultLogLevel(cmdLineArgs.logLevel, 16 | iox::log::LogLevelOutput::kHideLogLevel); 17 | 18 | // Read gateway config 19 | const iox::p3com::GatewayConfig_t gwConfig{iox::p3com::TomlGatewayConfigParser::parse(cmdLineArgs.configFile)}; 20 | 21 | // Start posh runtime 22 | iox::runtime::PoshRuntime::initRuntime(iox::p3com::IOX_GW_RUNTIME_NAME); 23 | 24 | // Run 25 | iox::p3com::GatewayApp gateway(cmdLineArgs, gwConfig); 26 | gateway.run(); 27 | } 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /source/p3com/gateway/transport_to_iox.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "iceoryx_posh/capro/service_description.hpp" 4 | #include "iceoryx_posh/gateway/gateway_generic.hpp" 5 | #include "iceoryx_posh/roudi/introspection_types.hpp" 6 | 7 | #include "p3com/gateway/transport_to_iox.hpp" 8 | #include "p3com/generic/config.hpp" 9 | #include "p3com/generic/data_writer.hpp" 10 | #include "p3com/generic/segmented_messages.hpp" 11 | #include "p3com/generic/serialization.hpp" 12 | #include "p3com/generic/types.hpp" 13 | #include "p3com/internal/log/logging.hpp" 14 | #include "p3com/transport/transport_info.hpp" 15 | 16 | namespace 17 | { 18 | constexpr std::chrono::nanoseconds NS_PER_BYTE{500U}; 19 | } 20 | 21 | iox::p3com::Transport2Iceoryx::Transport2Iceoryx(iox::p3com::DiscoveryManager& discovery, 22 | iox::p3com::TransportForwarder& transportForwarder, 23 | iox::p3com::SegmentedMessageManager& segmentedMessageManager) noexcept 24 | : m_discovery(discovery) 25 | , m_transportForwarder(transportForwarder) 26 | , m_segmentedMessageManager(segmentedMessageManager) 27 | { 28 | iox::p3com::TransportInfo::doForAllEnabled([this](iox::p3com::TransportLayer& transport) { 29 | // Register callback for user data received over transport 30 | transport.registerUserDataCallback( 31 | [this](const void* serializedUserPayload, size_t size, DeviceIndex_t deviceIndex) { 32 | receive(serializedUserPayload, size, deviceIndex); 33 | }); 34 | 35 | // Register callback for buffer loaning 36 | transport.registerBufferNeededCallback([this](const void* serializedDatagramHeader, size_t size) { 37 | return loanBuffer(serializedDatagramHeader, size); 38 | }); 39 | 40 | // Register callback for buffer releasing 41 | transport.registerBufferReleasedCallback( 42 | [this](const void* serializedDatagramHeader, size_t size, bool shouldRelease, DeviceIndex_t deviceIndex) { 43 | releaseBuffer(serializedDatagramHeader, size, shouldRelease, deviceIndex); 44 | }); 45 | }); 46 | } 47 | 48 | void iox::p3com::Transport2Iceoryx::updateChannels(const iox::p3com::ServiceVector_t& services) noexcept 49 | { 50 | updateChannelsInternal( 51 | services, 52 | [this](const iox::capro::ServiceDescription& service) { setupChannel(service); }, 53 | [this](const iox::capro::ServiceDescription& service) { deleteChannel(service); }); 54 | } 55 | 56 | void iox::p3com::Transport2Iceoryx::receive(const void* serializedUserPayload, 57 | size_t size, 58 | iox::p3com::DeviceIndex_t deviceIndex) noexcept 59 | { 60 | // Obtain the datagram header 61 | iox::p3com::IoxChunkDatagramHeader_t datagramHeader; 62 | const char* serializedUserPayloadPtr = static_cast(serializedUserPayload); 63 | const uint32_t serializedDatagramHeaderSize = iox::p3com::deserialize(datagramHeader, serializedUserPayloadPtr, size); 64 | serializedUserPayloadPtr += serializedDatagramHeaderSize; 65 | 66 | // Validate header 67 | if (size != datagramHeader.submessageSize + serializedDatagramHeaderSize) 68 | { 69 | iox::p3com::LogInfo() << "[Transport2Iceoryx] Received invalid user message, discarding!"; 70 | return; 71 | } 72 | 73 | doForChannel(datagramHeader.serviceHash, [&](iox::popo::UntypedPublisher& publisher) { 74 | void* userPayload = nullptr; 75 | void* userHeader = nullptr; 76 | bool shouldPublish = false; 77 | iox::p3com::LogInfo() << "[Transport2Iceoryx] Forwarding user message for service: " 78 | << publisher.getServiceDescription() 79 | << ", submessage offset: " << datagramHeader.submessageOffset; 80 | 81 | const bool isPushed = m_segmentedMessageManager.findAndDecrement( 82 | datagramHeader.messageHash, userHeader, userPayload, shouldPublish); 83 | if (!isPushed) 84 | { 85 | const bool hasUserHeader = datagramHeader.userHeaderSize != 0U; 86 | 87 | // Need to allocate new buffer 88 | publisher 89 | .loan(datagramHeader.userPayloadSize, 90 | datagramHeader.userPayloadAlignment, 91 | hasUserHeader ? datagramHeader.userHeaderSize : iox::CHUNK_NO_USER_HEADER_SIZE, 92 | hasUserHeader ? iox::p3com::USER_HEADER_ALIGNMENT : iox::CHUNK_NO_USER_HEADER_ALIGNMENT) 93 | .and_then([&](auto* p) { 94 | userHeader = hasUserHeader ? iox::mepoo::ChunkHeader::fromUserPayload(p)->userHeader() : nullptr; 95 | userPayload = p; 96 | }) 97 | .or_else([](auto& error) { 98 | if (error == iox::popo::AllocationError::TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL) 99 | { 100 | iox::p3com::LogWarn() 101 | << "[Transport2Iceoryx] Too many chunks allocated in parallel, discarding!"; 102 | } 103 | else if (error == iox::popo::AllocationError::RUNNING_OUT_OF_CHUNKS) 104 | { 105 | iox::p3com::LogWarn() << "[Transport2Iceoryx] Running out of chunks, discarding!"; 106 | } 107 | else 108 | { 109 | iox::p3com::LogError() << "[Transport2Iceoryx] Could not loan chunk, discarding! Error code: " 110 | << static_cast(error); 111 | } 112 | }); 113 | if (userPayload == nullptr) 114 | { 115 | return; 116 | } 117 | 118 | if (datagramHeader.submessageCount > 1U) 119 | { 120 | // Compute the deadline of this message 121 | const auto deadline = std::chrono::steady_clock::now() 122 | + NS_PER_BYTE * (datagramHeader.userHeaderSize + datagramHeader.userPayloadSize); 123 | 124 | m_segmentedMessageManager.push(datagramHeader.messageHash, 125 | datagramHeader.submessageCount - 1U, 126 | userHeader, 127 | userPayload, 128 | endpointsMutex(), 129 | publisher, 130 | deadline); 131 | shouldPublish = false; 132 | } 133 | else 134 | { 135 | shouldPublish = true; 136 | } 137 | } 138 | 139 | if (userPayload != nullptr) 140 | { 141 | iox::p3com::takeNext(datagramHeader, 142 | serializedUserPayloadPtr, 143 | static_cast(userHeader), 144 | static_cast(userPayload)); 145 | if (shouldPublish) 146 | { 147 | m_transportForwarder.push(userPayload, datagramHeader.serviceHash, deviceIndex); 148 | publisher.publish(userPayload); 149 | } 150 | } 151 | }); 152 | } 153 | 154 | void* iox::p3com::Transport2Iceoryx::loanBuffer(const void* serializedDatagramHeader, size_t size) noexcept 155 | { 156 | // Obtain the datagram header 157 | iox::p3com::IoxChunkDatagramHeader_t datagramHeader; 158 | const char* serializedDatagramHeaderPtr = static_cast(serializedDatagramHeader); 159 | iox::p3com::deserialize(datagramHeader, serializedDatagramHeaderPtr, size); 160 | 161 | void* bufferPtr = nullptr; 162 | doForChannel(datagramHeader.serviceHash, [&](iox::popo::UntypedPublisher& publisher) { 163 | void* userPayload = nullptr; 164 | void* userHeader = nullptr; 165 | 166 | const bool isPushed = m_segmentedMessageManager.find(datagramHeader.messageHash, userHeader, userPayload); 167 | if (!isPushed) 168 | { 169 | const bool hasUserHeader = datagramHeader.userHeaderSize != 0U; 170 | 171 | // Need to allocate new buffer 172 | publisher 173 | .loan(datagramHeader.userPayloadSize, 174 | datagramHeader.userPayloadAlignment, 175 | hasUserHeader ? datagramHeader.userHeaderSize : iox::CHUNK_NO_USER_HEADER_SIZE, 176 | hasUserHeader ? iox::p3com::USER_HEADER_ALIGNMENT : iox::CHUNK_NO_USER_HEADER_ALIGNMENT) 177 | .and_then([&](auto* p) { 178 | userHeader = hasUserHeader ? iox::mepoo::ChunkHeader::fromUserPayload(p)->userHeader() : nullptr; 179 | userPayload = p; 180 | }) 181 | .or_else([](auto& error) { 182 | if (error == iox::popo::AllocationError::TOO_MANY_CHUNKS_ALLOCATED_IN_PARALLEL) 183 | { 184 | iox::p3com::LogWarn() 185 | << "[Transport2Iceoryx] Too many chunks allocated in parallel, discarding!"; 186 | } 187 | else if (error == iox::popo::AllocationError::RUNNING_OUT_OF_CHUNKS) 188 | { 189 | iox::p3com::LogWarn() << "[Transport2Iceoryx] Running out of chunks, discarding!"; 190 | } 191 | else 192 | { 193 | iox::p3com::LogError() << "[Transport2Iceoryx] Could not loan chunk, discarding! Error code: " 194 | << static_cast(error); 195 | } 196 | }); 197 | if (userPayload == nullptr) 198 | { 199 | return; 200 | } 201 | 202 | // Compute the deadline of this message 203 | const auto deadline = std::chrono::steady_clock::now() 204 | + NS_PER_BYTE * (datagramHeader.userHeaderSize + datagramHeader.userPayloadSize); 205 | 206 | // Save the segmented message into the list 207 | m_segmentedMessageManager.push(datagramHeader.messageHash, 208 | datagramHeader.submessageCount, 209 | userHeader, 210 | userPayload, 211 | endpointsMutex(), 212 | publisher, 213 | deadline); 214 | } 215 | 216 | // Is this submessage filling the user header or the user payload? 217 | bufferPtr = (datagramHeader.submessageOffset < datagramHeader.userHeaderSize) ? userHeader : userPayload; 218 | }); 219 | return bufferPtr; 220 | } 221 | 222 | void iox::p3com::Transport2Iceoryx::releaseBuffer(const void* serializedDatagramHeader, 223 | size_t size, 224 | bool shouldRelease, 225 | iox::p3com::DeviceIndex_t deviceIndex) noexcept 226 | { 227 | // Obtain the datagram header 228 | iox::p3com::IoxChunkDatagramHeader_t datagramHeader; 229 | const char* serializedDatagramHeaderPtr = static_cast(serializedDatagramHeader); 230 | iox::p3com::deserialize(datagramHeader, serializedDatagramHeaderPtr, size); 231 | 232 | doForChannel(datagramHeader.serviceHash, [&](iox::popo::UntypedPublisher& publisher) { 233 | if (shouldRelease) 234 | { 235 | m_segmentedMessageManager.release(datagramHeader.messageHash); 236 | } 237 | else 238 | { 239 | void* userHeader = nullptr; 240 | void* userPayload = nullptr; 241 | bool shouldPublish = false; 242 | m_segmentedMessageManager.findAndDecrement( 243 | datagramHeader.messageHash, userHeader, userPayload, shouldPublish); 244 | if (shouldPublish) 245 | { 246 | m_transportForwarder.push(userPayload, datagramHeader.serviceHash, deviceIndex); 247 | publisher.publish(userPayload); 248 | } 249 | } 250 | }); 251 | } 252 | 253 | void iox::p3com::Transport2Iceoryx::setupChannel(const capro::ServiceDescription& service) noexcept 254 | { 255 | iox::popo::PublisherOptions options; 256 | options.nodeName = IOX_GW_NODE_NAME; 257 | addChannel(service, options, [this](iox::popo::UntypedPublisher& publisher) { 258 | m_discovery.addGatewayPublisher(publisher.getUid()); 259 | }); 260 | 261 | iox::p3com::LogInfo() << "[Transport2Iceoryx] Set up channel for service: " << service; 262 | } 263 | 264 | void iox::p3com::Transport2Iceoryx::deleteChannel(const iox::capro::ServiceDescription& service) noexcept 265 | { 266 | // Note: m_segmentedMessageMutex is always locked *after* internal gateway mutex!!! Avoid deadlocks. 267 | discardChannel(service, [this](iox::popo::UntypedPublisher& publisher) { 268 | // Release segmented messages associated with this channel 269 | m_segmentedMessageManager.releaseAll(publisher); 270 | 271 | m_discovery.discardGatewayPublisher(publisher.getUid()); 272 | }); 273 | 274 | iox::p3com::LogInfo() << "[Transport2Iceoryx] Discarded channel for service: " << service; 275 | } 276 | -------------------------------------------------------------------------------- /source/p3com/generic/data_reader.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/generic/data_reader.hpp" 4 | #include "p3com/generic/types.hpp" 5 | #include "p3com/utility/helper_functions.hpp" 6 | 7 | /** 8 | * @brief Take next message 9 | * 10 | * @param datagramHeader 11 | * @param data 12 | * @param userHeaderBuffer 13 | * @param userPayloadBuffer 14 | */ 15 | void iox::p3com::takeNext(const iox::p3com::IoxChunkDatagramHeader_t& datagramHeader, 16 | const void* data, 17 | uint8_t* userHeaderBuffer, 18 | uint8_t* userPayloadBuffer) noexcept 19 | { 20 | if (datagramHeader.submessageOffset < datagramHeader.userHeaderSize) 21 | { 22 | if (userHeaderBuffer != nullptr) 23 | { 24 | iox::p3com::neonMemcpy( 25 | userHeaderBuffer + datagramHeader.submessageOffset, data, datagramHeader.submessageSize); 26 | } 27 | } 28 | else 29 | { 30 | if (userPayloadBuffer != nullptr) 31 | { 32 | iox::p3com::neonMemcpy((userPayloadBuffer + datagramHeader.submessageOffset) - datagramHeader.userHeaderSize, 33 | data, 34 | static_cast(datagramHeader.submessageSize)); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /source/p3com/generic/data_writer.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/generic/data_writer.hpp" 4 | #include "p3com/generic/pending_messages.hpp" 5 | #include "p3com/generic/serialization.hpp" 6 | #include "p3com/generic/types.hpp" 7 | #include "p3com/internal/log/logging.hpp" 8 | #include "p3com/transport/transport_info.hpp" 9 | 10 | #include 11 | #include 12 | 13 | namespace 14 | { 15 | uint32_t divideAndRoundUp(uint32_t divident, uint32_t divisor) noexcept 16 | { 17 | return static_cast((divident + divisor - 1U) / divisor); 18 | } 19 | 20 | bool writeSegmentedInternal(iox::p3com::IoxChunkDatagramHeader_t& datagramHeader, 21 | const uint8_t* const userHeaderBytes, 22 | const uint8_t* const userPayloadBytes, 23 | const iox::p3com::DeviceIndex_t& deviceIndex) noexcept 24 | { 25 | // Obtain the corresponding transport and its maximum message size 26 | uint32_t pendingCount = 0U; 27 | iox::p3com::TransportInfo::doFor(deviceIndex.type, [&](iox::p3com::TransportLayer& transport) { 28 | std::array serializedDatagramHeaderBytes; 29 | const uint32_t maxTransportPayloadSize = 30 | static_cast(transport.maxMessageSize() - iox::p3com::maxIoxChunkDatagramHeaderSerializationSize()); 31 | datagramHeader.submessageCount = divideAndRoundUp(datagramHeader.userHeaderSize, maxTransportPayloadSize) 32 | + divideAndRoundUp(datagramHeader.userPayloadSize, maxTransportPayloadSize); 33 | 34 | // Send individual submessages 35 | uint32_t remainingUserHeaderSize = datagramHeader.userHeaderSize; 36 | uint32_t remainingUserPayloadSize = datagramHeader.userPayloadSize; 37 | 38 | datagramHeader.submessageOffset = 0U; 39 | while (remainingUserHeaderSize != 0U) 40 | { 41 | datagramHeader.submessageSize = std::min(maxTransportPayloadSize, remainingUserHeaderSize); 42 | const uint32_t serializedDatagramHeaderSize = 43 | iox::p3com::serialize(datagramHeader, serializedDatagramHeaderBytes.data()); 44 | 45 | const bool isPending = transport.sendUserData(serializedDatagramHeaderBytes.data(), 46 | serializedDatagramHeaderSize, 47 | userHeaderBytes + datagramHeader.submessageOffset, 48 | datagramHeader.submessageSize, 49 | deviceIndex.device); 50 | if (isPending) 51 | { 52 | iox::p3com::LogFatal() 53 | << "[DataWriter] Pending messages for user headers are not supported in this p3com gateway " 54 | "version! Please make your user headers smaller!"; 55 | } 56 | 57 | datagramHeader.submessageOffset += datagramHeader.submessageSize; 58 | remainingUserHeaderSize -= datagramHeader.submessageSize; 59 | } 60 | 61 | while (remainingUserPayloadSize != 0U) 62 | { 63 | datagramHeader.submessageSize = std::min(maxTransportPayloadSize, remainingUserPayloadSize); 64 | 65 | const uint32_t serializedDatagramHeaderSize = 66 | iox::p3com::serialize(datagramHeader, serializedDatagramHeaderBytes.data()); 67 | pendingCount += static_cast(transport.sendUserData( 68 | serializedDatagramHeaderBytes.data(), 69 | serializedDatagramHeaderSize, 70 | userPayloadBytes + datagramHeader.submessageOffset - datagramHeader.userHeaderSize, 71 | datagramHeader.submessageSize, 72 | deviceIndex.device)); 73 | 74 | datagramHeader.submessageOffset += datagramHeader.submessageSize; 75 | remainingUserPayloadSize -= datagramHeader.submessageSize; 76 | } 77 | }); 78 | 79 | if (pendingCount > 1U) 80 | { 81 | iox::p3com::LogFatal() << "[DataWriter] Multiple pending submessages for a single message are not supported in " 82 | "this p3com gateway version!"; 83 | } 84 | return pendingCount == 1U; 85 | } 86 | 87 | } // anonymous namespace 88 | 89 | void iox::p3com::writeSegmented( 90 | iox::p3com::IoxChunkDatagramHeader_t& datagramHeader, 91 | const iox::mepoo::ChunkHeader& chunkHeader, 92 | const iox::cxx::vector& deviceIndices, 93 | iox::p3com::PendingMessageManager& pendingMessageManager, 94 | std::mutex& mutex, 95 | iox::popo::UntypedSubscriber& subscriber) noexcept 96 | { 97 | for (const auto& i : deviceIndices) 98 | { 99 | bool shouldBePending = false; 100 | bool shouldDiscard = false; 101 | iox::p3com::TransportInfo::doFor(i.type, [&](auto& transport) { 102 | shouldBePending = transport.willBePending(datagramHeader.userPayloadSize); 103 | if (shouldBePending) 104 | { 105 | const bool pushed = pendingMessageManager.push(chunkHeader.userPayload(), mutex, subscriber); 106 | if (!pushed) 107 | { 108 | iox::p3com::LogWarn() << "[DataWriter] Exceeded maximum number of pending messages! Discarding!"; 109 | shouldDiscard = true; 110 | } 111 | } 112 | }); 113 | if (shouldDiscard) 114 | { 115 | std::lock_guard lock{mutex}; 116 | subscriber.release(chunkHeader.userPayload()); 117 | return; 118 | } 119 | 120 | const bool isPending = writeSegmentedInternal(datagramHeader, 121 | static_cast(chunkHeader.userHeader()), 122 | static_cast(chunkHeader.userPayload()), 123 | i); 124 | if (!isPending) 125 | { 126 | if (shouldBePending) 127 | { 128 | // This likely means that the message should have been pending, 129 | // but sending failed so it isnt pending. Note that mutex is 130 | // locked inside the release function, so we dont need to lock 131 | // it here. 132 | pendingMessageManager.release(chunkHeader.userPayload()); 133 | } 134 | else 135 | { 136 | std::lock_guard lock{mutex}; 137 | subscriber.release(chunkHeader.userPayload()); 138 | } 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /source/p3com/generic/pending_messages.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/generic/pending_messages.hpp" 4 | #include "p3com/transport/transport_info.hpp" 5 | #include "p3com/internal/log/logging.hpp" 6 | #include "p3com/utility/helper_functions.hpp" 7 | 8 | iox::p3com::PendingMessageManager::PendingMessageManager() noexcept 9 | { 10 | iox::p3com::TransportInfo::doForAllEnabled([this](iox::p3com::TransportLayer& transport) { 11 | // Register callback for buffer sending 12 | transport.registerBufferSentCallback( 13 | [this](const void* ptr) { release(ptr); }); 14 | }); 15 | } 16 | 17 | void iox::p3com::PendingMessageManager::release(const void* userPayload) noexcept 18 | { 19 | iox::cxx::optional msgToRelease{iox::cxx::nullopt}; 20 | 21 | { 22 | std::lock_guard lock{m_mutex}; 23 | auto* msgIt = m_pendingMessages.find(userPayload); 24 | if (msgIt == m_pendingMessages.end()) 25 | { 26 | iox::p3com::LogError() << "[PendingMessageManager] Cannot release invalid pending message!"; 27 | } 28 | else 29 | { 30 | auto& pendingMsg = *msgIt; 31 | pendingMsg.counter--; 32 | if (pendingMsg.counter == 0U) 33 | { 34 | msgToRelease.emplace(pendingMsg); 35 | m_pendingMessages.erase(msgIt); 36 | } 37 | } 38 | } 39 | 40 | if (msgToRelease.has_value()) 41 | { 42 | std::lock_guard lock{*msgToRelease->mutex}; 43 | msgToRelease->subscriber->release(userPayload); 44 | } 45 | } 46 | 47 | bool iox::p3com::PendingMessageManager::anyPending(iox::popo::UntypedSubscriber& subscriber) noexcept 48 | { 49 | std::lock_guard lock(m_mutex); 50 | for (auto& pendingMsg : m_pendingMessages) 51 | { 52 | if (pendingMsg.subscriber == &subscriber) 53 | { 54 | return true; 55 | } 56 | } 57 | return false; 58 | } 59 | 60 | bool iox::p3com::PendingMessageManager::push(const void* userPayload, std::mutex& mutex, iox::popo::UntypedSubscriber& subscriber) noexcept 61 | { 62 | std::lock_guard lock(m_mutex); 63 | auto* msgIt = m_pendingMessages.find(userPayload); 64 | if (msgIt == m_pendingMessages.end()) 65 | { 66 | const bool emplaced = m_pendingMessages.emplace( 67 | userPayload, iox::p3com::PendingMessageManager::PendingMessage_t{1U, &mutex, &subscriber}); 68 | 69 | return emplaced; 70 | } 71 | else 72 | { 73 | iox::p3com::LogFatal() << "[PendingMessageManager] Attempted to push a pending message which laready exists!"; 74 | return false; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /source/p3com/generic/segmented_messages.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/generic/segmented_messages.hpp" 4 | #include "p3com/internal/log/logging.hpp" 5 | 6 | void iox::p3com::SegmentedMessageManager::checkSegmentedMessages() noexcept 7 | { 8 | const auto now = std::chrono::steady_clock::now(); 9 | while (true) 10 | { 11 | iox::cxx::optional msgToRelease{iox::cxx::nullopt}; 12 | 13 | { 14 | std::lock_guard lock(m_mutex); 15 | for (auto& segmentedMsg : m_segmentedMessages) 16 | { 17 | if (segmentedMsg.deadline < now) 18 | { 19 | iox::p3com::LogWarn() << "[SegmentedMessageManager] Detected message segment timeout, discarding!"; 20 | msgToRelease.emplace(segmentedMsg); 21 | m_segmentedMessages.erase(&segmentedMsg); 22 | break; 23 | } 24 | } 25 | } 26 | 27 | if (msgToRelease.has_value()) 28 | { 29 | std::lock_guard lock{*msgToRelease->mutex}; 30 | msgToRelease->publisher->release(msgToRelease->userPayload); 31 | } 32 | else 33 | { 34 | break; 35 | } 36 | } 37 | } 38 | 39 | void iox::p3com::SegmentedMessageManager::push(iox::p3com::hash_t messageHash, 40 | uint32_t remainingSegments, 41 | void* userHeader, 42 | void* userPayload, 43 | std::mutex& mutex, 44 | iox::popo::UntypedPublisher& publisher, 45 | std::chrono::steady_clock::time_point deadline) noexcept 46 | { 47 | std::lock_guard lock(m_mutex); 48 | const bool emplaced = 49 | m_segmentedMessages.emplace(messageHash, 50 | iox::p3com::SegmentedMessageManager::SegmentedMessage_t{ 51 | remainingSegments, userHeader, userPayload, &mutex, &publisher, deadline}); 52 | if (!emplaced) 53 | { 54 | iox::p3com::LogWarn() << "[SegmentedMessageManager] Too many segmented messages at the same time, discarding!"; 55 | publisher.release(userPayload); 56 | } 57 | } 58 | 59 | bool iox::p3com::SegmentedMessageManager::findAndDecrement(iox::p3com::hash_t messageHash, 60 | void*& userHeader, 61 | void*& userPayload, 62 | bool& shouldPublish) noexcept 63 | { 64 | std::lock_guard lock(m_mutex); 65 | auto* msgIt = m_segmentedMessages.find(messageHash); 66 | if (msgIt != m_segmentedMessages.end()) 67 | { 68 | auto& msg = *msgIt; 69 | 70 | userHeader = msg.userHeader; 71 | userPayload = msg.userPayload; 72 | msg.remainingSegments--; 73 | if (msg.remainingSegments == 0U) 74 | { 75 | m_segmentedMessages.erase(msgIt); 76 | shouldPublish = true; 77 | } 78 | else 79 | { 80 | shouldPublish = false; 81 | } 82 | return true; 83 | } 84 | else 85 | { 86 | return false; 87 | } 88 | } 89 | 90 | bool iox::p3com::SegmentedMessageManager::find(iox::p3com::hash_t messageHash, 91 | void*& userHeader, 92 | void*& userPayload) noexcept 93 | { 94 | std::lock_guard lock(m_mutex); 95 | auto* msgIt = m_segmentedMessages.find(messageHash); 96 | if (msgIt != m_segmentedMessages.end()) 97 | { 98 | auto& msg = *msgIt; 99 | userHeader = msg.userHeader; 100 | userPayload = msg.userPayload; 101 | return true; 102 | } 103 | else 104 | { 105 | return false; 106 | } 107 | } 108 | 109 | void iox::p3com::SegmentedMessageManager::release(hash_t messageHash) noexcept 110 | { 111 | std::lock_guard lock(m_mutex); 112 | auto* msgIt = m_segmentedMessages.find(messageHash); 113 | if (msgIt != m_segmentedMessages.end()) 114 | { 115 | auto& msg = *msgIt; 116 | msg.publisher->release(msg.userPayload); 117 | m_segmentedMessages.erase(msgIt); 118 | } 119 | } 120 | 121 | void iox::p3com::SegmentedMessageManager::releaseAll(popo::UntypedPublisher& publisher) noexcept 122 | { 123 | std::lock_guard lock(m_mutex); 124 | 125 | // Remove elements in reverse order, to maintain validity of the iterator. 126 | for (auto it = m_segmentedMessages.end(); it != m_segmentedMessages.begin(); --it) 127 | { 128 | auto msgIt = it - 1; 129 | if (msgIt->publisher == &publisher) 130 | { 131 | msgIt->publisher->release(msgIt->userPayload); 132 | m_segmentedMessages.erase(msgIt); 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /source/p3com/generic/serialization.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/generic/serialization.hpp" 4 | 5 | uint32_t iox::p3com::serialize(const iox::p3com::PubSubInfo_t& info, char* ptr) noexcept 6 | { 7 | size_t offset = 0U; 8 | const auto pushPrimitive = [ptr, &offset](auto elem) noexcept { 9 | std::memcpy(ptr + offset, &elem, sizeof(elem)); 10 | offset += sizeof(elem); 11 | }; 12 | const auto pushString = [ptr, &offset](const auto& str) noexcept { 13 | const uint64_t size = str.size(); 14 | std::memcpy(ptr + offset, str.c_str(), size + 1); // include null-character 15 | offset += size + 1; 16 | }; 17 | 18 | // We dont care about endianness for now, since all supported platforms are little endian. 19 | // We also assume that all primitives (integer types) have a fixed size (e.g., use uint32_t instead of unsigned 20 | // int). 21 | pushPrimitive(static_cast(info.userSubscribers.size())); 22 | 23 | for (const auto& service : info.userSubscribers) 24 | { 25 | for (const auto& str : 26 | {service.getServiceIDString(), service.getInstanceIDString(), service.getEventIDString()}) 27 | { 28 | pushString(str); 29 | } 30 | } 31 | pushPrimitive(info.gatewayBitset); 32 | pushPrimitive(info.gatewayHash); 33 | pushPrimitive(info.infoHash); 34 | pushPrimitive(info.isTermination); 35 | 36 | iox::cxx::Expects(offset <= maxPubSubInfoSerializationSize()); 37 | return static_cast(offset); 38 | } 39 | 40 | uint32_t iox::p3com::deserialize(iox::p3com::PubSubInfo_t& info, const char* ptr, size_t size) noexcept 41 | { 42 | size_t offset = 0U; 43 | const auto loadPrimitive = [ptr, &offset, size](auto* elem) noexcept { 44 | iox::cxx::Expects(offset + sizeof(*elem) <= size); 45 | std::memcpy(elem, ptr + offset, sizeof(*elem)); 46 | offset += sizeof(*elem); 47 | }; 48 | const auto loadString = [ptr, &offset, size](auto& str) noexcept { 49 | const bool success = str.unsafe_assign(ptr + offset); 50 | iox::cxx::Expects(success); 51 | iox::cxx::Expects(offset + str.size() + 1 <= size); 52 | offset += str.size() + 1; 53 | }; 54 | 55 | uint64_t userSubscribersSize; 56 | loadPrimitive(&userSubscribersSize); 57 | iox::cxx::Expects(userSubscribersSize <= info.userSubscribers.capacity()); 58 | info.userSubscribers.resize(userSubscribersSize); 59 | 60 | iox::capro::IdString_t serviceStr; 61 | iox::capro::IdString_t instanceStr; 62 | iox::capro::IdString_t eventStr; 63 | for (auto& service : info.userSubscribers) 64 | { 65 | loadString(serviceStr); 66 | loadString(instanceStr); 67 | loadString(eventStr); 68 | service = capro::ServiceDescription{serviceStr, instanceStr, eventStr}; 69 | } 70 | loadPrimitive(&info.gatewayBitset); 71 | loadPrimitive(&info.gatewayHash); 72 | loadPrimitive(&info.infoHash); 73 | loadPrimitive(&info.isTermination); 74 | 75 | iox::cxx::Expects(offset <= maxPubSubInfoSerializationSize()); 76 | return static_cast(offset); 77 | } 78 | 79 | uint32_t iox::p3com::serialize(const iox::p3com::IoxChunkDatagramHeader_t& datagramHeader, char* ptr) noexcept 80 | { 81 | size_t offset = 0U; 82 | const auto pushPrimitive = [ptr, &offset](auto elem) noexcept { 83 | std::memcpy(ptr + offset, &elem, sizeof(elem)); 84 | offset += sizeof(elem); 85 | }; 86 | 87 | for (uint32_t i = 0U; i < iox::capro::CLASS_HASH_ELEMENT_COUNT; ++i) 88 | { 89 | pushPrimitive(datagramHeader.serviceHash[i]); 90 | } 91 | pushPrimitive(datagramHeader.messageHash); 92 | pushPrimitive(datagramHeader.submessageCount); 93 | pushPrimitive(datagramHeader.submessageOffset); 94 | pushPrimitive(datagramHeader.submessageSize); 95 | pushPrimitive(datagramHeader.userPayloadSize); 96 | pushPrimitive(datagramHeader.userPayloadAlignment); 97 | pushPrimitive(datagramHeader.userHeaderSize); 98 | 99 | iox::cxx::Expects(offset <= maxIoxChunkDatagramHeaderSerializationSize()); 100 | return static_cast(offset); 101 | } 102 | 103 | uint32_t iox::p3com::deserialize(iox::p3com::IoxChunkDatagramHeader_t& datagramHeader, const char* ptr, size_t size) noexcept 104 | { 105 | size_t offset = 0U; 106 | const auto loadPrimitive = [ptr, &offset, size](auto* elem) noexcept { 107 | iox::cxx::Expects(offset + sizeof(*elem) <= size); 108 | std::memcpy(elem, ptr + offset, sizeof(*elem)); 109 | offset += sizeof(*elem); 110 | }; 111 | 112 | for (uint32_t i = 0U; i < iox::capro::CLASS_HASH_ELEMENT_COUNT; ++i) 113 | { 114 | loadPrimitive(&datagramHeader.serviceHash[i]); 115 | } 116 | loadPrimitive(&datagramHeader.messageHash); 117 | loadPrimitive(&datagramHeader.submessageCount); 118 | loadPrimitive(&datagramHeader.submessageOffset); 119 | loadPrimitive(&datagramHeader.submessageSize); 120 | loadPrimitive(&datagramHeader.userPayloadSize); 121 | loadPrimitive(&datagramHeader.userPayloadAlignment); 122 | loadPrimitive(&datagramHeader.userHeaderSize); 123 | 124 | iox::cxx::Expects(offset <= maxIoxChunkDatagramHeaderSerializationSize()); 125 | return static_cast(offset); 126 | } 127 | -------------------------------------------------------------------------------- /source/p3com/generic/transport_forwarder.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/generic/transport_forwarder.hpp" 4 | #include "p3com/generic/pending_messages.hpp" 5 | #include "p3com/generic/data_writer.hpp" 6 | #include "p3com/utility/helper_functions.hpp" 7 | #include "p3com/internal/log/logging.hpp" 8 | 9 | iox::p3com::TransportForwarder::TransportForwarder( 10 | iox::p3com::DiscoveryManager& discovery, 11 | iox::p3com::PendingMessageManager& pendingMessageManager, 12 | const iox::cxx::vector& forwardedServices) noexcept 13 | : m_discovery(discovery) 14 | , m_pendingMessageManager(pendingMessageManager) 15 | , m_terminateFlag(false) 16 | { 17 | for (auto& service : forwardedServices) 18 | { 19 | m_forwardedServiceHashes.emplace_back(service.getClassHash()); 20 | 21 | const NodeName_t FORWARDED_SERVICES_NODE_NAME{"iox-gw-forwarded"}; 22 | iox::popo::SubscriberOptions options; 23 | options.nodeName = FORWARDED_SERVICES_NODE_NAME; 24 | m_forwardedServiceSubscribers.emplace_back(service, options); 25 | 26 | m_waitset.attachState(m_forwardedServiceSubscribers.back(), iox::popo::SubscriberState::HAS_DATA) 27 | .and_then([&service]() { 28 | iox::p3com::LogInfo() << "[TransportForwarder] Set up forwarding for service: " << service; 29 | }) 30 | .or_else([](auto& error) { 31 | iox::p3com::LogError() << "[TransportForwarder] Could not attach listener subscriber callback!" 32 | << " Error code: " << static_cast(error); 33 | }); 34 | } 35 | 36 | if (!forwardedServices.empty()) 37 | { 38 | m_waitsetThread = std::thread(&TransportForwarder::waitsetLoop, this); 39 | } 40 | } 41 | 42 | void iox::p3com::TransportForwarder::join() noexcept 43 | { 44 | m_terminateFlag.store(true); 45 | if (m_waitsetThread.joinable()) 46 | { 47 | m_waitsetThread.join(); 48 | } 49 | } 50 | 51 | void iox::p3com::TransportForwarder::push(const void* userPayload, 52 | iox::capro::ServiceDescription::ClassHash hash, 53 | DeviceIndex_t deviceIndex) noexcept 54 | { 55 | if (iox::p3com::containsElement(m_forwardedServiceHashes, hash)) 56 | { 57 | std::lock_guard lock(m_messagesToForwardMutex); 58 | m_messagesToForward.emplace(userPayload, deviceIndex); 59 | } 60 | } 61 | 62 | void iox::p3com::TransportForwarder::waitsetLoop() noexcept 63 | { 64 | constexpr iox::units::Duration WAITSET_TIMEOUT{iox::units::Duration::fromMilliseconds(50)}; 65 | while (!m_terminateFlag.load()) 66 | { 67 | const auto notificationVector = m_waitset.timedWait(WAITSET_TIMEOUT); 68 | for (auto& notification : notificationVector) 69 | { 70 | iox::popo::UntypedSubscriber& subscriber = *notification->getOrigin(); 71 | const void* userPayload = nullptr; 72 | { 73 | std::lock_guard lock{m_forwardedServiceSubscribersMutex}; 74 | subscriber.take().and_then([&userPayload](const void* p) { userPayload = p; }).or_else([](auto& error) { 75 | switch (error) 76 | { 77 | case iox::popo::ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL: 78 | iox::p3com::LogError() << "[TransportForwarder] Forwarder subscriber failed because too many " 79 | "chunks are held in parallel!"; 80 | break; 81 | case iox::popo::ChunkReceiveResult::NO_CHUNK_AVAILABLE: 82 | break; // This is fine, it just means there are currently no messages to take 83 | } 84 | }); 85 | } 86 | 87 | if (userPayload != nullptr) 88 | { 89 | const auto chunkHeader = iox::mepoo::ChunkHeader::fromUserPayload(userPayload); 90 | const auto hash = subscriber.getServiceDescription().getClassHash(); 91 | 92 | iox::p3com::DeviceIndex_t deviceIndex; 93 | // This check is not actually needed, because if the service hash is not 94 | // one of the forwarded ones, it definitely will not be present in 95 | // m_messagesToForward. However, this way we avoid the overhead of locking 96 | // the mutex, so this might be a teeny tiny optimization. 97 | if (iox::p3com::containsElement(m_forwardedServiceHashes, hash)) 98 | { 99 | std::lock_guard lock(m_messagesToForwardMutex); 100 | iox::p3com::DeviceIndex_t* deviceIndexPtr = m_messagesToForward.find(userPayload); 101 | if (deviceIndexPtr != nullptr) 102 | { 103 | deviceIndex = *deviceIndexPtr; 104 | m_messagesToForward.erase(deviceIndexPtr); 105 | } 106 | } 107 | 108 | const auto deviceIndices = m_discovery.generateDeviceIndicesForwarding(hash, deviceIndex); 109 | if (deviceIndices.empty()) 110 | { 111 | std::lock_guard lock{m_forwardedServiceSubscribersMutex}; 112 | subscriber.release(userPayload); 113 | } 114 | else 115 | { 116 | iox::p3com::LogInfo() << "[TransportForwarder] Forwarding user message for service: " 117 | << subscriber.getServiceDescription(); 118 | 119 | iox::p3com::IoxChunkDatagramHeader_t datagramHeader; 120 | datagramHeader.serviceHash = hash; 121 | datagramHeader.messageHash = iox::p3com::generateHash(); 122 | datagramHeader.userPayloadSize = chunkHeader->userPayloadSize(); 123 | datagramHeader.userPayloadAlignment = chunkHeader->userPayloadAlignment(); 124 | datagramHeader.userHeaderSize = 125 | (chunkHeader->userHeaderId() == iox::mepoo::ChunkHeader::NO_USER_HEADER) 126 | ? 0U 127 | : chunkHeader->userHeaderSize(); 128 | // submessage* fields will be filled for every submessage individually inside writeSegmented 129 | 130 | iox::p3com::writeSegmented(datagramHeader, 131 | *chunkHeader, 132 | deviceIndices, 133 | m_pendingMessageManager, 134 | m_forwardedServiceSubscribersMutex, 135 | subscriber); 136 | } 137 | } 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /source/p3com/introspection/gw_introspection.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "iceoryx_posh/popo/subscriber.hpp" 4 | #include "iceoryx_posh/popo/wait_set.hpp" 5 | #include "iceoryx_posh/runtime/service_discovery.hpp" 6 | #include "iceoryx_hoofs/internal/units/duration.hpp" 7 | 8 | #include "p3com/introspection/gw_introspection_types.hpp" 9 | #include "p3com/introspection/gw_introspection.hpp" 10 | 11 | bool iox::p3com::isGwRunning() noexcept 12 | { 13 | bool found = false; 14 | iox::runtime::ServiceDiscovery serviceDiscovery; 15 | serviceDiscovery.findService( 16 | iox::p3com::IntrospectionGwService.getServiceIDString(), 17 | iox::p3com::IntrospectionGwService.getInstanceIDString(), 18 | iox::p3com::IntrospectionGwService.getEventIDString(), 19 | [&found](const iox::capro::ServiceDescription&) { found = true; }, 20 | iox::popo::MessagingPattern::PUB_SUB); 21 | return found; 22 | } 23 | 24 | bool iox::p3com::hasGwRegistered(iox::popo::uid_t publisherUid) noexcept 25 | { 26 | iox::popo::Subscriber sub{iox::p3com::IntrospectionGwService, {1U, 1U}}; 27 | while (sub.getSubscriptionState() != SubscribeState::SUBSCRIBED) 28 | { 29 | } 30 | 31 | bool hasRegistered = false; 32 | sub.take().and_then([publisherUid, &hasRegistered](auto& data) { 33 | const auto it = 34 | std::find(data->publisherUids.begin(), data->publisherUids.end(), static_cast(publisherUid)); 35 | hasRegistered = it != data->publisherUids.end(); 36 | }); 37 | 38 | // Need to wait for unsubscription to avoid exhausting subscriber ports 39 | sub.unsubscribe(); 40 | while (sub.getSubscriptionState() != SubscribeState::NOT_SUBSCRIBED) 41 | { 42 | } 43 | return hasRegistered; 44 | } 45 | 46 | bool iox::p3com::waitForGwRegistration(iox::popo::uid_t publisherUid, iox::units::Duration timeout) noexcept 47 | { 48 | iox::popo::Subscriber sub{iox::p3com::IntrospectionGwService, {1U, 1U}}; 49 | while (sub.getSubscriptionState() != SubscribeState::SUBSCRIBED) 50 | { 51 | } 52 | 53 | bool hasRegistered = false; 54 | auto takeLambda = [publisherUid, &hasRegistered](auto& data) { 55 | const auto it = 56 | std::find(data->publisherUids.begin(), data->publisherUids.end(), static_cast(publisherUid)); 57 | hasRegistered = it != data->publisherUids.end(); 58 | }; 59 | 60 | if (sub.hasData()) 61 | { 62 | sub.take().and_then(takeLambda); 63 | } 64 | 65 | if(!hasRegistered) 66 | { 67 | iox::popo::WaitSet<> waitset; 68 | const bool attached = static_cast(waitset.attachState(sub, iox::popo::SubscriberState::HAS_DATA)); 69 | if (!attached) 70 | { 71 | return false; 72 | } 73 | 74 | auto now = std::chrono::steady_clock::now(); 75 | const auto end = now + std::chrono::nanoseconds{timeout.toNanoseconds()}; 76 | while (!hasRegistered && now < end) 77 | { 78 | const auto remaining = std::chrono::duration_cast(end - now); 79 | auto notificationVector = waitset.timedWait(iox::units::Duration::fromNanoseconds(remaining.count())); 80 | if (notificationVector.empty()) 81 | { 82 | // Timeout 83 | break; 84 | } 85 | for (auto& notification : notificationVector) 86 | { 87 | if (notification->doesOriginateFrom(&sub)) 88 | { 89 | sub.take().and_then(takeLambda); 90 | if (hasRegistered) 91 | { 92 | break; 93 | } 94 | } 95 | } 96 | now = std::chrono::steady_clock::now(); 97 | } 98 | } 99 | 100 | // Need to wait for unsubscription to avoid exhausting subscriber ports 101 | sub.unsubscribe(); 102 | while (sub.getSubscriptionState() != SubscribeState::NOT_SUBSCRIBED) 103 | { 104 | } 105 | return hasRegistered; 106 | } 107 | 108 | bool iox::p3com::hasServiceRegistered(const iox::capro::ServiceDescription& service) noexcept 109 | { 110 | iox::popo::Subscriber sub{iox::p3com::IntrospectionGwService, {1U, 1U}}; 111 | while (sub.getSubscriptionState() != SubscribeState::SUBSCRIBED) 112 | { 113 | } 114 | 115 | bool hasRegistered = false; 116 | sub.take().and_then([&service, &hasRegistered](auto& data) { 117 | const auto it = std::find(data->subscriberServices.begin(), data->subscriberServices.end(), service); 118 | hasRegistered = it != data->subscriberServices.end(); 119 | }); 120 | 121 | // Need to wait for unsubscription to avoid exhausting subscriber ports 122 | sub.unsubscribe(); 123 | while (sub.getSubscriptionState() != SubscribeState::NOT_SUBSCRIBED) 124 | { 125 | } 126 | return hasRegistered; 127 | } 128 | 129 | bool iox::p3com::waitForServiceRegistration(const iox::capro::ServiceDescription& service, 130 | iox::units::Duration timeout) noexcept 131 | { 132 | iox::popo::Subscriber sub{iox::p3com::IntrospectionGwService, {1U, 1U}}; 133 | while (sub.getSubscriptionState() != SubscribeState::SUBSCRIBED) 134 | { 135 | } 136 | 137 | bool hasRegistered = false; 138 | auto takeLambda = [&service, &hasRegistered](auto& data) { 139 | const auto it = std::find(data->subscriberServices.begin(), data->subscriberServices.end(), service); 140 | hasRegistered = it != data->subscriberServices.end(); 141 | }; 142 | 143 | if (sub.hasData()) 144 | { 145 | sub.take().and_then(takeLambda); 146 | } 147 | 148 | if(!hasRegistered) 149 | { 150 | iox::popo::WaitSet<> waitset; 151 | const bool attached = static_cast(waitset.attachState(sub, iox::popo::SubscriberState::HAS_DATA)); 152 | if (!attached) 153 | { 154 | return false; 155 | } 156 | 157 | auto now = std::chrono::steady_clock::now(); 158 | const auto end = now + std::chrono::nanoseconds{timeout.toNanoseconds()}; 159 | while (!hasRegistered && now < end) 160 | { 161 | const auto remaining = std::chrono::duration_cast(end - now); 162 | auto notificationVector = waitset.timedWait(iox::units::Duration::fromNanoseconds(remaining.count())); 163 | if (notificationVector.empty()) 164 | { 165 | // Timeout 166 | break; 167 | } 168 | for (auto& notification : notificationVector) 169 | { 170 | if (notification->doesOriginateFrom(&sub)) 171 | { 172 | sub.take().and_then(takeLambda); 173 | if (hasRegistered) 174 | { 175 | break; 176 | } 177 | } 178 | } 179 | now = std::chrono::steady_clock::now(); 180 | } 181 | } 182 | 183 | // Need to wait for unsubscription to avoid exhausting subscriber ports 184 | sub.unsubscribe(); 185 | while (sub.getSubscriptionState() != SubscribeState::NOT_SUBSCRIBED) 186 | { 187 | } 188 | return hasRegistered; 189 | } 190 | -------------------------------------------------------------------------------- /source/p3com/log/logging.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | // SPDX-License-Identifier: Apache-2.0 16 | 17 | /* Modifications by NXP 2022 */ 18 | 19 | #include "p3com/internal/log/logging.hpp" 20 | 21 | namespace iox 22 | { 23 | namespace p3com 24 | { 25 | // Ctx 26 | constexpr char P3comLoggingComponent::Ctx[]; 27 | // Description 28 | constexpr char P3comLoggingComponent::Description[]; 29 | 30 | } // namespace p3com 31 | } // namespace iox 32 | -------------------------------------------------------------------------------- /source/p3com/transport/transport_info.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/transport/transport_info.hpp" 4 | #include "p3com/generic/config.hpp" 5 | 6 | std::array, iox::p3com::TRANSPORT_TYPE_COUNT> iox::p3com::TransportInfo::s_transports; 7 | iox::p3com::bitset_t iox::p3com::TransportInfo::s_bitset; 8 | iox::p3com::TransportInfo::transportFailCallback_t iox::p3com::TransportInfo::s_failCallback; 9 | 10 | void iox::p3com::TransportInfo::enable(iox::p3com::TransportType type) noexcept 11 | { 12 | const auto i = index(type); 13 | s_bitset[i] = true; 14 | 15 | iox::p3com::LogInfo() << "[TransportInfo] Enabling transport type: " << iox::p3com::TRANSPORT_TYPE_NAMES[i]; 16 | switch (type) 17 | { 18 | case iox::p3com::TransportType::PCIE: 19 | #if defined(PCIE_GATEWAY) 20 | s_transports[i] = std::make_unique(); 21 | #else 22 | iox::p3com::LogError() << "[TransportInfo] Invalid transport type: PCIe"; 23 | #endif 24 | break; 25 | case iox::p3com::TransportType::UDP: 26 | #if defined(UDP_GATEWAY) 27 | s_transports[i] = std::make_unique(); 28 | #else 29 | iox::p3com::LogError() << "[TransportInfo] Invalid transport type: UDP"; 30 | #endif 31 | break; 32 | case iox::p3com::TransportType::TCP: 33 | #if defined(TCP_GATEWAY) 34 | s_transports[i] = std::make_unique(); 35 | #else 36 | iox::p3com::LogError() << "[TransportInfo] Invalid transport type: TCP"; 37 | #endif 38 | break; 39 | default: 40 | iox::p3com::LogError() << "[TransportInfo] Invalid transport type"; 41 | return; 42 | } 43 | } 44 | 45 | void iox::p3com::TransportInfo::enableAll() noexcept 46 | { 47 | #if defined(PCIE_GATEWAY) 48 | enable(iox::p3com::TransportType::PCIE); 49 | #endif 50 | #if defined(UDP_GATEWAY) && !defined(TCP_GATEWAY) 51 | enable(iox::p3com::TransportType::UDP); 52 | #endif 53 | #if defined(TCP_GATEWAY) 54 | enable(iox::p3com::TransportType::TCP); 55 | #endif 56 | } 57 | 58 | void iox::p3com::TransportInfo::disable(iox::p3com::TransportType type) noexcept 59 | { 60 | const auto i = index(type); 61 | s_bitset[i] = false; 62 | 63 | iox::p3com::LogWarn() << "[TransportInfo] Disabled transport type: " << iox::p3com::TRANSPORT_TYPE_NAMES[i]; 64 | 65 | // We shouldn't actually destroy the transport object for two reasons: 66 | // * Other threads can concurrently call its methods (and we want to avoid 67 | // introducing another mutex). 68 | // * In case of failure, it might not even be safe to call the destruction 69 | // of the transport (graceful closing of the resources might fail, too). 70 | // s_transports[i].reset(); 71 | } 72 | 73 | void iox::p3com::TransportInfo::registerTransportFailCallback( 74 | iox::p3com::TransportInfo::transportFailCallback_t callback) noexcept 75 | { 76 | s_failCallback = callback; 77 | } 78 | -------------------------------------------------------------------------------- /source/tcp/tcp_client_transport_session.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/transport/tcp/tcp_client_transport_session.hpp" 4 | 5 | constexpr std::chrono::seconds iox::p3com::tcp::TCPClientTransportSession::M_RETRY_TIMEOUT; 6 | 7 | iox::p3com::tcp::TCPClientTransportSession::TCPClientTransportSession( 8 | asio::io_service& io_service, 9 | const iox::p3com::tcp::TCPTransportSession::dataCallback_t& dataCallbackHandler, 10 | const iox::p3com::tcp::TCPTransportSession::sessionClosedCallback_t& sessionClosedHandler, 11 | const sessionOpenCallback_t& sessionOpenHandler, 12 | asio::ip::tcp::endpoint remote_endpoint, 13 | int max_reconnection_attempts) noexcept 14 | : TCPTransportSession(io_service, dataCallbackHandler, sessionClosedHandler) 15 | , m_resolver(io_service) 16 | , m_remoteEndpoint(remote_endpoint) 17 | , m_retriesLeft(max_reconnection_attempts) 18 | , m_retryTimer(io_service, M_RETRY_TIMEOUT) 19 | , m_sessionOpenCallback(std::move(sessionOpenHandler)) 20 | { 21 | } 22 | 23 | asio::ip::tcp::endpoint iox::p3com::tcp::TCPClientTransportSession::remoteEndpoint() noexcept 24 | { 25 | return m_remoteEndpoint; 26 | } 27 | 28 | void iox::p3com::tcp::TCPClientTransportSession::start() noexcept 29 | { 30 | connectToEndpoint(); 31 | } 32 | 33 | void iox::p3com::tcp::TCPClientTransportSession::connectToEndpoint() noexcept 34 | { 35 | getSocket().async_connect(m_remoteEndpoint, [this](std::error_code ec) { 36 | if (ec) 37 | { 38 | iox::p3com::LogError() << "[TCPTransport] " << ec.message(); 39 | connectionFailedHandler(); 40 | } 41 | else 42 | { 43 | m_sessionOpenCallback(this); 44 | receiveTcpData(); 45 | } 46 | }); 47 | } 48 | 49 | void iox::p3com::tcp::TCPClientTransportSession::connectionFailedHandler() noexcept 50 | { 51 | asio::error_code ec; 52 | getSocket().close(ec); 53 | if (ec) 54 | { 55 | iox::p3com::LogError() << "[TCPTransport] " << ec.message(); 56 | } 57 | 58 | if (m_retriesLeft > 0) 59 | { 60 | m_retriesLeft--; 61 | // Retry connection after a short time 62 | m_retryTimer.async_wait([this](std::error_code ec) { 63 | if (ec) 64 | { 65 | iox::p3com::LogError() << "[TCPTransport] " << ec.message(); 66 | sessionClosedHandler(); 67 | } 68 | else 69 | { 70 | connectToEndpoint(); 71 | } 72 | }); 73 | } 74 | else 75 | { 76 | sessionClosedHandler(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /source/tcp/tcp_server_transport_session.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/transport/tcp/tcp_server_transport_session.hpp" 4 | #include "p3com/internal/log/logging.hpp" 5 | 6 | iox::p3com::tcp::TCPServerTransportSession::TCPServerTransportSession( 7 | asio::io_service& io_service, 8 | const dataCallback_t& dataCallbackHandler, 9 | const sessionClosedCallback_t& sessionClosedHandler) noexcept 10 | : TCPTransportSession(io_service, dataCallbackHandler, sessionClosedHandler) 11 | { 12 | } 13 | 14 | asio::ip::tcp::endpoint iox::p3com::tcp::TCPServerTransportSession::remoteEndpoint() noexcept 15 | { 16 | if (m_remoteEndpoint.address() == asio::ip::address_v4::any()) 17 | { 18 | asio::error_code ec; 19 | m_remoteEndpoint = getSocket().remote_endpoint(ec); 20 | if (ec) 21 | { 22 | iox::p3com::LogError() << "[TCPTransport] " << ec.message(); 23 | } 24 | } 25 | return m_remoteEndpoint; 26 | } 27 | 28 | void iox::p3com::tcp::TCPServerTransportSession::start() noexcept 29 | { 30 | try 31 | { 32 | // server side of connection 33 | getSocket().set_option(asio::ip::tcp::no_delay(true)); 34 | receiveTcpData(); 35 | } 36 | catch (std::exception& e) 37 | { 38 | iox::p3com::LogError() << "[TCPTransport] " << e.what(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /source/tcp/tcp_transport.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/transport/tcp/tcp_transport.hpp" 4 | #include "p3com/generic/types.hpp" 5 | #include "p3com/internal/log/logging.hpp" 6 | #include "p3com/transport/transport.hpp" 7 | #include 8 | #include 9 | 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | 16 | iox::p3com::tcp::TCPTransport::TCPTransport() noexcept 17 | : m_context() 18 | , m_dataAcceptor(m_context) 19 | , m_broadcast(m_context) 20 | , m_serverListeningSession(nullptr) 21 | { 22 | auto endpoint = asio::ip::tcp::endpoint(asio::ip::tcp::v4(), DATA_PORT); 23 | try 24 | { 25 | m_dataAcceptor.open(endpoint.protocol()); 26 | m_dataAcceptor.set_option(asio::ip::tcp::acceptor::reuse_address(true)); 27 | m_dataAcceptor.bind(endpoint); 28 | m_dataAcceptor.listen(asio::socket_base::max_listen_connections); 29 | } 30 | catch (std::exception& e) 31 | { 32 | iox::p3com::LogError() << "[TCPTransport] " << e.what(); 33 | setFailed(); 34 | return; 35 | } 36 | m_thread = std::thread([this]() { 37 | try 38 | { 39 | m_work.emplace(m_context); 40 | m_context.run(); 41 | 42 | iox::p3com::LogInfo() << "[TCPTransport] Worker thread has exited"; 43 | } 44 | catch (std::exception& e) 45 | { 46 | iox::p3com::LogError() << "[TCPTransport] " << e.what(); 47 | setFailed(); 48 | return; 49 | } 50 | }); 51 | 52 | startAccept(); 53 | m_broadcast.registerDiscoveryCallback([this](const void* data, size_t size, DeviceIndex_t deviceIndex) { 54 | udpDiscoveryCallback(data, size, deviceIndex); 55 | }); 56 | 57 | iox::p3com::LogInfo() << "[TCPTransport] Created TCP listener and waiting for clients on endpoint " 58 | << endpoint.address().to_string() << ":" << std::to_string(endpoint.port()); 59 | } 60 | 61 | iox::p3com::tcp::TCPTransport::~TCPTransport() 62 | { 63 | m_work.reset(); 64 | m_context.stop(); 65 | m_thread.join(); 66 | } 67 | 68 | 69 | void iox::p3com::tcp::TCPTransport::addSession(asio::ip::tcp::endpoint& endpoint) noexcept 70 | { 71 | // Add the session to the session list 72 | m_transportSessions.emplace_back(std::make_unique( 73 | m_context, handleUserDataCallback(this), handleSessionClose(this), handleSessionOpen(this), endpoint)); 74 | m_transportSessions.back()->start(); 75 | } 76 | 77 | void iox::p3com::tcp::TCPTransport::addSession() noexcept 78 | { 79 | m_transportSessions.push_back(std::move(m_serverListeningSession)); 80 | m_transportSessions.back()->start(); 81 | handleSessionOpen(this)(m_transportSessions.back().get()); 82 | } 83 | 84 | void iox::p3com::tcp::TCPTransport::startAccept() noexcept 85 | { 86 | m_serverListeningSession = 87 | std::make_unique(m_context, handleUserDataCallback(this), handleSessionClose(this)); 88 | 89 | 90 | m_dataAcceptor.async_accept(m_serverListeningSession->getSocket(), [this](asio::error_code ec) { 91 | if (ec) 92 | { 93 | iox::p3com::LogError() << "[TCPTransport] " << ec.message(); 94 | setFailed(); 95 | } 96 | else 97 | { 98 | iox::p3com::LogInfo() << "[TCPTransport] New connection request from client " 99 | << m_serverListeningSession->remoteEndpointToString(); 100 | std::lock_guard transportSessionsLock(m_transportSessionsMutex); 101 | 102 | auto iter = findSession(m_serverListeningSession->remoteEndpoint()); 103 | if (iter == m_transportSessions.end()) 104 | { 105 | // device not found, add it 106 | addSession(); 107 | } 108 | else 109 | { 110 | iox::p3com::LogWarn() << "[TCPTransport] Already connected to " 111 | << m_serverListeningSession->remoteEndpointToString() 112 | << " as client, closing server connection."; 113 | } 114 | startAccept(); 115 | } 116 | }); 117 | } 118 | 119 | 120 | iox::p3com::tcp::TCPServerTransportSession::sessionClosedCallback_t 121 | iox::p3com::tcp::TCPTransport::handleSessionClose(iox::p3com::tcp::TCPTransport* self) noexcept 122 | { 123 | return [self](TCPTransportSession* session) { 124 | std::lock_guard transportSessionsLock(self->m_transportSessionsMutex); 125 | auto session_it = std::find_if(self->m_transportSessions.begin(), 126 | self->m_transportSessions.end(), 127 | [session](const auto& iter) { return iter.get() == session; }); 128 | if (session_it != self->m_transportSessions.end()) 129 | { 130 | iox::p3com::LogInfo() << "[TCPTransport] Successfully removed session " << session->remoteEndpointToString(); 131 | self->m_transportSessions.erase(session_it); 132 | } 133 | }; 134 | } 135 | 136 | void iox::p3com::tcp::TCPTransport::udpDiscoveryCallback(const void* data, 137 | size_t size, 138 | DeviceIndex_t deviceIndex) noexcept 139 | { 140 | auto endpoint = m_broadcast.getEndpoint(deviceIndex.device); 141 | std::lock_guard transportSessionsLock(m_transportSessionsMutex); 142 | auto tcpEndpoint = asio::ip::tcp::endpoint(endpoint.address(), DATA_PORT); 143 | auto iter = findSession(tcpEndpoint); 144 | if (iter == m_transportSessions.end()) 145 | { 146 | // device not found, add it 147 | iox::p3com::LogInfo() << "[TCPTransport] Discovered remote GW, not yet registered, adding " 148 | << endpoint.address().to_string(); 149 | iox::cxx::vector serializedInfo(size); 150 | std::memcpy(serializedInfo.data(), data, size); 151 | m_infoToReport.emplace_back(tcpEndpoint, serializedInfo); 152 | addSession(tcpEndpoint); 153 | } 154 | else 155 | { 156 | remoteDiscoveryHandler(data, size, static_cast(std::distance(m_transportSessions.begin(), iter))); 157 | } 158 | } 159 | std::unique_ptr* 160 | iox::p3com::tcp::TCPTransport::findSession(const asio::ip::tcp::endpoint& endpoint) noexcept 161 | { 162 | return std::find_if(m_transportSessions.begin(), m_transportSessions.end(), [&endpoint](auto& iter) { 163 | return iter->remoteEndpoint().address() == endpoint.address(); 164 | }); 165 | } 166 | void iox::p3com::tcp::TCPTransport::remoteDiscoveryHandler(const void* data, 167 | size_t size, 168 | const uint32_t device) const noexcept 169 | { 170 | if (m_remoteDiscoveryCallback) 171 | { 172 | m_remoteDiscoveryCallback(data, size, {TransportType::TCP, device}); 173 | } 174 | } 175 | 176 | void iox::p3com::tcp::TCPTransport::registerDiscoveryCallback(iox::p3com::remoteDiscoveryCallback_t callback) noexcept 177 | { 178 | m_remoteDiscoveryCallback = std::move(callback); 179 | } 180 | 181 | void iox::p3com::tcp::TCPTransport::registerUserDataCallback(iox::p3com::userDataCallback_t callback) noexcept 182 | { 183 | m_userDataCallback = std::move(callback); 184 | } 185 | 186 | 187 | void iox::p3com::tcp::TCPTransport::sendBroadcast(const void* data, size_t size) noexcept 188 | { 189 | m_broadcast.sendBroadcast(data, size); 190 | } 191 | 192 | bool iox::p3com::tcp::TCPTransport::sendUserData( 193 | const void* data1, size_t size1, const void* data2, size_t size2, uint32_t deviceIndex) noexcept 194 | { 195 | if (deviceIndex >= m_transportSessions.size()) 196 | { 197 | iox::p3com::LogWarn() << "[TCPTransport] Invalid device index when sending user data"; 198 | return false; 199 | } 200 | iox::p3com::LogInfo() << "[TCPTransport] Sending data to " 201 | << m_transportSessions[deviceIndex]->remoteEndpointToString(); 202 | return m_transportSessions[deviceIndex]->sendData(data1, size1, data2, size2); 203 | } 204 | 205 | size_t iox::p3com::tcp::TCPTransport::maxMessageSize() const noexcept 206 | { 207 | return TCPTransportSession::MAX_PACKET_SIZE; 208 | } 209 | 210 | iox::p3com::TransportType iox::p3com::tcp::TCPTransport::getType() const noexcept 211 | { 212 | return iox::p3com::TransportType::TCP; 213 | } 214 | 215 | iox::p3com::tcp::TCPTransportSession::dataCallback_t 216 | iox::p3com::tcp::TCPTransport::handleUserDataCallback(iox::p3com::tcp::TCPTransport* self) noexcept 217 | { 218 | return [self](const void* data, size_t size, asio::ip::tcp::endpoint endpoint) { 219 | const auto index = self->m_broadcast.getIndex(endpoint.address()); 220 | if (index.has_value()) 221 | { 222 | if (self->m_userDataCallback) 223 | { 224 | self->m_userDataCallback(data, size, {iox::p3com::TransportType::TCP, *index}); 225 | } 226 | } 227 | else 228 | { 229 | iox::p3com::LogError() << "[TCPTransport] Received user data message from an unknown device! Discarding!"; 230 | } 231 | }; 232 | } 233 | 234 | iox::p3com::tcp::TCPClientTransportSession::sessionOpenCallback_t 235 | iox::p3com::tcp::TCPTransport::handleSessionOpen(iox::p3com::tcp::TCPTransport* self) noexcept 236 | { 237 | return [self](TCPTransportSession* session) { 238 | LogInfo() << "[TCPTransport] New connection established: " << session->endpointToString() 239 | << " Sessions: " << self->m_transportSessions.size(); 240 | auto infoToReportIt = 241 | std::find_if(self->m_infoToReport.begin(), self->m_infoToReport.end(), [session](const auto& iter) { 242 | return iter.first.address() == session->remoteEndpoint().address(); 243 | }); 244 | 245 | if (infoToReportIt != self->m_infoToReport.end()) 246 | { 247 | auto iter = self->findSession(session->remoteEndpoint()); 248 | const auto deviceIdx = static_cast(std::distance(self->m_transportSessions.begin(), iter)); 249 | const auto& vec = infoToReportIt->second; 250 | self->remoteDiscoveryHandler(vec.data(), vec.size(), deviceIdx); 251 | self->m_infoToReport.erase(infoToReportIt); 252 | } 253 | }; 254 | } 255 | -------------------------------------------------------------------------------- /source/tcp/tcp_transport_session.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/transport/tcp/tcp_transport_session.hpp" 4 | #include "p3com/internal/log/logging.hpp" 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | iox::p3com::tcp::TCPTransportSession::TCPTransportSession(asio::io_service& io_service, 12 | const dataCallback_t& dataCallbackHandler, 13 | const sessionClosedCallback_t& sessionClosedHandler) noexcept 14 | : m_sessionClosedCallback(std::move(sessionClosedHandler)) 15 | , m_dataCallback(std::move(dataCallbackHandler)) 16 | , m_dataSocket(io_service) 17 | { 18 | } 19 | 20 | iox::p3com::tcp::TCPTransportSession::~TCPTransportSession() 21 | { 22 | } 23 | 24 | asio::ip::tcp::socket& iox::p3com::tcp::TCPTransportSession::getSocket() noexcept 25 | { 26 | return m_dataSocket; 27 | } 28 | 29 | std::string iox::p3com::tcp::TCPTransportSession::endpointToString() noexcept 30 | { 31 | std::stringstream sstream; 32 | sstream << m_dataSocket.local_endpoint() << " <- " << remoteEndpoint(); 33 | return sstream.str(); 34 | } 35 | 36 | std::string iox::p3com::tcp::TCPTransportSession::remoteEndpointToString() noexcept 37 | { 38 | std::stringstream sstream; 39 | sstream << remoteEndpoint(); 40 | return sstream.str(); 41 | } 42 | 43 | bool iox::p3com::tcp::TCPTransportSession::sendData(const void* data1, 44 | size_t size1, 45 | const void* data2, 46 | size_t size2) noexcept 47 | { 48 | try 49 | { 50 | // First, we write a size_t integer with the size of the following message 51 | const size_t totalSize = size1 + size2; 52 | const auto writtenSize = asio::write(m_dataSocket, asio::const_buffer{&totalSize, sizeof(totalSize)}); 53 | cxx::Expects(writtenSize == sizeof(totalSize)); 54 | 55 | // Next, we actually write the message 56 | constexpr uint32_t BUFFER_COUNT = 2U; 57 | std::array buffers{asio::const_buffer{data1, size1}, 58 | asio::const_buffer{data2, size2}}; 59 | const auto writtenData = asio::write(m_dataSocket, buffers); 60 | cxx::Expects(writtenData == totalSize); 61 | } 62 | catch (std::exception& e) 63 | { 64 | iox::p3com::LogWarn() << "[TCPTransport] " << e.what(); 65 | } 66 | return false; 67 | } 68 | 69 | void iox::p3com::tcp::TCPTransportSession::receiveTcpData() noexcept 70 | { 71 | const auto processErrorCode = [this](std::error_code ec) { 72 | if (ec) 73 | { 74 | iox::p3com::LogInfo() << "[TCPTransport] " << ec.message() << ", going to close socket " 75 | << remoteEndpointToString(); 76 | sessionClosedHandler(); 77 | return true; 78 | } 79 | else 80 | { 81 | return false; 82 | } 83 | }; 84 | 85 | // After we have read the size of the full message, we read the actual message payload 86 | auto readInner = [this, processErrorCode](std::error_code ec, std::size_t size) { 87 | if (!processErrorCode(ec)) 88 | { 89 | iox::p3com::LogInfo() << "[TCPTransport] Received data from " << remoteEndpointToString(); 90 | m_dataCallback(m_readBuffer.data(), size, remoteEndpoint()); 91 | receiveTcpData(); 92 | } 93 | }; 94 | 95 | const auto readOuter = [this, processErrorCode, readInner = std::move(readInner)](std::error_code ec, std::size_t) { 96 | if (!processErrorCode(ec)) 97 | { 98 | // m_readBufferSize now stores the size of the following message, we need to read exactly this many bytes 99 | asio::async_read(m_dataSocket, asio::buffer(m_readBuffer, m_readBufferSize), std::move(readInner)); 100 | } 101 | }; 102 | 103 | // We read a size_t integer with the size of the following message into m_readBufferSize 104 | asio::async_read(m_dataSocket, asio::buffer(&m_readBufferSize, sizeof(m_readBufferSize)), std::move(readOuter)); 105 | } 106 | 107 | void iox::p3com::tcp::TCPTransportSession::sessionClosedHandler() noexcept 108 | { 109 | m_dataSocket.close(); 110 | m_sessionClosedCallback(this); 111 | } 112 | -------------------------------------------------------------------------------- /source/udp/udp_transport.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/generic/types.hpp" 4 | #include "p3com/internal/log/logging.hpp" 5 | #include "p3com/transport/transport.hpp" 6 | 7 | #include "p3com/transport/udp/udp_transport.hpp" 8 | 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | 16 | iox::p3com::udp::UDPTransport::UDPTransport() noexcept 17 | : m_context() 18 | , m_dataSocket(m_context, asio::ip::udp::endpoint(asio::ip::address_v4::any(), DATA_PORT)) 19 | , m_broadcast(m_context) 20 | { 21 | try 22 | { 23 | // TODO: What are the best values for send and receive buffer sizes? 24 | constexpr uint32_t SEND_BUFFER_SIZE = 16 * 1024 * 1024; 25 | constexpr uint32_t RECEIVE_BUFFER_SIZE = 32 * 1024 * 1024; 26 | m_dataSocket.set_option(asio::socket_base::send_buffer_size(SEND_BUFFER_SIZE)); 27 | m_dataSocket.set_option(asio::socket_base::receive_buffer_size(RECEIVE_BUFFER_SIZE)); 28 | } 29 | catch (std::exception& e) 30 | { 31 | iox::p3com::LogError() << "[UDPTransport] " << e.what(); 32 | setFailed(); 33 | return; 34 | } 35 | 36 | m_thread = std::thread([this]() { 37 | try 38 | { 39 | m_work.emplace(m_context); 40 | m_context.run(); 41 | 42 | iox::p3com::LogInfo() << "[UDPTransport] Worker thread has exited"; 43 | } 44 | catch (std::exception& e) 45 | { 46 | iox::p3com::LogError() << "[UDPTransport] " << e.what(); 47 | setFailed(); 48 | return; 49 | } 50 | }); 51 | 52 | dataAsyncReceive(); 53 | } 54 | 55 | iox::p3com::udp::UDPTransport::~UDPTransport() 56 | { 57 | m_work.reset(); 58 | m_context.stop(); 59 | m_thread.join(); 60 | } 61 | 62 | void iox::p3com::udp::UDPTransport::dataSocketCallback(asio::error_code ec, size_t bytes) noexcept 63 | { 64 | if (ec) 65 | { 66 | iox::p3com::LogError() << "[UDPTransport] " << ec.message(); 67 | setFailed(); 68 | return; 69 | } 70 | iox::p3com::LogInfo() << "[UDPTransport] Received user data message from IP " 71 | << m_outputEndpoint.address().to_string(); 72 | const auto index = m_broadcast.getIndex(m_outputEndpoint.address()); 73 | if (index.has_value()) 74 | { 75 | if (m_userDataCallback) 76 | { 77 | m_userDataCallback(m_outputBuffer.data(), bytes, {iox::p3com::TransportType::UDP, *index}); 78 | } 79 | } 80 | else 81 | { 82 | iox::p3com::LogError() << "[UDPTransport] Received user data message from an unknown device! Discarding!"; 83 | } 84 | 85 | dataAsyncReceive(); 86 | } 87 | 88 | void iox::p3com::udp::UDPTransport::registerDiscoveryCallback(iox::p3com::remoteDiscoveryCallback_t callback) noexcept 89 | { 90 | m_broadcast.registerDiscoveryCallback(callback); 91 | } 92 | 93 | void iox::p3com::udp::UDPTransport::registerUserDataCallback(iox::p3com::userDataCallback_t callback) noexcept 94 | { 95 | m_userDataCallback = std::move(callback); 96 | } 97 | 98 | void iox::p3com::udp::UDPTransport::dataAsyncReceive() noexcept 99 | { 100 | try 101 | { 102 | m_dataSocket.async_receive_from( 103 | asio::buffer(m_outputBuffer), m_outputEndpoint, [this](asio::error_code ec, size_t bytes) { 104 | dataSocketCallback(ec, bytes); 105 | }); 106 | } 107 | catch (std::exception& e) 108 | { 109 | iox::p3com::LogError() << "[UDPTransport] " << e.what(); 110 | setFailed(); 111 | } 112 | } 113 | 114 | void iox::p3com::udp::UDPTransport::sendBroadcast(const void* data, size_t size) noexcept 115 | { 116 | m_broadcast.sendBroadcast(data, size); 117 | } 118 | 119 | bool iox::p3com::udp::UDPTransport::sendUserData( 120 | const void* data1, size_t size1, const void* data2, size_t size2, uint32_t deviceIndex) noexcept 121 | { 122 | auto endpoint = m_broadcast.getEndpoint(deviceIndex); 123 | endpoint.port(DATA_PORT); 124 | try 125 | { 126 | constexpr uint32_t BUFFER_COUNT = 2U; 127 | std::array buffers{asio::const_buffer{data1, size1}, 128 | asio::const_buffer{data2, size2}}; 129 | std::lock_guard lock(m_socketMutex); 130 | m_dataSocket.send_to(buffers, endpoint); 131 | 132 | iox::p3com::LogInfo() << "[UDPTransport] Sent user data message to IP " << endpoint.address().to_string() 133 | << " with index " << deviceIndex; 134 | } 135 | catch (std::exception& e) 136 | { 137 | iox::p3com::LogError() << "[UDPTransport] " << e.what(); 138 | setFailed(); 139 | } 140 | return false; 141 | } 142 | 143 | size_t iox::p3com::udp::UDPTransport::maxMessageSize() const noexcept 144 | { 145 | return MAX_DATAGRAM_SIZE; 146 | } 147 | 148 | iox::p3com::TransportType iox::p3com::udp::UDPTransport::getType() const noexcept 149 | { 150 | return iox::p3com::TransportType::UDP; 151 | } 152 | -------------------------------------------------------------------------------- /source/udp/udp_transport_broadcast.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2023 NXP 2 | 3 | #include "p3com/transport/udp/udp_transport_broadcast.hpp" 4 | #include "p3com/internal/log/logging.hpp" 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | iox::p3com::udp::UDPBroadcast::UDPBroadcast(asio::io_service& context) noexcept 13 | : m_discoverySocket(context, asio::ip::udp::endpoint(asio::ip::address_v4::any(), DISCOVERY_PORT)) 14 | , m_outputBuffer() 15 | { 16 | discoverBroadcastAddresses(); 17 | try 18 | { 19 | // This is taken from https://stackoverflow.com/questions/9310231/boostasio-udp-broadcasting 20 | m_discoverySocket.set_option(asio::ip::udp::socket::reuse_address(true)); 21 | m_discoverySocket.set_option(asio::socket_base::broadcast(true)); 22 | } 23 | catch (std::exception& e) 24 | { 25 | iox::p3com::LogError() << "[UDPBroadcast] " << e.what(); 26 | setFailed(); 27 | return; 28 | } 29 | discoveryAsyncReceive(); 30 | } 31 | 32 | void iox::p3com::udp::UDPBroadcast::discoverBroadcastAddresses() noexcept 33 | { 34 | struct ifaddrs* ifap; 35 | if (getifaddrs(&ifap) == 0) 36 | { 37 | uint32_t iface_n = 0; 38 | for (struct ifaddrs* iface = ifap; iface != nullptr && iface_n < MAX_NETWORK_IFACE_COUNT; 39 | iface = iface->ifa_next) 40 | { 41 | uint32_t ifaAddr = sockAddrToUint32(iface->ifa_addr); 42 | uint32_t maskAddr = sockAddrToUint32(iface->ifa_netmask); 43 | uint32_t dstAddr = sockAddrToUint32(iface->ifa_dstaddr); 44 | if (ifaAddr > 0) 45 | { 46 | auto ifaAddrStr = inetNtoA(ifaAddr); 47 | auto maskAddrStr = inetNtoA(maskAddr); 48 | auto dstAddrStr = inetNtoA(dstAddr); 49 | iox::p3com::LogInfo() << "[UDPBroadcast] Found interface:" 50 | << "name=[" << iface->ifa_name << "]" 51 | << "address=[" << ifaAddrStr << "]" 52 | << "netmask=[" << maskAddrStr << "]" 53 | << "broadcastAddr=[" << dstAddrStr << "]"; 54 | auto ifEp = asio::ip::udp::endpoint(asio::ip::address_v4(ifaAddr), DISCOVERY_PORT); 55 | auto bcEp = asio::ip::udp::endpoint(asio::ip::address_v4(dstAddr), DISCOVERY_PORT); 56 | if (!bcEp.address().is_loopback()) 57 | { 58 | m_interfaceEndpoints.push_back(ifEp); 59 | m_broadcastEndpoints.push_back(bcEp); 60 | iface_n++; 61 | } 62 | } 63 | } 64 | freeifaddrs(ifap); 65 | } 66 | } 67 | 68 | 69 | uint32_t iox::p3com::udp::UDPBroadcast::sockAddrToUint32(struct sockaddr* address) noexcept 70 | { 71 | if ((address != nullptr) && (address->sa_family == AF_INET)) 72 | { 73 | return ntohl((reinterpret_cast(address))->sin_addr.s_addr); 74 | } 75 | else 76 | { 77 | return 0; 78 | } 79 | } 80 | 81 | 82 | // convert a numeric IP address into its string representation 83 | std::string iox::p3com::udp::UDPBroadcast::inetNtoA(uint32_t addr) noexcept 84 | { 85 | return iox::cxx::convert::toString((addr >> 24) & 0xFF) + "." + iox::cxx::convert::toString((addr >> 16) & 0xFF) 86 | + "." + iox::cxx::convert::toString((addr >> 8) & 0xFF) + "." 87 | + iox::cxx::convert::toString((addr >> 0) & 0xFF); 88 | } 89 | 90 | void iox::p3com::udp::UDPBroadcast::discoverySocketCallback(asio::error_code ec, size_t bytes) noexcept 91 | { 92 | if (ec) 93 | { 94 | iox::p3com::LogError() << "[UDPBroadcast] " << ec.message(); 95 | setFailed(); 96 | return; 97 | } 98 | 99 | auto* local_it = std::find(m_interfaceEndpoints.begin(), m_interfaceEndpoints.end(), m_outputEndpoint); 100 | // We assume that the first received discovery message was actually from the 101 | // ego device. So, m_outputEndpoint has not to be amongst m_interfaceEndpoints => local endpoint is ignored 102 | if (local_it == m_interfaceEndpoints.end()) 103 | { 104 | // Find index of the endpoint. If iter is not registered, add iter. 105 | auto* iter = std::find(m_devices.begin(), m_devices.end(), m_outputEndpoint); 106 | if (iter == m_devices.end() && m_devices.size() < MAX_DEVICE_COUNT) 107 | { 108 | m_devices.push_back(m_outputEndpoint); 109 | iter = &m_devices.back(); 110 | } 111 | const auto device = static_cast(std::distance(m_devices.begin(), iter)); 112 | iox::p3com::LogDebug() << "[UDPBroadcast] Received discovery message from IP " 113 | << m_outputEndpoint.address().to_string() << " with index " << device; 114 | 115 | if (m_remoteDiscoveryCallback) 116 | { 117 | m_remoteDiscoveryCallback(m_outputBuffer.data(), bytes, {iox::p3com::TransportType::UDP, device}); 118 | } 119 | } 120 | else 121 | { 122 | iox::p3com::LogDebug() << "[UDPBroadcast] Received discovery message from myself: " 123 | << m_outputEndpoint.address().to_string() << " ignoring"; 124 | } 125 | discoveryAsyncReceive(); 126 | } 127 | 128 | void iox::p3com::udp::UDPBroadcast::registerDiscoveryCallback(iox::p3com::remoteDiscoveryCallback_t callback) noexcept 129 | { 130 | m_remoteDiscoveryCallback = std::move(callback); 131 | } 132 | 133 | void iox::p3com::udp::UDPBroadcast::discoveryAsyncReceive() noexcept 134 | { 135 | try 136 | { 137 | m_discoverySocket.async_receive_from( 138 | asio::buffer(m_outputBuffer), m_outputEndpoint, [this](asio::error_code ec, size_t bytes) { 139 | discoverySocketCallback(ec, bytes); 140 | }); 141 | } 142 | catch (std::exception& e) 143 | { 144 | iox::p3com::LogError() << "[UDPBroadcast] " << e.what(); 145 | setFailed(); 146 | } 147 | } 148 | 149 | void iox::p3com::udp::UDPBroadcast::sendBroadcast(const void* data, size_t size) noexcept 150 | { 151 | try 152 | { 153 | // std::lock_guard lock(m_socketMutex); 154 | for (auto&& m_broadcastEndpoint : m_broadcastEndpoints) 155 | { 156 | m_discoverySocket.send_to(asio::buffer(data, size), m_broadcastEndpoint); 157 | } 158 | 159 | iox::p3com::LogDebug() << "[UDPBroadcast] Broadcast discovery info"; 160 | } 161 | catch (std::exception& e) 162 | { 163 | iox::p3com::LogError() << "[UDPBroadcast] " << e.what(); 164 | setFailed(); 165 | } 166 | } 167 | 168 | uint64_t iox::p3com::udp::UDPBroadcast::discoveredEndpoints() const noexcept 169 | { 170 | return m_devices.size(); 171 | } 172 | 173 | asio::ip::udp::endpoint iox::p3com::udp::UDPBroadcast::getEndpoint(uint32_t deviceIndex) noexcept 174 | { 175 | if (deviceIndex >= discoveredEndpoints()) 176 | { 177 | iox::p3com::LogError() << "[UDPBroadcast] Invalid device index when sending user data"; 178 | setFailed(); 179 | return asio::ip::udp::endpoint(); 180 | } 181 | return m_devices[deviceIndex]; 182 | } 183 | 184 | iox::cxx::optional iox::p3com::udp::UDPBroadcast::getIndex(asio::ip::address address) const noexcept 185 | { 186 | // Find index of the endpoint. If iter is not registered, add iter. 187 | auto* iter = 188 | std::find_if(m_devices.begin(), m_devices.end(), [&address](auto& dev) { return dev.address() == address; }); 189 | if (iter != m_devices.end()) 190 | { 191 | const auto device = static_cast(std::distance(m_devices.begin(), iter)); 192 | return {device}; 193 | } 194 | else 195 | { 196 | return iox::cxx::nullopt; 197 | } 198 | } 199 | --------------------------------------------------------------------------------