diff --git a/.clang-tidy b/.clang-tidy index edc9255..16270e3 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,28 +1,46 @@ --- -Checks: 'bugprone-*, +Checks: '*, + -altera-struct-pack-align, + -altera-unroll-loops, + -android-cloexec-accept, + -android-cloexec-socket, -bugprone-easily-swappable-parameters, - clang-diagnostic-*, - clang-analyzer-*, - google-readability-*, - -google-readability-casting, - google-runtime-operator, - misc-*, - -misc-const-correctness, + -cert-err34-c, + -cert-err58-cpp, + -cert-msc30-c, + -cert-msc32-c, + -cert-msc50-cpp, + -cert-msc51-cpp, + -concurrency-mt-unsafe, + -cppcoreguidelines-avoid-c-arrays, + -cppcoreguidelines-avoid-do-while, + -cppcoreguidelines-avoid-magic-numbers, + -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-macro-usage, + -cppcoreguidelines-non-private-member-variables-in-classes, + -cppcoreguidelines-owning-memory, + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, + -cppcoreguidelines-pro-bounds-constant-array-index, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -cppcoreguidelines-pro-type-vararg, + -cppcoreguidelines-pro-type-reinterpret-cast, + -fuchsia-default-arguments-calls, + -fuchsia-default-arguments-declarations, + -fuchsia-statically-constructed-objects, + -google-build-using-namespace, + -google-runtime-int, + -hicpp-avoid-c-arrays, + -hicpp-no-array-decay, + -hicpp-vararg, + -hicpp-signed-bitwise, + -llvmlibc-callee-namespace, + -llvmlibc-implementation-in-namespace, + -llvmlibc-restrict-system-libc-headers, -misc-non-private-member-variables-in-classes, - -misc-no-recursion, - -misc-use-anonymous-namespace, - modernize-*, - -modernize-avoid-c-arrays, - -modernize-pass-by-value, - -modernize-use-nodiscard, -modernize-use-trailing-return-type, - performance-*, - portability-*, - readability-*, -readability-function-cognitive-complexity, - -readability-redundant-access-specifiers, - -readability-magic-numbers, - -readability-identifier-length' + -readability-identifier-length, + -readability-magic-numbers' CheckOptions: - { key: readability-identifier-naming.ClassCase, value: CamelCase } diff --git a/.gitmodules b/.gitmodules index ffc5164..922463b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,6 +7,3 @@ [submodule "third_party/fmt"] path = third_party/fmt url = https://github.com/fmtlib/fmt.git -[submodule "third_party/asio"] - path = third_party/asio - url = https://github.com/chriskohlhoff/asio.git diff --git a/benchmark/BenchmarkBusBuffer.cpp b/benchmark/BenchmarkBusBuffer.cpp index 04bd0e8..ac28f55 100644 --- a/benchmark/BenchmarkBusBuffer.cpp +++ b/benchmark/BenchmarkBusBuffer.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include "BusBuffer.h" @@ -42,8 +41,8 @@ void ReceiveMessages(size_t count, BusBuffer& receiverBusBuffer, Channel& channe template void RunTest(benchmark::State& state, ConnectionKind connectionKind, - std::string_view senderName, - std::string_view receiverName, + const std::string& senderName, + const std::string& receiverName, Channel& senderChannel, Channel& receiverChannel) { using TController = std::tuple_element_t<0, TypeParam>; diff --git a/benchmark/BenchmarkIoBuffer.cpp b/benchmark/BenchmarkIoBuffer.cpp index 274c171..7eb3f59 100644 --- a/benchmark/BenchmarkIoBuffer.cpp +++ b/benchmark/BenchmarkIoBuffer.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include "CoSimTypes.h" @@ -37,8 +36,8 @@ void Receive(const IoSignal& signal, IoBuffer& readerIoBuffer, Channel& channel, void RunTest(benchmark::State& state, ConnectionKind connectionKind, - std::string_view writerName, - std::string_view readerName, + const std::string& writerName, + const std::string& readerName, Channel& senderChannel, Channel& receiverChannel) { IoSignal signal = CreateSignal(DsVeosCoSim_DataType_Int8, DsVeosCoSim_SizeKind_Fixed); diff --git a/benchmark/OsAbstraction/BenchmarkNamedEvent.cpp b/benchmark/OsAbstraction/BenchmarkNamedEvent.cpp index 72f3bd5..f392f1d 100644 --- a/benchmark/OsAbstraction/BenchmarkNamedEvent.cpp +++ b/benchmark/OsAbstraction/BenchmarkNamedEvent.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include "Generator.h" @@ -37,7 +36,7 @@ void EventSetAndWait(benchmark::State& state) { bool stopThread; -void WaitAndSet(std::string_view eventName1, std::string_view eventName2) { +void WaitAndSet(const std::string& eventName1, const std::string& eventName2) { NamedEvent event1 = NamedEvent::CreateOrOpen(eventName1); NamedEvent event2 = NamedEvent::CreateOrOpen(eventName2); diff --git a/benchmark/OsAbstraction/BenchmarkSocket.cpp b/benchmark/OsAbstraction/BenchmarkSocket.cpp index 3a0df69..2958800 100644 --- a/benchmark/OsAbstraction/BenchmarkSocket.cpp +++ b/benchmark/OsAbstraction/BenchmarkSocket.cpp @@ -1,6 +1,7 @@ // Copyright dSPACE GmbH. All rights reserved. #include +#include #include #include diff --git a/compile_flags.txt b/compile_flags.txt index 0a0ce8e..787f8cd 100644 --- a/compile_flags.txt +++ b/compile_flags.txt @@ -3,6 +3,7 @@ -DDSVEOSCOSIM_EXPORT -DWIN32_LEAN_AND_MEAN -D_CRT_SECURE_NO_WARNINGS +-DDSVEOSCOSIM_ENABLE_TRACING -DEXCEPTION_TESTS -Wall -Wextra @@ -17,8 +18,6 @@ -Itest -Itest/Helpers -isystem -third_party/asio/asio/include --isystem third_party/benchmark/include -isystem third_party/fmt/include diff --git a/shared/BackgroundService.cpp b/shared/BackgroundService.cpp index 5b2b06e..ecc5d3e 100644 --- a/shared/BackgroundService.cpp +++ b/shared/BackgroundService.cpp @@ -2,6 +2,8 @@ #include "BackgroundService.h" +#include + using namespace DsVeosCoSim; BackgroundService::BackgroundService(CoSimServer& coSimServer) : _coSimServer(coSimServer) { @@ -18,5 +20,9 @@ BackgroundService::BackgroundService(CoSimServer& coSimServer) : _coSimServer(co BackgroundService::~BackgroundService() noexcept { _stopEvent.Set(); - _thread.join(); + if (std::this_thread::get_id() == _thread.get_id()) { + _thread.detach(); + } else { + _thread.join(); + } } diff --git a/shared/ClientServerTestHelper.cpp b/shared/ClientServerTestHelper.cpp index c743844..6f1b13b 100644 --- a/shared/ClientServerTestHelper.cpp +++ b/shared/ClientServerTestHelper.cpp @@ -3,6 +3,7 @@ #include "ClientServerTestHelper.h" #include +#include #include "BusBuffer.h" #include "CoSimHelper.h" @@ -43,23 +44,23 @@ void SwitchSendingLinMessages() { PrintStatus(g_sendLinMessages, "LIN messages"); } -bool IsSendingIoSignalsEnabled() { +[[nodiscard]] bool IsSendingIoSignalsEnabled() { return g_sendIoData; } -bool IsSendingCanMessagesEnabled() { +[[nodiscard]] bool IsSendingCanMessagesEnabled() { return g_sendCanMessages; } -bool IsSendingEthMessagesEnabled() { +[[nodiscard]] bool IsSendingEthMessagesEnabled() { return g_sendEthMessages; } -bool IsSendingLinMessagesEnabled() { +[[nodiscard]] bool IsSendingLinMessagesEnabled() { return g_sendLinMessages; } -bool SendSomeData(DsVeosCoSim_SimulationTime simulationTime, const RunTimeInfo& runTimeInfo) { +[[nodiscard]] bool SendSomeData(DsVeosCoSim_SimulationTime simulationTime, const RunTimeInfo& runTimeInfo) { static int64_t lastHalfSecond = -1; static int64_t counter = 0; const int64_t currentHalfSecond = simulationTime / 500000000; diff --git a/shared/ClientServerTestHelper.h b/shared/ClientServerTestHelper.h index 78dd898..e769156 100644 --- a/shared/ClientServerTestHelper.h +++ b/shared/ClientServerTestHelper.h @@ -24,9 +24,9 @@ void SwitchSendingCanMessages(); void SwitchSendingEthMessages(); void SwitchSendingLinMessages(); -bool IsSendingIoSignalsEnabled(); -bool IsSendingCanMessagesEnabled(); -bool IsSendingEthMessagesEnabled(); -bool IsSendingLinMessagesEnabled(); +[[nodiscard]] bool IsSendingIoSignalsEnabled(); +[[nodiscard]] bool IsSendingCanMessagesEnabled(); +[[nodiscard]] bool IsSendingEthMessagesEnabled(); +[[nodiscard]] bool IsSendingLinMessagesEnabled(); [[nodiscard]] bool SendSomeData(DsVeosCoSim_SimulationTime simulationTime, const RunTimeInfo& runTimeInfo); \ No newline at end of file diff --git a/shared/Generator.cpp b/shared/Generator.cpp index da10d9b..934d7fe 100644 --- a/shared/Generator.cpp +++ b/shared/Generator.cpp @@ -3,19 +3,21 @@ #include "Generator.h" #include +#include +#include using namespace DsVeosCoSim; -int32_t Random(int32_t min, int32_t max) { +[[nodiscard]] int32_t Random(int32_t min, int32_t max) { static bool first = true; if (first) { - srand(42); // NOLINT(cert-msc51-cpp) + srand(42); first = false; } const int32_t diff = max + 1 - min; - return min + rand() % diff; // NOLINT(concurrency-mt-unsafe) + return min + rand() % diff; } void FillWithRandom(uint8_t* data, size_t length) { @@ -24,47 +26,47 @@ void FillWithRandom(uint8_t* data, size_t length) { } } -uint8_t GenerateU8() { +[[nodiscard]] uint8_t GenerateU8() { return GenerateRandom(static_cast(0U), static_cast(UINT8_MAX)); } -uint16_t GenerateU16() { +[[nodiscard]] uint16_t GenerateU16() { return GenerateRandom(static_cast(0U), static_cast(UINT16_MAX)); } -uint32_t GenerateU32() { +[[nodiscard]] uint32_t GenerateU32() { return GenerateRandom(0U, 123456789U); } -uint64_t GenerateU64() { +[[nodiscard]] uint64_t GenerateU64() { return (static_cast(GenerateU32()) << sizeof(uint32_t)) + static_cast(GenerateU32()); } -int64_t GenerateI64() { +[[nodiscard]] int64_t GenerateI64() { return static_cast(GenerateU64()); } -std::string GenerateString(std::string_view prefix) { +[[nodiscard]] std::string GenerateString(std::string_view prefix) { return fmt::format("{}{}", prefix, GenerateU32()); } -DsVeosCoSim_DataType GenerateDataType() { +[[nodiscard]] DsVeosCoSim_DataType GenerateDataType() { return GenerateRandom(DsVeosCoSim_DataType_Bool, DsVeosCoSim_DataType_Float64); } -DsVeosCoSim_SizeKind GenerateSizeKind() { +[[nodiscard]] DsVeosCoSim_SizeKind GenerateSizeKind() { return GenerateRandom(DsVeosCoSim_SizeKind_Fixed, DsVeosCoSim_SizeKind_Variable); } -IoSignal CreateSignal() { +[[nodiscard]] IoSignal CreateSignal() { return CreateSignal(GenerateDataType(), GenerateSizeKind()); } -IoSignal CreateSignal(DsVeosCoSim_DataType dataType) { +[[nodiscard]] IoSignal CreateSignal(DsVeosCoSim_DataType dataType) { return CreateSignal(dataType, GenerateSizeKind()); } -IoSignal CreateSignal(DsVeosCoSim_DataType dataType, DsVeosCoSim_SizeKind sizeKind) { +[[nodiscard]] IoSignal CreateSignal(DsVeosCoSim_DataType dataType, DsVeosCoSim_SizeKind sizeKind) { IoSignal signal{}; signal.id = GenerateU32(); signal.length = GenerateRandom(1U, 10U); @@ -74,13 +76,13 @@ IoSignal CreateSignal(DsVeosCoSim_DataType dataType, DsVeosCoSim_SizeKind sizeKi return signal; } -std::vector GenerateIoData(const DsVeosCoSim_IoSignal& signal) { +[[nodiscard]] std::vector GenerateIoData(const DsVeosCoSim_IoSignal& signal) { std::vector data = CreateZeroedIoData(signal); FillWithRandom(data.data(), data.size()); return data; } -std::vector CreateZeroedIoData(const DsVeosCoSim_IoSignal& signal) { +[[nodiscard]] std::vector CreateZeroedIoData(const DsVeosCoSim_IoSignal& signal) { std::vector data; data.resize(GetDataTypeSize(signal.dataType) * signal.length); return data; @@ -142,7 +144,7 @@ void FillWithRandom(LinMessage& message, DsVeosCoSim_BusControllerId controllerI FillWithRandom(message.data.data(), length); } -std::vector CreateSignals(size_t count) { +[[nodiscard]] std::vector CreateSignals(size_t count) { std::vector signals; for (size_t i = 0; i < count; i++) { @@ -152,7 +154,7 @@ std::vector CreateSignals(size_t count) { return signals; } -std::vector CreateCanControllers(size_t count) { +[[nodiscard]] std::vector CreateCanControllers(size_t count) { std::vector controllers; for (size_t i = 0; i < count; i++) { @@ -164,7 +166,7 @@ std::vector CreateCanControllers(size_t count) { return controllers; } -std::vector CreateEthControllers(size_t count) { +[[nodiscard]] std::vector CreateEthControllers(size_t count) { std::vector controllers; for (size_t i = 0; i < count; i++) { @@ -176,7 +178,7 @@ std::vector CreateEthControllers(size_t count) { return controllers; } -std::vector CreateLinControllers(size_t count) { +[[nodiscard]] std::vector CreateLinControllers(size_t count) { std::vector controllers; for (size_t i = 0; i < count; i++) { diff --git a/shared/Helper.cpp b/shared/Helper.cpp index a5533b2..179b07c 100644 --- a/shared/Helper.cpp +++ b/shared/Helper.cpp @@ -3,6 +3,8 @@ #include "Helper.h" #include +#include +#include #include "CoSimHelper.h" #include "LogHelper.h" @@ -13,17 +15,16 @@ #include #include #else +#include #include #include -#include - #endif using namespace DsVeosCoSim; namespace { -uint16_t GetNextFreeDynamicPort() { +[[nodiscard]] uint16_t GetNextFreeDynamicPort() { Socket socket(AddressFamily::Ipv4); socket.Bind(0, false); return socket.GetLocalPort(); @@ -31,7 +32,7 @@ uint16_t GetNextFreeDynamicPort() { } // namespace -bool StartUp() { +[[nodiscard]] bool StartUp() { InitializeOutput(); try { @@ -57,11 +58,11 @@ bool StartUp() { return true; } -int32_t GetChar() { +[[nodiscard]] int32_t GetChar() { #ifdef _WIN32 return _getch(); #else - termios oldt; + termios oldt{}; tcgetattr(STDIN_FILENO, &oldt); termios newt = oldt; @@ -69,15 +70,15 @@ int32_t GetChar() { tcsetattr(STDIN_FILENO, TCSANOW, &newt); - int32_t ch = getchar(); + int32_t character = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); - return ch; + return character; #endif } -Socket ConnectSocket(std::string_view ipAddress, uint16_t remotePort) { +[[nodiscard]] Socket ConnectSocket(std::string_view ipAddress, uint16_t remotePort) { std::optional connectedSocket = Socket::TryConnect(ipAddress, remotePort, 0, DefaultTimeout); if (connectedSocket) { return std::move(*connectedSocket); @@ -86,7 +87,7 @@ Socket ConnectSocket(std::string_view ipAddress, uint16_t remotePort) { throw std::runtime_error("Could not connect within timeout."); } -Socket ConnectSocket(std::string_view name) { +[[nodiscard]] Socket ConnectSocket(const std::string& name) { Socket socket(AddressFamily::Uds); if (socket.TryConnect(name)) { return socket; @@ -95,7 +96,7 @@ Socket ConnectSocket(std::string_view name) { throw std::runtime_error("Could not connect."); } -Socket Accept(const Socket& serverSocket) { +[[nodiscard]] Socket Accept(const Socket& serverSocket) { std::optional acceptedSocket = serverSocket.TryAccept(DefaultTimeout); if (acceptedSocket) { return std::move(*acceptedSocket); @@ -104,7 +105,7 @@ Socket Accept(const Socket& serverSocket) { throw std::runtime_error("Could not accept within timeout."); } -SocketChannel ConnectToTcpChannel(std::string_view ipAddress, uint16_t remotePort) { +[[nodiscard]] SocketChannel ConnectToTcpChannel(std::string_view ipAddress, uint16_t remotePort) { std::optional channel = TryConnectToTcpChannel(ipAddress, remotePort, 0, DefaultTimeout); if (channel) { return std::move(*channel); @@ -113,7 +114,7 @@ SocketChannel ConnectToTcpChannel(std::string_view ipAddress, uint16_t remotePor throw std::runtime_error("Could not connect within timeout."); } -SocketChannel Accept(const TcpChannelServer& server) { +[[nodiscard]] SocketChannel Accept(const TcpChannelServer& server) { std::optional acceptedChannel = server.TryAccept(DefaultTimeout); if (acceptedChannel) { return std::move(*acceptedChannel); @@ -122,7 +123,7 @@ SocketChannel Accept(const TcpChannelServer& server) { throw std::runtime_error("Could not accept within timeout."); } -SocketChannel ConnectToUdsChannel(std::string_view name) { +[[nodiscard]] SocketChannel ConnectToUdsChannel(const std::string& name) { std::optional channel = TryConnectToUdsChannel(name); if (channel) { return std::move(*channel); @@ -131,7 +132,7 @@ SocketChannel ConnectToUdsChannel(std::string_view name) { throw std::runtime_error("Could not connect."); } -SocketChannel Accept(const UdsChannelServer& server) { +[[nodiscard]] SocketChannel Accept(const UdsChannelServer& server) { std::optional acceptedChannel = server.TryAccept(DefaultTimeout); if (acceptedChannel) { return std::move(*acceptedChannel); @@ -142,7 +143,7 @@ SocketChannel Accept(const UdsChannelServer& server) { #ifdef _WIN32 -LocalChannel ConnectToLocalChannel(std::string_view name) { +[[nodiscard]] LocalChannel ConnectToLocalChannel(const std::string& name) { std::optional channel = TryConnectToLocalChannel(name); if (channel) { return std::move(*channel); @@ -151,7 +152,7 @@ LocalChannel ConnectToLocalChannel(std::string_view name) { throw std::runtime_error("Could not connect."); } -LocalChannel Accept(LocalChannelServer& server) { +[[nodiscard]] LocalChannel Accept(LocalChannelServer& server) { std::optional acceptedChannel = server.TryAccept(); if (acceptedChannel) { return std::move(*acceptedChannel); @@ -170,7 +171,7 @@ LocalChannel Accept(LocalChannelServer& server) { return "::1"; } -bool SendComplete(const Socket& socket, const void* buffer, size_t length) { +[[nodiscard]] bool SendComplete(const Socket& socket, const void* buffer, size_t length) { const auto* bufferPointer = static_cast(buffer); while (length > 0) { int32_t sentSize{}; @@ -183,7 +184,7 @@ bool SendComplete(const Socket& socket, const void* buffer, size_t length) { return true; } -bool ReceiveComplete(const Socket& socket, void* buffer, size_t length) { +[[nodiscard]] bool ReceiveComplete(const Socket& socket, void* buffer, size_t length) { auto* bufferPointer = static_cast(buffer); while (length > 0) { int32_t receivedSize{}; diff --git a/shared/Helper.h b/shared/Helper.h index 87808ea..7975745 100644 --- a/shared/Helper.h +++ b/shared/Helper.h @@ -3,7 +3,9 @@ #pragma once #include -#include // IWYU pragma: keep, NOLINT +#include // IWYU pragma: keep +#include +#include #include "Communication/SocketChannel.h" #include "OsAbstraction/Socket.h" @@ -32,18 +34,18 @@ constexpr uint32_t DefaultTimeout = 1000; // NOLINT [[nodiscard]] bool StartUp(); [[nodiscard]] DsVeosCoSim::Socket ConnectSocket(std::string_view ipAddress, uint16_t remotePort); -[[nodiscard]] DsVeosCoSim::Socket ConnectSocket(std::string_view name); +[[nodiscard]] DsVeosCoSim::Socket ConnectSocket(const std::string& name); [[nodiscard]] DsVeosCoSim::Socket Accept(const DsVeosCoSim::Socket& serverSocket); [[nodiscard]] DsVeosCoSim::SocketChannel ConnectToTcpChannel(std::string_view ipAddress, uint16_t remotePort); [[nodiscard]] DsVeosCoSim::SocketChannel Accept(const DsVeosCoSim::TcpChannelServer& server); -[[nodiscard]] DsVeosCoSim::SocketChannel ConnectToUdsChannel(std::string_view name); +[[nodiscard]] DsVeosCoSim::SocketChannel ConnectToUdsChannel(const std::string& name); [[nodiscard]] DsVeosCoSim::SocketChannel Accept(const DsVeosCoSim::UdsChannelServer& server); #ifdef _WIN32 -[[nodiscard]] DsVeosCoSim::LocalChannel ConnectToLocalChannel(std::string_view name); +[[nodiscard]] DsVeosCoSim::LocalChannel ConnectToLocalChannel(const std::string& name); [[nodiscard]] DsVeosCoSim::LocalChannel Accept(DsVeosCoSim::LocalChannelServer& server); #endif diff --git a/shared/LogHelper.cpp b/shared/LogHelper.cpp index e3a48ae..12295a8 100644 --- a/shared/LogHelper.cpp +++ b/shared/LogHelper.cpp @@ -3,8 +3,8 @@ #include "LogHelper.h" #include -#include #include +#include #include "CoSimHelper.h" @@ -27,19 +27,6 @@ fmt::text_style gray = fg(fmt::color::light_gray); fmt::text_style blue = fg(fmt::color::dodger_blue); fmt::text_style violet = fg(fmt::color::fuchsia); -[[nodiscard]] std::string DataToString(const uint8_t* data, uint32_t dataLength, char separator = 0) { - std::ostringstream oss; - oss << std::hex << std::setfill('0'); - for (uint32_t i = 0; i < dataLength; i++) { - oss << std::setw(2) << static_cast(data[i]); - if ((i < dataLength - 1) && separator != 0) { - oss << separator; - } - } - - return oss.str(); -} - [[nodiscard]] std::string DataTypeValueToString(const void* value, uint32_t index, DsVeosCoSim_DataType dataType) { switch (dataType) { case DsVeosCoSim_DataType_Bool: @@ -239,6 +226,6 @@ void ClearLastMessage() { g_lastMessage = ""; } -std::string GetLastMessage() { +[[nodiscard]] std::string GetLastMessage() { return g_lastMessage; } diff --git a/shared/OsAbstractionTestHelper.cpp b/shared/OsAbstractionTestHelper.cpp index 6b49927..a770839 100644 --- a/shared/OsAbstractionTestHelper.cpp +++ b/shared/OsAbstractionTestHelper.cpp @@ -3,6 +3,8 @@ #include "OsAbstractionTestHelper.h" #include +#include +#include #ifdef _WIN32 #include @@ -99,7 +101,7 @@ void UdpSocket::Listen() const { } } -bool UdpSocket::SendTo(const void* source, uint32_t size, const InternetAddress& address) const { +[[nodiscard]] bool UdpSocket::SendTo(const void* source, uint32_t size, const InternetAddress& address) const { const auto* const sourcePointer = static_cast(source); static auto addressLength = static_cast(sizeof(sockaddr_in)); const auto length = static_cast(sendto(_socket, @@ -111,7 +113,7 @@ bool UdpSocket::SendTo(const void* source, uint32_t size, const InternetAddress& return length == static_cast(size); } -bool UdpSocket::ReceiveFrom(void* destination, uint32_t size, InternetAddress& address) const { +[[nodiscard]] bool UdpSocket::ReceiveFrom(void* destination, uint32_t size, InternetAddress& address) const { auto* const destinationPointer = static_cast(destination); static auto addressLength = static_cast(sizeof(sockaddr_in)); const auto length = static_cast(recvfrom(_socket, @@ -128,10 +130,10 @@ constexpr uint32_t PipeBufferSize = 1024 * 16; #endif #ifndef _WIN32 -Pipe::pipe_t Pipe::CreatePipe(std::string_view name) { +[[nodiscard]] Pipe::pipe_t Pipe::CreatePipe(std::string_view name) { mkfifo(name.data(), 0666); - pipe_t pipe = open(name.data(), O_RDWR); + pipe_t pipe = open(name.data(), O_RDWR | O_CLOEXEC); if (pipe < 0) { throw std::runtime_error("Could not open pipe."); } @@ -140,12 +142,12 @@ Pipe::pipe_t Pipe::CreatePipe(std::string_view name) { } #endif -Pipe::Pipe(std::string_view name) { +Pipe::Pipe(const std::string& name) { #ifdef _WIN32 - _name = std::string(R"(\\.\pipe\)") + std::string(name); + _name = R"(\\.\pipe\)" + name; #else - _pipe1 = CreatePipe(std::string("/tmp/Pipe1") + std::string(name)); - _pipe2 = CreatePipe(std::string("/tmp/Pipe2") + std::string(name)); + _pipe1 = CreatePipe("/tmp/Pipe1" + name); + _pipe2 = CreatePipe("/tmp/Pipe2" + name); #endif } @@ -211,24 +213,24 @@ void Pipe::Connect() { #endif } -bool Pipe::Write(const void* source, uint32_t size) const { +[[nodiscard]] bool Pipe::Write(const void* source, uint32_t size) const { #ifdef _WIN32 DWORD processedSize = 0; BOOL success = ::WriteFile(_pipe, source, size, &processedSize, nullptr); return (success != 0) && (size == processedSize); #else ssize_t length = write(_writePipe, source, size); - return length == (ssize_t)size; + return length == static_cast(size); #endif } -bool Pipe::Read(void* destination, uint32_t size) const { +[[nodiscard]] bool Pipe::Read(void* destination, uint32_t size) const { #ifdef _WIN32 DWORD processedSize = 0; BOOL success = ReadFile(_pipe, destination, size, &processedSize, nullptr); return (success != 0) && (size == processedSize); #else ssize_t length = read(_readPipe, destination, size); - return length == (ssize_t)size; + return length == static_cast(size); #endif } diff --git a/shared/OsAbstractionTestHelper.h b/shared/OsAbstractionTestHelper.h index fd29917..1cf8d3d 100644 --- a/shared/OsAbstractionTestHelper.h +++ b/shared/OsAbstractionTestHelper.h @@ -4,6 +4,7 @@ #include #include +#include class InternetAddress final { public: @@ -37,8 +38,8 @@ class UdpSocket final { void SetReuseAddress(bool value) const; void Listen() const; - bool SendTo(const void* source, uint32_t size, const InternetAddress& address) const; - bool ReceiveFrom(void* destination, uint32_t size, InternetAddress& address) const; + [[nodiscard]] bool SendTo(const void* source, uint32_t size, const InternetAddress& address) const; + [[nodiscard]] bool ReceiveFrom(void* destination, uint32_t size, InternetAddress& address) const; private: #ifdef _WIN32 @@ -55,7 +56,7 @@ class UdpSocket final { class Pipe final { public: - explicit Pipe(std::string_view name); + explicit Pipe(const std::string& name); ~Pipe(); Pipe(const Pipe&) = delete; @@ -67,8 +68,8 @@ class Pipe final { void Accept(); void Connect(); - bool Write(const void* source, uint32_t size) const; - bool Read(void* destination, uint32_t size) const; + [[nodiscard]] bool Write(const void* source, uint32_t size) const; + [[nodiscard]] bool Read(void* destination, uint32_t size) const; private: #ifdef _WIN32 @@ -78,7 +79,7 @@ class Pipe final { #endif #ifndef _WIN32 - static pipe_t CreatePipe(std::string_view name); + [[nodiscard]] static pipe_t CreatePipe(std::string_view name); #endif #ifdef _WIN32 diff --git a/shared/PerformanceTestHelper.h b/shared/PerformanceTestHelper.h index 978d37e..9a56232 100644 --- a/shared/PerformanceTestHelper.h +++ b/shared/PerformanceTestHelper.h @@ -3,19 +3,17 @@ #pragma once #include -#include +#include -constexpr uint32_t BufferSize = 24U; // NOLINT -constexpr uint16_t UdpPort = 27100; // NOLINT -constexpr uint16_t TcpPort = 27101; // NOLINT -constexpr uint16_t CommunicationPort = 27102; // NOLINT -constexpr uint16_t CoSimPort = 27103; // NOLINT -constexpr uint16_t AsioAsyncPort = 27111; // NOLINT -constexpr uint16_t AsioBlockingPort = 27112; // NOLINT -constexpr std::string_view UdsName = "Uds4711"; // NOLINT -constexpr std::string_view PipeName = "Pipe4711"; // NOLINT -constexpr std::string_view BeginEventName = "BeginEvent4711"; // NOLINT -constexpr std::string_view EndEventName = "EndEvent4711"; // NOLINT -constexpr std::string_view ShmName = "Shm4711"; // NOLINT -constexpr std::string_view LocalName = "Local4711"; // NOLINT -constexpr std::string_view CoSimServerName = "TestServer"; // NOLINT +constexpr uint32_t BufferSize = 24U; // NOLINT +constexpr uint16_t UdpPort = 27100; // NOLINT +constexpr uint16_t TcpPort = 27101; // NOLINT +constexpr uint16_t CommunicationPort = 27102; // NOLINT +constexpr uint16_t CoSimPort = 27103; // NOLINT +const std::string UdsName = "Uds4711"; // NOLINT +const std::string PipeName = "Pipe4711"; // NOLINT +const std::string BeginEventName = "BeginEvent4711"; // NOLINT +const std::string EndEventName = "EndEvent4711"; // NOLINT +const std::string ShmName = "Shm4711"; // NOLINT +const std::string LocalName = "Local4711"; // NOLINT +const std::string CoSimServerName = "TestServer"; // NOLINT diff --git a/src/BusBuffer.cpp b/src/BusBuffer.cpp index 063b4eb..2899b5e 100644 --- a/src/BusBuffer.cpp +++ b/src/BusBuffer.cpp @@ -2,6 +2,8 @@ #include "BusBuffer.h" +#include + namespace DsVeosCoSim { namespace { @@ -18,7 +20,7 @@ using RemoteLinBuffer = RemoteBusProtocolBuffer& canControllers, const std::vector& ethControllers, const std::vector& linControllers) { @@ -201,31 +203,31 @@ BusBuffer::BusBuffer(CoSimType coSimType, std::string suffixForTransmit = coSimType == CoSimType::Client ? "Transmit" : "Receive"; std::string suffixForReceive = coSimType == CoSimType::Client ? "Receive" : "Transmit"; - _canTransmitBuffer->Initialize(coSimType, std::string(name) + ".Can." + suffixForTransmit, canControllers); - _ethTransmitBuffer->Initialize(coSimType, std::string(name) + ".Eth." + suffixForTransmit, ethControllers); - _linTransmitBuffer->Initialize(coSimType, std::string(name) + ".Lin." + suffixForTransmit, linControllers); - _canReceiveBuffer->Initialize(coSimType, std::string(name) + ".Can." + suffixForReceive, canControllers); - _ethReceiveBuffer->Initialize(coSimType, std::string(name) + ".Eth." + suffixForReceive, ethControllers); - _linReceiveBuffer->Initialize(coSimType, std::string(name) + ".Lin." + suffixForReceive, linControllers); + _canTransmitBuffer->Initialize(coSimType, name + ".Can." + suffixForTransmit, canControllers); + _ethTransmitBuffer->Initialize(coSimType, name + ".Eth." + suffixForTransmit, ethControllers); + _linTransmitBuffer->Initialize(coSimType, name + ".Lin." + suffixForTransmit, linControllers); + _canReceiveBuffer->Initialize(coSimType, name + ".Can." + suffixForReceive, canControllers); + _ethReceiveBuffer->Initialize(coSimType, name + ".Eth." + suffixForReceive, ethControllers); + _linReceiveBuffer->Initialize(coSimType, name + ".Lin." + suffixForReceive, linControllers); } BusBuffer::BusBuffer(CoSimType coSimType, ConnectionKind connectionKind, - std::string_view name, + const std::string& name, const std::vector& canControllers) : BusBuffer(coSimType, connectionKind, name, canControllers, {}, {}) { } BusBuffer::BusBuffer(CoSimType coSimType, ConnectionKind connectionKind, - std::string_view name, + const std::string& name, const std::vector& ethControllers) : BusBuffer(coSimType, connectionKind, name, {}, ethControllers, {}) { } BusBuffer::BusBuffer(CoSimType coSimType, ConnectionKind connectionKind, - std::string_view name, + const std::string& name, const std::vector& linControllers) : BusBuffer(coSimType, connectionKind, name, {}, {}, linControllers) { } @@ -240,40 +242,40 @@ void BusBuffer::ClearData() const { _linReceiveBuffer->ClearData(); } -bool BusBuffer::Transmit(const DsVeosCoSim_CanMessage& message) const { +[[nodiscard]] bool BusBuffer::Transmit(const DsVeosCoSim_CanMessage& message) const { return _canTransmitBuffer->Transmit(message); } -bool BusBuffer::Transmit(const DsVeosCoSim_EthMessage& message) const { +[[nodiscard]] bool BusBuffer::Transmit(const DsVeosCoSim_EthMessage& message) const { return _ethTransmitBuffer->Transmit(message); } -bool BusBuffer::Transmit(const DsVeosCoSim_LinMessage& message) const { +[[nodiscard]] bool BusBuffer::Transmit(const DsVeosCoSim_LinMessage& message) const { return _linTransmitBuffer->Transmit(message); } -bool BusBuffer::Receive(DsVeosCoSim_CanMessage& message) const { +[[nodiscard]] bool BusBuffer::Receive(DsVeosCoSim_CanMessage& message) const { return _canReceiveBuffer->Receive(message); } -bool BusBuffer::Receive(DsVeosCoSim_EthMessage& message) const { +[[nodiscard]] bool BusBuffer::Receive(DsVeosCoSim_EthMessage& message) const { return _ethReceiveBuffer->Receive(message); } -bool BusBuffer::Receive(DsVeosCoSim_LinMessage& message) const { +[[nodiscard]] bool BusBuffer::Receive(DsVeosCoSim_LinMessage& message) const { return _linReceiveBuffer->Receive(message); } -bool BusBuffer::Serialize(ChannelWriter& writer) const { +[[nodiscard]] bool BusBuffer::Serialize(ChannelWriter& writer) const { CheckResultWithMessage(_canTransmitBuffer->Serialize(writer), "Could not transmit CAN messages."); CheckResultWithMessage(_ethTransmitBuffer->Serialize(writer), "Could not transmit ETH messages."); CheckResultWithMessage(_linTransmitBuffer->Serialize(writer), "Could not transmit LIN messages."); return true; } -bool BusBuffer::Deserialize(ChannelReader& reader, - DsVeosCoSim_SimulationTime simulationTime, - const Callbacks& callbacks) const { +[[nodiscard]] bool BusBuffer::Deserialize(ChannelReader& reader, + DsVeosCoSim_SimulationTime simulationTime, + const Callbacks& callbacks) const { CheckResultWithMessage(_canReceiveBuffer->Deserialize(reader, simulationTime, callbacks.canMessageReceivedCallback), "Could not receive CAN messages."); CheckResultWithMessage(_ethReceiveBuffer->Deserialize(reader, simulationTime, callbacks.ethMessageReceivedCallback), diff --git a/src/BusBuffer.h b/src/BusBuffer.h index 6427545..bfc038e 100644 --- a/src/BusBuffer.h +++ b/src/BusBuffer.h @@ -6,7 +6,6 @@ #include #include #include -#include #include #include @@ -25,23 +24,24 @@ namespace DsVeosCoSim { template -concept ControllerExtern = requires(TControllerExtern e) { - { e.queueSize } -> std::same_as; - { e.name } -> std::same_as; +concept ControllerExtern = requires(TControllerExtern controllerExtern) { + { controllerExtern.queueSize } -> std::same_as; + { controllerExtern.name } -> std::same_as; }; template -concept MessageExtern = requires(TMessageExtern e) { - { e.controllerId } -> std::same_as; +concept MessageExtern = requires(TMessageExtern messageExtern) { + { messageExtern.controllerId } -> std::same_as; }; template -concept Message = requires(TMessage& m, TMessageExtern& e, ChannelWriter& writer, ChannelReader& reader) { - { std::as_const(m).SerializeTo(writer) }; - { m.DeserializeFrom(reader) }; - { std::as_const(m).WriteTo(e) }; - { m.ReadFrom(std::as_const(e)) }; -}; +concept Message = + requires(TMessage& message, TMessageExtern& messageExtern, ChannelWriter& writer, ChannelReader& reader) { + { std::as_const(message).SerializeTo(writer) }; + { message.DeserializeFrom(reader) }; + { std::as_const(message).WriteTo(messageExtern) }; + { message.ReadFrom(std::as_const(messageExtern)) }; + }; struct CanMessage { DsVeosCoSim_SimulationTime timestamp{}; @@ -127,7 +127,7 @@ class BusProtocolBufferBase { BusProtocolBufferBase(BusProtocolBufferBase&&) = delete; BusProtocolBufferBase& operator=(BusProtocolBufferBase&&) = delete; - void Initialize(CoSimType coSimType, std::string_view name, const std::vector& controllers) { + void Initialize(CoSimType coSimType, const std::string& name, const std::vector& controllers) { _coSimType = coSimType; size_t totalQueueItemsCountPerBuffer = 0; @@ -197,7 +197,7 @@ class BusProtocolBufferBase { } protected: - virtual void InitializeInternal(std::string_view name, size_t totalQueueItemsCountPerBuffer) = 0; + virtual void InitializeInternal(const std::string& name, size_t totalQueueItemsCountPerBuffer) = 0; virtual void ClearDataInternal() = 0; @@ -241,7 +241,7 @@ class RemoteBusProtocolBuffer final : public BusProtocolBufferBase_controllers.size()); _messageBuffer = RingBuffer(totalQueueItemsCountPerBuffer); } @@ -365,7 +365,7 @@ class LocalBusProtocolBuffer final : public BusProtocolBufferBase& canControllers, const std::vector& ethControllers, const std::vector& linControllers); BusBuffer(CoSimType coSimType, ConnectionKind connectionKind, - std::string_view name, + const std::string& name, const std::vector& canControllers); BusBuffer(CoSimType coSimType, ConnectionKind connectionKind, - std::string_view name, + const std::string& name, const std::vector& ethControllers); BusBuffer(CoSimType coSimType, ConnectionKind connectionKind, - std::string_view name, + const std::string& name, const std::vector& linControllers); ~BusBuffer() noexcept = default; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d5db1bd..58b0269 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -18,6 +18,7 @@ target_sources( Communication/LocalChannel.cpp Communication/SocketChannel.cpp Helpers/CoSimHelper.cpp + Helpers/Environment.cpp OsAbstraction/Handle.cpp OsAbstraction/NamedEvent.cpp OsAbstraction/NamedMutex.cpp diff --git a/src/CoSimClient.cpp b/src/CoSimClient.cpp index dfc741f..9dd9506 100644 --- a/src/CoSimClient.cpp +++ b/src/CoSimClient.cpp @@ -3,6 +3,7 @@ #include "CoSimClient.h" #include +#include #include "CoSimHelper.h" #include "CoSimTypes.h" @@ -23,7 +24,7 @@ constexpr uint32_t ClientTimeoutInMilliseconds = 1000; } // namespace -bool CoSimClient::Connect(const ConnectConfig& connectConfig) { +[[nodiscard]] bool CoSimClient::Connect(const ConnectConfig& connectConfig) { if (connectConfig.serverName.empty() && (connectConfig.remotePort == 0)) { throw CoSimException("Either ConnectConfig.serverName or ConnectConfig.remotePort must be set."); } @@ -62,7 +63,7 @@ void CoSimClient::Disconnect() { } } -DsVeosCoSim_ConnectionState CoSimClient::GetConnectionState() const { +[[nodiscard]] DsVeosCoSim_ConnectionState CoSimClient::GetConnectionState() const { if (_isConnected) { return DsVeosCoSim_ConnectionState_Connected; } @@ -165,7 +166,7 @@ void CoSimClient::SetCallbacks(const Callbacks& callbacks) { } } -bool CoSimClient::RunCallbackBasedCoSimulation(const Callbacks& callbacks) { +[[nodiscard]] bool CoSimClient::RunCallbackBasedCoSimulation(const Callbacks& callbacks) { EnsureIsConnected(); EnsureIsInResponderModeBlocking(); @@ -186,7 +187,9 @@ void CoSimClient::StartPollingBasedCoSimulation(const Callbacks& callbacks) { SetCallbacks(callbacks); } -bool CoSimClient::PollCommand(DsVeosCoSim_SimulationTime& simulationTime, Command& command, bool returnOnPing) { +[[nodiscard]] bool CoSimClient::PollCommand(DsVeosCoSim_SimulationTime& simulationTime, + Command& command, + bool returnOnPing) { EnsureIsConnected(); EnsureIsInResponderModeNonBlocking(); @@ -202,7 +205,7 @@ bool CoSimClient::PollCommand(DsVeosCoSim_SimulationTime& simulationTime, Comman return true; } -bool CoSimClient::FinishCommand() { +[[nodiscard]] bool CoSimClient::FinishCommand() { EnsureIsConnected(); EnsureIsInResponderModeNonBlocking(); @@ -246,7 +249,7 @@ void CoSimClient::Terminate(DsVeosCoSim_TerminateReason terminateReason) { case DsVeosCoSim_TerminateReason_Error: _nextCommand.exchange(Command::Terminate); break; - default: // NOLINT(clang-diagnostic-covered-switch-default) + default: throw CoSimException("Unknown terminate reason " + ToString(terminateReason) + "."); } } @@ -263,7 +266,7 @@ void CoSimClient::Continue() { _nextCommand.exchange(Command::Continue); } -DsVeosCoSim_SimulationTime CoSimClient::GetStepSize() const { +[[nodiscard]] DsVeosCoSim_SimulationTime CoSimClient::GetStepSize() const { EnsureIsConnected(); return _stepSize; @@ -285,13 +288,13 @@ void CoSimClient::GetOutgoingSignals(uint32_t* outgoingSignalsCount, *outgoingSignals = _outgoingSignalsExtern.data(); } -std::vector CoSimClient::GetIncomingSignals() const { +[[nodiscard]] std::vector CoSimClient::GetIncomingSignals() const { EnsureIsConnected(); return _incomingSignals; } -std::vector CoSimClient::GetOutgoingSignals() const { +[[nodiscard]] std::vector CoSimClient::GetOutgoingSignals() const { EnsureIsConnected(); return _outgoingSignals; @@ -336,55 +339,55 @@ void CoSimClient::GetLinControllers(uint32_t* controllersCount, const DsVeosCoSi *controllers = _linControllersExtern.data(); } -std::vector CoSimClient::GetCanControllers() const { +[[nodiscard]] std::vector CoSimClient::GetCanControllers() const { EnsureIsConnected(); return _canControllers; } -std::vector CoSimClient::GetEthControllers() const { +[[nodiscard]] std::vector CoSimClient::GetEthControllers() const { EnsureIsConnected(); return _ethControllers; } -std::vector CoSimClient::GetLinControllers() const { +[[nodiscard]] std::vector CoSimClient::GetLinControllers() const { EnsureIsConnected(); return _linControllers; } -bool CoSimClient::Transmit(const DsVeosCoSim_CanMessage& message) const { +[[nodiscard]] bool CoSimClient::Transmit(const DsVeosCoSim_CanMessage& message) const { EnsureIsConnected(); return _busBuffer->Transmit(message); } -bool CoSimClient::Transmit(const DsVeosCoSim_EthMessage& message) const { +[[nodiscard]] bool CoSimClient::Transmit(const DsVeosCoSim_EthMessage& message) const { EnsureIsConnected(); return _busBuffer->Transmit(message); } -bool CoSimClient::Transmit(const DsVeosCoSim_LinMessage& message) const { +[[nodiscard]] bool CoSimClient::Transmit(const DsVeosCoSim_LinMessage& message) const { EnsureIsConnected(); return _busBuffer->Transmit(message); } -bool CoSimClient::Receive(DsVeosCoSim_CanMessage& message) const { +[[nodiscard]] bool CoSimClient::Receive(DsVeosCoSim_CanMessage& message) const { EnsureIsConnected(); return _busBuffer->Receive(message); } -bool CoSimClient::Receive(DsVeosCoSim_EthMessage& message) const { +[[nodiscard]] bool CoSimClient::Receive(DsVeosCoSim_EthMessage& message) const { EnsureIsConnected(); return _busBuffer->Receive(message); } -bool CoSimClient::Receive(DsVeosCoSim_LinMessage& message) const { +[[nodiscard]] bool CoSimClient::Receive(DsVeosCoSim_LinMessage& message) const { EnsureIsConnected(); return _busBuffer->Receive(message); @@ -414,7 +417,7 @@ void CoSimClient::ResetDataFromPreviousConnect() { _linControllersExtern.clear(); } -bool CoSimClient::LocalConnect() { +[[nodiscard]] bool CoSimClient::LocalConnect() { #ifdef _WIN32 std::optional channel = TryConnectToLocalChannel(_serverName); if (!channel) { @@ -437,7 +440,7 @@ bool CoSimClient::LocalConnect() { return true; } -bool CoSimClient::RemoteConnect() { +[[nodiscard]] bool CoSimClient::RemoteConnect() { if (_remotePort == 0) { LogInfo("Obtaining TCP port of dSPACE VEOS CoSim server '" + _serverName + "' at " + _remoteIpAddress + " ..."); CheckResultWithMessage(PortMapper_GetPort(_remoteIpAddress, _serverName, _remotePort), @@ -462,14 +465,14 @@ bool CoSimClient::RemoteConnect() { return true; } -bool CoSimClient::SendConnectRequest() const { +[[nodiscard]] bool CoSimClient::SendConnectRequest() const { CheckResultWithMessage( Protocol::SendConnect(_channel->GetWriter(), CoSimProtocolVersion, {}, _serverName, _clientName), "Could not send connect frame."); return true; } -bool CoSimClient::OnConnectOk() { +[[nodiscard]] bool CoSimClient::OnConnectOk() { uint32_t serverProtocolVersion{}; Mode mode{}; SimulationState simulationState{}; @@ -522,35 +525,34 @@ bool CoSimClient::OnConnectOk() { return true; } -bool CoSimClient::OnConnectError() const { +[[nodiscard]] bool CoSimClient::OnConnectError() const { std::string errorString; CheckResultWithMessage(Protocol::ReadError(_channel->GetReader(), errorString), "Could not read error frame."); - throw CoSimException(errorString); + return false; } -bool CoSimClient::ReceiveConnectResponse() { +[[nodiscard]] bool CoSimClient::ReceiveConnectResponse() { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(_channel->GetReader(), frameKind)); - switch (frameKind) // NOLINT(clang-diagnostic-switch-enum) - { + switch (frameKind) { case FrameKind::ConnectOk: CheckResultWithMessage(OnConnectOk(), "Could not handle connect ok."); return true; case FrameKind::Error: CheckResultWithMessage(OnConnectError(), "Could not handle connect error."); - return true; + return false; default: throw CoSimException("Received unexpected frame " + ToString(frameKind) + "."); } } -bool CoSimClient::RunCallbackBasedCoSimulationInternal() { +[[nodiscard]] bool CoSimClient::RunCallbackBasedCoSimulationInternal() { while (_isConnected) { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(_channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::Step: { CheckResultWithMessage(OnStep(), "Could not handle step."); if (!_isConnected) { @@ -620,14 +622,16 @@ bool CoSimClient::RunCallbackBasedCoSimulationInternal() { return true; } -bool CoSimClient::PollCommandInternal(DsVeosCoSim_SimulationTime& simulationTime, Command& command, bool returnOnPing) { +[[nodiscard]] bool CoSimClient::PollCommandInternal(DsVeosCoSim_SimulationTime& simulationTime, + Command& command, + bool returnOnPing) { simulationTime = _currentSimulationTime; command = Command::Terminate; while (true) { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(_channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::Step: CheckResultWithMessage(OnStep(), "Could not handle step."); _currentCommand = Command::Step; @@ -674,8 +678,8 @@ bool CoSimClient::PollCommandInternal(DsVeosCoSim_SimulationTime& simulationTime return true; } -bool CoSimClient::FinishCommandInternal() { - switch (_currentCommand) { // NOLINT(clang-diagnostic-switch, clang-diagnostic-switch-enum) +[[nodiscard]] bool CoSimClient::FinishCommandInternal() { + switch (_currentCommand) { case Command::Start: case Command::Stop: case Command::Terminate: @@ -705,7 +709,7 @@ bool CoSimClient::FinishCommandInternal() { return true; } -bool CoSimClient::OnStep() { +[[nodiscard]] bool CoSimClient::OnStep() { CheckResultWithMessage( Protocol::ReadStep(_channel->GetReader(), _currentSimulationTime, *_ioBuffer, *_busBuffer, _callbacks), "Could not read step frame."); @@ -717,7 +721,7 @@ bool CoSimClient::OnStep() { return true; } -bool CoSimClient::OnStart() { +[[nodiscard]] bool CoSimClient::OnStart() { CheckResultWithMessage(Protocol::ReadStart(_channel->GetReader(), _currentSimulationTime), "Could not read start frame."); @@ -731,7 +735,7 @@ bool CoSimClient::OnStart() { return true; } -bool CoSimClient::OnStop() { +[[nodiscard]] bool CoSimClient::OnStop() { CheckResultWithMessage(Protocol::ReadStop(_channel->GetReader(), _currentSimulationTime), "Could not read stop frame."); @@ -742,7 +746,7 @@ bool CoSimClient::OnStop() { return true; } -bool CoSimClient::OnTerminate() { +[[nodiscard]] bool CoSimClient::OnTerminate() { DsVeosCoSim_TerminateReason reason{}; CheckResultWithMessage(Protocol::ReadTerminate(_channel->GetReader(), _currentSimulationTime, reason), "Could not read terminate frame."); @@ -754,7 +758,7 @@ bool CoSimClient::OnTerminate() { return true; } -bool CoSimClient::OnPause() { +[[nodiscard]] bool CoSimClient::OnPause() { CheckResultWithMessage(Protocol::ReadPause(_channel->GetReader(), _currentSimulationTime), "Could not read pause frame."); @@ -765,7 +769,7 @@ bool CoSimClient::OnPause() { return true; } -bool CoSimClient::OnContinue() { +[[nodiscard]] bool CoSimClient::OnContinue() { CheckResultWithMessage(Protocol::ReadContinue(_channel->GetReader(), _currentSimulationTime), "Could not read continue frame."); @@ -783,7 +787,7 @@ void CoSimClient::EnsureIsConnected() const { } void CoSimClient::EnsureIsInResponderModeBlocking() { - switch (_responderMode) { // NOLINT(clang-diagnostic-switch-enum) + switch (_responderMode) { case ResponderMode::Unknown: _responderMode = ResponderMode::Blocking; break; @@ -796,7 +800,7 @@ void CoSimClient::EnsureIsInResponderModeBlocking() { } void CoSimClient::EnsureIsInResponderModeNonBlocking() { - switch (_responderMode) { // NOLINT(clang-diagnostic-switch-enum) + switch (_responderMode) { case ResponderMode::Unknown: _responderMode = ResponderMode::NonBlocking; break; diff --git a/src/CoSimClient.h b/src/CoSimClient.h index b5cdb5c..b0cf39f 100644 --- a/src/CoSimClient.h +++ b/src/CoSimClient.h @@ -3,6 +3,7 @@ #pragma once #include +#include #include #include "BusBuffer.h" diff --git a/src/CoSimServer.cpp b/src/CoSimServer.cpp index aa53a3e..4327f84 100644 --- a/src/CoSimServer.cpp +++ b/src/CoSimServer.cpp @@ -3,6 +3,7 @@ #include "CoSimServer.h" #include +#include #include #include "CoSimHelper.h" @@ -155,7 +156,7 @@ void CoSimServer::Read(DsVeosCoSim_IoSignalId signalId, uint32_t& length, const _ioBuffer->Read(signalId, length, value); } -bool CoSimServer::Transmit(const DsVeosCoSim_CanMessage& message) const { +[[nodiscard]] bool CoSimServer::Transmit(const DsVeosCoSim_CanMessage& message) const { if (!_channel) { return true; } @@ -163,7 +164,7 @@ bool CoSimServer::Transmit(const DsVeosCoSim_CanMessage& message) const { return _busBuffer->Transmit(message); } -bool CoSimServer::Transmit(const DsVeosCoSim_EthMessage& message) const { +[[nodiscard]] bool CoSimServer::Transmit(const DsVeosCoSim_EthMessage& message) const { if (!_channel) { return true; } @@ -171,7 +172,7 @@ bool CoSimServer::Transmit(const DsVeosCoSim_EthMessage& message) const { return _busBuffer->Transmit(message); } -bool CoSimServer::Transmit(const DsVeosCoSim_LinMessage& message) const { +[[nodiscard]] bool CoSimServer::Transmit(const DsVeosCoSim_LinMessage& message) const { if (!_channel) { return true; } @@ -200,7 +201,7 @@ void CoSimServer::BackgroundService() { HandlePendingCommand(command); } -uint16_t CoSimServer::GetLocalPort() const { +[[nodiscard]] uint16_t CoSimServer::GetLocalPort() const { if (_tcpChannelServer) { return _tcpChannelServer->GetLocalPort(); } @@ -208,42 +209,42 @@ uint16_t CoSimServer::GetLocalPort() const { return 0; } -bool CoSimServer::StartInternal(DsVeosCoSim_SimulationTime simulationTime) const { +[[nodiscard]] bool CoSimServer::StartInternal(DsVeosCoSim_SimulationTime simulationTime) const { CheckResultWithMessage(Protocol::SendStart(_channel->GetWriter(), simulationTime), "Could not send start frame."); CheckResultWithMessage(WaitForOkFrame(), "Could not receive ok frame."); return true; } -bool CoSimServer::StopInternal(DsVeosCoSim_SimulationTime simulationTime) const { +[[nodiscard]] bool CoSimServer::StopInternal(DsVeosCoSim_SimulationTime simulationTime) const { CheckResultWithMessage(Protocol::SendStop(_channel->GetWriter(), simulationTime), "Could not send stop frame."); CheckResultWithMessage(WaitForOkFrame(), "Could not receive ok frame."); return true; } -bool CoSimServer::TerminateInternal(DsVeosCoSim_SimulationTime simulationTime, - DsVeosCoSim_TerminateReason reason) const { +[[nodiscard]] bool CoSimServer::TerminateInternal(DsVeosCoSim_SimulationTime simulationTime, + DsVeosCoSim_TerminateReason reason) const { CheckResultWithMessage(Protocol::SendTerminate(_channel->GetWriter(), simulationTime, reason), "Could not send terminate frame."); CheckResultWithMessage(WaitForOkFrame(), "Could not receive ok frame."); return true; } -bool CoSimServer::PauseInternal(DsVeosCoSim_SimulationTime simulationTime) const { +[[nodiscard]] bool CoSimServer::PauseInternal(DsVeosCoSim_SimulationTime simulationTime) const { CheckResultWithMessage(Protocol::SendPause(_channel->GetWriter(), simulationTime), "Could not send pause frame."); CheckResultWithMessage(WaitForOkFrame(), "Could not receive ok frame."); return true; } -bool CoSimServer::ContinueInternal(DsVeosCoSim_SimulationTime simulationTime) const { +[[nodiscard]] bool CoSimServer::ContinueInternal(DsVeosCoSim_SimulationTime simulationTime) const { CheckResultWithMessage(Protocol::SendContinue(_channel->GetWriter(), simulationTime), "Could not send continue frame."); CheckResultWithMessage(WaitForOkFrame(), "Could not receive ok frame."); return true; } -bool CoSimServer::StepInternal(DsVeosCoSim_SimulationTime simulationTime, - DsVeosCoSim_SimulationTime& nextSimulationTime, - Command& command) const { +[[nodiscard]] bool CoSimServer::StepInternal(DsVeosCoSim_SimulationTime simulationTime, + DsVeosCoSim_SimulationTime& nextSimulationTime, + Command& command) const { CheckResultWithMessage(Protocol::SendStep(_channel->GetWriter(), simulationTime, *_ioBuffer, *_busBuffer), "Could not send step frame."); CheckResultWithMessage(WaitForStepOkFrame(nextSimulationTime, command), "Could not receive step ok frame"); @@ -262,7 +263,7 @@ void CoSimServer::CloseConnection() { StartAccepting(); } -bool CoSimServer::Ping(Command& command) const { +[[nodiscard]] bool CoSimServer::Ping(Command& command) const { CheckResultWithMessage(Protocol::SendPing(_channel->GetWriter()), "Could not send ping frame."); CheckResultWithMessage(WaitForPingOkFrame(command), "Could not receive ping ok frame."); return true; @@ -320,7 +321,7 @@ void CoSimServer::StopAccepting() { #endif } -bool CoSimServer::AcceptChannel() { +[[nodiscard]] bool CoSimServer::AcceptChannel() { if (_channel) { return true; } @@ -357,7 +358,7 @@ bool CoSimServer::AcceptChannel() { return false; } -bool CoSimServer::OnHandleConnect() { +[[nodiscard]] bool CoSimServer::OnHandleConnect() { uint32_t clientProtocolVersion{}; std::string clientName; CheckResultWithMessage(WaitForConnectFrame(clientProtocolVersion, clientName), "Could not receive connect frame."); @@ -414,11 +415,11 @@ bool CoSimServer::OnHandleConnect() { return true; } -bool CoSimServer::WaitForOkFrame() const { +[[nodiscard]] bool CoSimServer::WaitForOkFrame() const { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(_channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::Ok: return true; case FrameKind::Error: { @@ -432,11 +433,11 @@ bool CoSimServer::WaitForOkFrame() const { } } -bool CoSimServer::WaitForPingOkFrame(Command& command) const { +[[nodiscard]] bool CoSimServer::WaitForPingOkFrame(Command& command) const { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(_channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::PingOk: CheckResultWithMessage(Protocol::ReadPingOk(_channel->GetReader(), command), "Could not read ping ok frame."); @@ -446,11 +447,11 @@ bool CoSimServer::WaitForPingOkFrame(Command& command) const { } } -bool CoSimServer::WaitForConnectFrame(uint32_t& version, std::string& clientName) const { +[[nodiscard]] bool CoSimServer::WaitForConnectFrame(uint32_t& version, std::string& clientName) const { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(_channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::Connect: { Mode mode{}; std::string serverName; @@ -463,11 +464,11 @@ bool CoSimServer::WaitForConnectFrame(uint32_t& version, std::string& clientName } } -bool CoSimServer::WaitForStepOkFrame(DsVeosCoSim_SimulationTime& simulationTime, Command& command) const { +[[nodiscard]] bool CoSimServer::WaitForStepOkFrame(DsVeosCoSim_SimulationTime& simulationTime, Command& command) const { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(_channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::StepOk: CheckResultWithMessage(Protocol::ReadStepOk(_channel->GetReader(), simulationTime, @@ -511,7 +512,7 @@ void CoSimServer::HandlePendingCommand(Command command) const { case Command::None: case Command::Step: case Command::Ping: - default: // NOLINT(clang-diagnostic-covered-switch-default) + default: break; } } diff --git a/src/CoSimTypes.h b/src/CoSimTypes.h index b64c106..c389389 100644 --- a/src/CoSimTypes.h +++ b/src/CoSimTypes.h @@ -2,11 +2,13 @@ #pragma once -#include #include #include +#include +#include +#include #include -#include // NOLINT +#include #include "DsVeosCoSim/DsVeosCoSim.h" @@ -17,6 +19,10 @@ constexpr uint32_t EthMessageMaxLength = DSVEOSCOSIM_ETH_MESSAGE_MAX_LENGTH; // constexpr uint32_t LinMessageMaxLength = DSVEOSCOSIM_LIN_MESSAGE_MAX_LENGTH; // NOLINT constexpr uint32_t EthAddressLength = DSVEOSCOSIM_ETH_ADDRESS_LENGTH; +[[nodiscard]] inline std::string SimulationTimeToString(DsVeosCoSim_SimulationTime simulationTime) { + return std::to_string(DSVEOSCOSIM_SIMULATION_TIME_TO_SECONDS(simulationTime)) + " s"; +} + enum class CoSimType { Client, Server @@ -38,7 +44,7 @@ enum class ConnectionKind { Local }; -[[nodiscard]] inline std::string_view ToString(ConnectionKind connectionKind) { +[[nodiscard]] inline std::string ToString(ConnectionKind connectionKind) { switch (connectionKind) { case ConnectionKind::Remote: return "Remote"; @@ -61,7 +67,7 @@ enum class Command { Ping }; -[[nodiscard]] inline std::string_view ToString(Command command) { +[[nodiscard]] inline std::string ToString(Command command) { switch (command) { case Command::None: return "None"; @@ -86,7 +92,7 @@ enum class Command { return ""; } -[[nodiscard]] inline std::string_view ToString(DsVeosCoSim_Severity severity) { +[[nodiscard]] inline std::string ToString(DsVeosCoSim_Severity severity) { switch (severity) { case DsVeosCoSim_Severity_Error: return "Error"; @@ -116,7 +122,7 @@ enum class Command { return ""; } -[[nodiscard]] inline std::string_view ToString(DsVeosCoSim_ConnectionState connectionState) { +[[nodiscard]] inline std::string ToString(DsVeosCoSim_ConnectionState connectionState) { switch (connectionState) { case DsVeosCoSim_ConnectionState_Connected: return "Connected"; @@ -197,7 +203,7 @@ enum class Command { return ""; } -[[nodiscard]] inline std::string_view ToString(DsVeosCoSim_LinControllerType type) { +[[nodiscard]] inline std::string ToString(DsVeosCoSim_LinControllerType type) { switch (type) { case DsVeosCoSim_LinControllerType_Responder: return "Responder"; @@ -213,9 +219,17 @@ enum class Command { enum class SimulationState { }; +[[nodiscard]] inline std::string ToString([[maybe_unused]] SimulationState simulationState) { + return ""; +} + enum class Mode { }; +[[nodiscard]] inline std::string ToString([[maybe_unused]] Mode mode) { + return ""; +} + [[nodiscard]] inline std::string CanMessageFlagsToString(DsVeosCoSim_CanMessageFlags flags) { std::string flagsStr; @@ -330,6 +344,19 @@ enum class Mode { return flagsStr; } +[[nodiscard]] inline std::string DataToString(const uint8_t* data, size_t dataLength, char separator = 0) { + std::ostringstream oss; + oss << std::hex << std::setfill('0'); + for (uint32_t i = 0; i < dataLength; i++) { + oss << std::setw(2) << static_cast(data[i]); + if ((i < dataLength - 1) && separator != 0) { + oss << separator; + } + } + + return oss.str(); +} + struct IoSignal { DsVeosCoSim_IoSignalId id{}; uint32_t length{}; @@ -348,6 +375,33 @@ struct IoSignal { } }; +[[nodiscard]] inline std::string ToString(const IoSignal& signal) { + std::string str = "{Id: " + std::to_string(signal.id) + ", Length: " + std::to_string(signal.length) + + ", DataType: " + ToString(signal.dataType) + ", SizeKind: " + ToString(signal.sizeKind) + + ", Name: \"" + signal.name + "\"}"; + + return str; +} + +[[nodiscard]] inline std::string ToString(const std::vector& signals) { + std::string str = "["; + + bool first = true; + for (const IoSignal& signal : signals) { + str.append(ToString(signal)); + + if (first) { + first = false; + } else { + str.append(", "); + } + } + + str.append("]"); + + return str; +} + [[nodiscard]] inline std::vector Convert(const std::vector& signals) { std::vector ioSignals; ioSignals.reserve(signals.size()); @@ -381,6 +435,35 @@ struct CanController { } }; +[[nodiscard]] inline std::string ToString(const CanController& controller) { + std::string str = "{Id: " + std::to_string(controller.id) + ", QueueSize: " + std::to_string(controller.queueSize) + + ", BitsPerSecond: " + std::to_string(controller.bitsPerSecond) + + ", FlexibleDataRateBitsPerSecond: " + std::to_string(controller.flexibleDataRateBitsPerSecond) + + ", Name: \"" + controller.name + "\", ChannelName: \"" + controller.channelName + + "\", ClusterName: \"" + controller.clusterName + "\"}"; + + return str; +} + +[[nodiscard]] inline std::string ToString(const std::vector& controllers) { + std::string str = "["; + + bool first = true; + for (const CanController& controller : controllers) { + str.append(ToString(controller)); + + if (first) { + first = false; + } else { + str.append(", "); + } + } + + str.append("]"); + + return str; +} + [[nodiscard]] inline std::vector Convert(const std::vector& controllers) { std::vector canControllers; canControllers.reserve(controllers.size()); @@ -414,6 +497,35 @@ struct EthController { } }; +[[nodiscard]] inline std::string ToString(const EthController& controller) { + std::string str = "{Id: " + std::to_string(controller.id) + ", QueueSize: " + std::to_string(controller.queueSize) + + ", BitsPerSecond: " + std::to_string(controller.bitsPerSecond) + ", MacAddress: [" + + DataToString(controller.macAddress.data(), controller.macAddress.size(), ':') + "], Name: \"" + + controller.name + "\", ChannelName: \"" + controller.channelName + "\", ClusterName: \"" + + controller.clusterName + "\"}"; + + return str; +} + +[[nodiscard]] inline std::string ToString(const std::vector& controllers) { + std::string str = "["; + + bool first = true; + for (const EthController& controller : controllers) { + str.append(ToString(controller)); + + if (first) { + first = false; + } else { + str.append(", "); + } + } + + str.append("]"); + + return str; +} + [[nodiscard]] inline std::vector Convert(const std::vector& controllers) { std::vector ethControllers; ethControllers.reserve(controllers.size()); @@ -447,6 +559,34 @@ struct LinController { } }; +[[nodiscard]] inline std::string ToString(const LinController& controller) { + std::string str = "{Id: " + std::to_string(controller.id) + ", QueueSize: " + std::to_string(controller.queueSize) + + ", BitsPerSecond: " + std::to_string(controller.bitsPerSecond) + + ", Type: " + ToString(controller.type) + ", Name: \"" + controller.name + "\", ChannelName: \"" + + controller.channelName + "\", ClusterName: \"" + controller.clusterName + "\"}"; + + return str; +} + +[[nodiscard]] inline std::string ToString(const std::vector& controllers) { + std::string str = "["; + + bool first = true; + for (const LinController& controller : controllers) { + str.append(ToString(controller)); + + if (first) { + first = false; + } else { + str.append(", "); + } + } + + str.append("]"); + + return str; +} + [[nodiscard]] inline std::vector Convert(const std::vector& controllers) { std::vector linControllers; linControllers.reserve(controllers.size()); diff --git a/src/Communication/LocalChannel.cpp b/src/Communication/LocalChannel.cpp index 13a9225..d4b3311 100644 --- a/src/Communication/LocalChannel.cpp +++ b/src/Communication/LocalChannel.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "CoSimHelper.h" #include "NamedMutex.h" @@ -21,32 +22,32 @@ constexpr uint32_t BufferSize = 64 * 1024; std::string ServerToClientPostFix = "ServerToClient"; std::string ClientToServerPostFix = "ClientToServer"; -std::string GetWriterName(std::string_view name, bool isServer) { +[[nodiscard]] std::string GetWriterName(const std::string& name, bool isServer) { std::string postfix = isServer ? ServerToClientPostFix : ClientToServerPostFix; - return std::string(name) + "." + postfix; + return name + "." + postfix; } -std::string GetReaderName(std::string_view name, bool isServer) { +[[nodiscard]] std::string GetReaderName(const std::string& name, bool isServer) { std::string postfix = isServer ? ClientToServerPostFix : ServerToClientPostFix; - return std::string(name) + "." + postfix; + return name + "." + postfix; } -constexpr uint32_t MaskIndex(uint32_t index) noexcept { +[[nodiscard]] constexpr uint32_t MaskIndex(uint32_t index) noexcept { return index & (BufferSize - 1); } } // namespace -LocalChannelBase::LocalChannelBase(std::string_view name, bool isServer) { +LocalChannelBase::LocalChannelBase(const std::string& name, bool isServer) { NamedMutex mutex = NamedMutex::CreateOrOpen(name); std::lock_guard lock(mutex); bool initShm{}; - const std::string dataName = std::string(name) + ".Data"; - const std::string newDataName = std::string(name) + ".NewData"; - const std::string newSpaceName = std::string(name) + ".NewSpace"; + const std::string dataName = name + ".Data"; + const std::string newDataName = name + ".NewData"; + const std::string newSpaceName = name + ".NewSpace"; uint32_t totalSize = BufferSize + sizeof(Header); @@ -88,16 +89,14 @@ LocalChannelBase::~LocalChannelBase() noexcept { Disconnect(); } -LocalChannelBase::LocalChannelBase(LocalChannelBase&& other) noexcept { - _newDataEvent = std::move(other._newDataEvent); - _newSpaceEvent = std::move(other._newSpaceEvent); - _sharedMemory = std::move(other._sharedMemory); - - _header = other._header; - _data = other._data; - _counterpartPid = other._counterpartPid; - _ownPid = other._ownPid; - +LocalChannelBase::LocalChannelBase(LocalChannelBase&& other) noexcept + : _newDataEvent(std::move(other._newDataEvent)), + _newSpaceEvent(std::move(other._newSpaceEvent)), + _header(other._header), + _data(other._data), + _counterpartPid(other._counterpartPid), + _ownPid(other._ownPid), + _sharedMemory(std::move(other._sharedMemory)) { other._header = {}; other._data = {}; other._counterpartPid = {}; @@ -128,7 +127,7 @@ void LocalChannelBase::Disconnect() const { } } -bool LocalChannelBase::CheckIfConnectionIsAlive() { +[[nodiscard]] bool LocalChannelBase::CheckIfConnectionIsAlive() { uint32_t counterpartPid = *_counterpartPid; if (counterpartPid != 0) { _connectionDetected = true; @@ -152,11 +151,11 @@ bool LocalChannelBase::CheckIfConnectionIsAlive() { return true; } -LocalChannelWriter::LocalChannelWriter(std::string_view name, bool isServer) +LocalChannelWriter::LocalChannelWriter(const std::string& name, bool isServer) : LocalChannelBase(GetWriterName(name, isServer), isServer) { } -bool LocalChannelWriter::Write(const void* source, size_t size) { +[[nodiscard]] bool LocalChannelWriter::Write(const void* source, size_t size) { const auto* bufferPointer = static_cast(source); auto totalSizeToCopy = static_cast(size); @@ -192,12 +191,12 @@ bool LocalChannelWriter::Write(const void* source, size_t size) { return true; } -bool LocalChannelWriter::EndWrite() { +[[nodiscard]] bool LocalChannelWriter::EndWrite() { _newDataEvent.Set(); return true; } -bool LocalChannelWriter::WaitForFreeSpace(uint32_t& currentSize) { +[[nodiscard]] bool LocalChannelWriter::WaitForFreeSpace(uint32_t& currentSize) { (void)SignalAndWait(_newDataEvent, _newSpaceEvent, 1); currentSize = _writeIndex - _header->readIndex.load(); if (currentSize < BufferSize) { @@ -219,11 +218,11 @@ bool LocalChannelWriter::WaitForFreeSpace(uint32_t& currentSize) { return true; } -LocalChannelReader::LocalChannelReader(std::string_view name, bool isServer) +LocalChannelReader::LocalChannelReader(const std::string& name, bool isServer) : LocalChannelBase(GetReaderName(name, isServer), isServer) { } -bool LocalChannelReader::Read(void* destination, size_t size) { +[[nodiscard]] bool LocalChannelReader::Read(void* destination, size_t size) { auto* bufferPointer = static_cast(destination); auto totalSizeToCopy = static_cast(size); @@ -262,7 +261,7 @@ bool LocalChannelReader::Read(void* destination, size_t size) { return true; } -bool LocalChannelReader::BeginRead(uint32_t& currentSize) { +[[nodiscard]] bool LocalChannelReader::BeginRead(uint32_t& currentSize) { while (!_newDataEvent.Wait(1)) { currentSize = _header->writeIndex.load() - _readIndex; if (currentSize > 0) { @@ -278,7 +277,7 @@ bool LocalChannelReader::BeginRead(uint32_t& currentSize) { return true; } -LocalChannel::LocalChannel(std::string_view name, bool isServer) : _writer(name, isServer), _reader(name, isServer) { +LocalChannel::LocalChannel(const std::string& name, bool isServer) : _writer(name, isServer), _reader(name, isServer) { } void LocalChannel::Disconnect() { @@ -286,15 +285,15 @@ void LocalChannel::Disconnect() { _reader.Disconnect(); } -ChannelWriter& LocalChannel::GetWriter() { +[[nodiscard]] ChannelWriter& LocalChannel::GetWriter() { return _writer; } -ChannelReader& LocalChannel::GetReader() { +[[nodiscard]] ChannelReader& LocalChannel::GetReader() { return _reader; } -std::optional TryConnectToLocalChannel(std::string_view name) { +[[nodiscard]] std::optional TryConnectToLocalChannel(const std::string& name) { NamedMutex mutex = NamedMutex::CreateOrOpen(name); std::lock_guard lock(mutex); @@ -306,25 +305,26 @@ std::optional TryConnectToLocalChannel(std::string_view name) { auto& counter = *static_cast*>(sharedMemory->data()); const int32_t currentCounter = counter.fetch_add(1); - const std::string specificName = std::string(name) + "." + std::to_string(currentCounter); + const std::string specificName = name + "." + std::to_string(currentCounter); return LocalChannel(specificName, false); } -LocalChannelServer::LocalChannelServer(std::string_view name) : _name(name) { +LocalChannelServer::LocalChannelServer(const std::string& name) : _name(name) { NamedMutex mutex = NamedMutex::CreateOrOpen(name); std::lock_guard lock(mutex); _sharedMemory = SharedMemory::CreateOrOpen(_name, ServerSharedMemorySize); - _counter = static_cast*>(_sharedMemory.data()); + _counter = static_cast*>( // NOLINT(cppcoreguidelines-prefer-member-initializer) + _sharedMemory.data()); _counter->store(0); } -std::optional LocalChannelServer::TryAccept() { +[[nodiscard]] std::optional LocalChannelServer::TryAccept() { const int32_t currentCounter = _counter->load(); if (currentCounter > _lastCounter) { - const std::string specificName = std::string(_name) + "." + std::to_string(_lastCounter); + const std::string specificName = _name + "." + std::to_string(_lastCounter); _lastCounter++; return LocalChannel(specificName, true); } diff --git a/src/Communication/LocalChannel.h b/src/Communication/LocalChannel.h index 89181a7..c81dbaa 100644 --- a/src/Communication/LocalChannel.h +++ b/src/Communication/LocalChannel.h @@ -9,7 +9,6 @@ #include #include #include -#include #include "Channel.h" #include "NamedEvent.h" @@ -21,7 +20,7 @@ constexpr uint32_t LockFreeCacheLineBytes = 64; class LocalChannelBase { protected: - LocalChannelBase(std::string_view name, bool isServer); + LocalChannelBase(const std::string& name, bool isServer); public: virtual ~LocalChannelBase() noexcept; @@ -59,7 +58,7 @@ class LocalChannelBase { class LocalChannelWriter final : public LocalChannelBase, public ChannelWriter { public: - LocalChannelWriter(std::string_view name, bool isServer); + LocalChannelWriter(const std::string& name, bool isServer); ~LocalChannelWriter() noexcept override = default; LocalChannelWriter(const LocalChannelWriter&) = delete; @@ -81,7 +80,7 @@ class LocalChannelWriter final : public LocalChannelBase, public ChannelWriter { class LocalChannelReader final : public LocalChannelBase, public ChannelReader { public: - LocalChannelReader(std::string_view name, bool isServer); + LocalChannelReader(const std::string& name, bool isServer); ~LocalChannelReader() noexcept override = default; LocalChannelReader(const LocalChannelReader&) = delete; @@ -101,7 +100,7 @@ class LocalChannelReader final : public LocalChannelBase, public ChannelReader { class LocalChannel final : public Channel { public: - LocalChannel(std::string_view name, bool isServer); + LocalChannel(const std::string& name, bool isServer); ~LocalChannel() noexcept override = default; LocalChannel(const LocalChannel&) = delete; @@ -120,11 +119,11 @@ class LocalChannel final : public Channel { LocalChannelReader _reader; }; -[[nodiscard]] std::optional TryConnectToLocalChannel(std::string_view name); +[[nodiscard]] std::optional TryConnectToLocalChannel(const std::string& name); class LocalChannelServer final { public: - explicit LocalChannelServer(std::string_view name); + explicit LocalChannelServer(const std::string& name); ~LocalChannelServer() noexcept = default; LocalChannelServer(const LocalChannelServer&) = delete; diff --git a/src/Communication/SocketChannel.cpp b/src/Communication/SocketChannel.cpp index 5d3a475..3e7e8b7 100644 --- a/src/Communication/SocketChannel.cpp +++ b/src/Communication/SocketChannel.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include #include "CoSimHelper.h" @@ -19,20 +21,14 @@ constexpr int32_t ReadPacketSize = 1024; } // namespace -SocketChannelWriter::SocketChannelWriter(Socket* socket) : _socket(socket) { - _writeIndex = HeaderSize; - +SocketChannelWriter::SocketChannelWriter(Socket* socket) : _socket(socket), _writeIndex(HeaderSize) { _writeBuffer.resize(BufferSize); } -SocketChannelWriter::SocketChannelWriter(SocketChannelWriter&& other) noexcept { - _socket = other._socket; - _writeIndex = other._writeIndex; - _writeBuffer = other._writeBuffer; - +SocketChannelWriter::SocketChannelWriter(SocketChannelWriter&& other) noexcept + : _socket(other._socket), _writeIndex(other._writeIndex), _writeBuffer(std::move(other._writeBuffer)) { other._socket = nullptr; other._writeIndex = 0; - other._writeBuffer.clear(); } SocketChannelWriter& SocketChannelWriter::operator=(SocketChannelWriter&& other) noexcept { @@ -47,7 +43,7 @@ SocketChannelWriter& SocketChannelWriter::operator=(SocketChannelWriter&& other) return *this; } -bool SocketChannelWriter::Write(const void* source, size_t size) { +[[nodiscard]] bool SocketChannelWriter::Write(const void* source, size_t size) { const auto* bufferPointer = static_cast(source); while (size > 0) { @@ -66,7 +62,7 @@ bool SocketChannelWriter::Write(const void* source, size_t size) { return true; } -bool SocketChannelWriter::EndWrite() { +[[nodiscard]] bool SocketChannelWriter::EndWrite() { uint8_t* sourcePtr = _writeBuffer.data(); // Write header @@ -84,21 +80,16 @@ bool SocketChannelWriter::EndWrite() { return true; } -SocketChannelReader::SocketChannelReader(Socket* socket) : _socket(socket) { - _readIndex = HeaderSize; - _writeIndex = 0; - _endFrameIndex = 0; - +SocketChannelReader::SocketChannelReader(Socket* socket) : _socket(socket), _readIndex(HeaderSize) { _readBuffer.resize(BufferSize); } -SocketChannelReader::SocketChannelReader(SocketChannelReader&& other) noexcept { - _socket = other._socket; - _readIndex = other._readIndex; - _writeIndex = other._writeIndex; - _endFrameIndex = other._endFrameIndex; - _readBuffer = other._readBuffer; - +SocketChannelReader::SocketChannelReader(SocketChannelReader&& other) noexcept + : _socket(other._socket), + _readIndex(other._readIndex), + _writeIndex(other._writeIndex), + _endFrameIndex(other._endFrameIndex), + _readBuffer(std::move(other._readBuffer)) { other._socket = nullptr; other._readIndex = 0; other._writeIndex = 0; @@ -122,7 +113,7 @@ SocketChannelReader& SocketChannelReader::operator=(SocketChannelReader&& other) return *this; } -bool SocketChannelReader::BeginRead() { +[[nodiscard]] bool SocketChannelReader::BeginRead() { _readIndex = HeaderSize; int32_t sizeToRead = ReadPacketSize; bool readHeader = true; @@ -172,7 +163,7 @@ bool SocketChannelReader::BeginRead() { return true; } -bool SocketChannelReader::Read(void* destination, size_t size) { +[[nodiscard]] bool SocketChannelReader::Read(void* destination, size_t size) { auto* bufferPointer = static_cast(destination); while (size > 0) { @@ -205,7 +196,7 @@ SocketChannel& SocketChannel::operator=(SocketChannel&& other) noexcept { return *this; } -SocketAddress SocketChannel::GetRemoteAddress() const { +[[nodiscard]] SocketAddress SocketChannel::GetRemoteAddress() const { return _socket.GetRemoteAddress(); } @@ -213,18 +204,18 @@ void SocketChannel::Disconnect() { _socket.Shutdown(); } -ChannelWriter& SocketChannel::GetWriter() { +[[nodiscard]] ChannelWriter& SocketChannel::GetWriter() { return _writer; } -ChannelReader& SocketChannel::GetReader() { +[[nodiscard]] ChannelReader& SocketChannel::GetReader() { return _reader; } -std::optional TryConnectToTcpChannel(std::string_view remoteIpAddress, - uint16_t remotePort, - uint16_t localPort, - uint32_t timeoutInMilliseconds) { +[[nodiscard]] std::optional TryConnectToTcpChannel(std::string_view remoteIpAddress, + uint16_t remotePort, + uint16_t localPort, + uint32_t timeoutInMilliseconds) { StartupNetwork(); std::optional connectedSocket = @@ -237,11 +228,9 @@ std::optional TryConnectToTcpChannel(std::string_view remoteIpAdd return {}; } -TcpChannelServer::TcpChannelServer(uint16_t port, bool enableRemoteAccess) { +TcpChannelServer::TcpChannelServer(uint16_t port, bool enableRemoteAccess) : _port(port) { StartupNetwork(); - _port = port; - if (Socket::IsIpv4Supported()) { _listenSocketIpv4 = Socket(AddressFamily::Ipv4); _listenSocketIpv4.EnableReuseAddress(); @@ -260,11 +249,11 @@ TcpChannelServer::TcpChannelServer(uint16_t port, bool enableRemoteAccess) { } } -uint16_t TcpChannelServer::GetLocalPort() const { +[[nodiscard]] uint16_t TcpChannelServer::GetLocalPort() const { return _port; } -std::optional TcpChannelServer::TryAccept(uint32_t timeoutInMilliseconds) const { +[[nodiscard]] std::optional TcpChannelServer::TryAccept(uint32_t timeoutInMilliseconds) const { do { std::optional socket = _listenSocketIpv4.TryAccept(); if (socket) { @@ -288,7 +277,7 @@ std::optional TcpChannelServer::TryAccept(uint32_t timeoutInMilli return {}; } -std::optional TryConnectToUdsChannel(std::string_view name) { +[[nodiscard]] std::optional TryConnectToUdsChannel(const std::string& name) { StartupNetwork(); Socket socket(AddressFamily::Uds); @@ -299,7 +288,7 @@ std::optional TryConnectToUdsChannel(std::string_view name) { return {}; } -UdsChannelServer::UdsChannelServer(std::string_view name) { +UdsChannelServer::UdsChannelServer(const std::string& name) { StartupNetwork(); _listenSocket = Socket(AddressFamily::Uds); @@ -307,7 +296,7 @@ UdsChannelServer::UdsChannelServer(std::string_view name) { _listenSocket.Listen(); } -std::optional UdsChannelServer::TryAccept(uint32_t timeoutInMilliseconds) const { +[[nodiscard]] std::optional UdsChannelServer::TryAccept(uint32_t timeoutInMilliseconds) const { std::optional socket = _listenSocket.TryAccept(timeoutInMilliseconds); if (socket) { return SocketChannel(std::move(*socket)); diff --git a/src/Communication/SocketChannel.h b/src/Communication/SocketChannel.h index c0b605a..bf19d58 100644 --- a/src/Communication/SocketChannel.h +++ b/src/Communication/SocketChannel.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -110,11 +111,11 @@ class TcpChannelServer final { Socket _listenSocketIpv6; }; -[[nodiscard]] std::optional TryConnectToUdsChannel(std::string_view name); +[[nodiscard]] std::optional TryConnectToUdsChannel(const std::string& name); class UdsChannelServer final { public: - explicit UdsChannelServer(std::string_view name); + explicit UdsChannelServer(const std::string& name); ~UdsChannelServer() noexcept = default; UdsChannelServer(const UdsChannelServer&) = delete; diff --git a/src/DsVeosCoSim.cpp b/src/DsVeosCoSim.cpp index dbec1f1..5ce6b08 100644 --- a/src/DsVeosCoSim.cpp +++ b/src/DsVeosCoSim.cpp @@ -3,6 +3,8 @@ #include "DsVeosCoSim/DsVeosCoSim.h" #include +#include +#include #include "CoSimClient.h" #include "CoSimHelper.h" @@ -48,7 +50,7 @@ void DsVeosCoSim_Destroy(DsVeosCoSim_Handle handle) { delete client; } -DsVeosCoSim_Result DsVeosCoSim_Connect(DsVeosCoSim_Handle handle, DsVeosCoSim_ConnectConfig connectConfig) { // NOLINT +DsVeosCoSim_Result DsVeosCoSim_Connect(DsVeosCoSim_Handle handle, DsVeosCoSim_ConnectConfig connectConfig) { CheckNotNull(handle); auto* const client = static_cast(handle); @@ -117,7 +119,7 @@ DsVeosCoSim_Result DsVeosCoSim_GetConnectionState(DsVeosCoSim_Handle handle, } DsVeosCoSim_Result DsVeosCoSim_RunCallbackBasedCoSimulation(DsVeosCoSim_Handle handle, - DsVeosCoSim_Callbacks callbacks) { // NOLINT + DsVeosCoSim_Callbacks callbacks) { CheckNotNull(handle); auto* const client = static_cast(handle); @@ -139,7 +141,7 @@ DsVeosCoSim_Result DsVeosCoSim_RunCallbackBasedCoSimulation(DsVeosCoSim_Handle h } DsVeosCoSim_Result DsVeosCoSim_StartPollingBasedCoSimulation(DsVeosCoSim_Handle handle, - DsVeosCoSim_Callbacks callbacks) { // NOLINT + DsVeosCoSim_Callbacks callbacks) { CheckNotNull(handle); auto* const client = static_cast(handle); diff --git a/src/Helpers/CoSimHelper.cpp b/src/Helpers/CoSimHelper.cpp index 306ba66..f247e51 100644 --- a/src/Helpers/CoSimHelper.cpp +++ b/src/Helpers/CoSimHelper.cpp @@ -2,6 +2,8 @@ #include "CoSimHelper.h" +#include +#include #include namespace DsVeosCoSim { @@ -44,7 +46,15 @@ void LogTrace(std::string_view message) { } } -std::string GetSystemErrorMessage(int32_t errorCode) { +void LogProtocolBeginTrace(const std::string& message) { + LogTrace("PROT BEGIN " + message); +} + +void LogProtocolEndTrace(const std::string& message) { + LogTrace("PROT END " + message); +} + +[[nodiscard]] std::string GetSystemErrorMessage(int32_t errorCode) { return "Error code: " + std::to_string(errorCode) + ". " + std::system_category().message(errorCode); } diff --git a/src/Helpers/CoSimHelper.h b/src/Helpers/CoSimHelper.h index 9ef459a..71aae67 100644 --- a/src/Helpers/CoSimHelper.h +++ b/src/Helpers/CoSimHelper.h @@ -3,6 +3,8 @@ #pragma once #include +#include +#include #include "CoSimTypes.h" @@ -14,6 +16,8 @@ void LogError(std::string_view message); void LogWarning(std::string_view message); void LogInfo(std::string_view message); void LogTrace(std::string_view message); +void LogProtocolBeginTrace(const std::string& message); +void LogProtocolEndTrace(const std::string& message); #define CheckResultWithMessage(result, message) \ do { \ @@ -37,8 +41,8 @@ class CoSimException final : public std::runtime_error { explicit CoSimException(std::string_view message) : std::runtime_error(message.data()) { } - CoSimException(std::string_view message, int32_t errorCode) - : std::runtime_error(std::string(message) + " " + GetSystemErrorMessage(errorCode)) { + CoSimException(const std::string& message, int32_t errorCode) + : std::runtime_error(message + " " + GetSystemErrorMessage(errorCode)) { } }; diff --git a/src/Helpers/Environment.cpp b/src/Helpers/Environment.cpp new file mode 100644 index 0000000..b4f3c2f --- /dev/null +++ b/src/Helpers/Environment.cpp @@ -0,0 +1,53 @@ +// Copyright dSPACE GmbH. All rights reserved. + +#include "Environment.h" + +#include +#include + +namespace DsVeosCoSim { + +namespace { + +[[nodiscard]] bool GetBoolValue(const std::string& name) { + const char* stringValue = std::getenv(name.c_str()); + if (stringValue) { + const int32_t intValue = std::atoi(stringValue); + return intValue != 0; + } + + return false; +} + +[[nodiscard]] uint16_t GetPortMapperPortInitial() { + constexpr uint16_t defaultPort = 27027; + + const char* portString = std::getenv("VEOS_COSIM_PORTMAPPER_PORT"); + if (portString) { + const int32_t port = std::atoi(portString); + if (port > 0 && port <= UINT16_MAX) { + return static_cast(port); + } + } + + return defaultPort; +} + +} // namespace + +[[nodiscard]] bool IsPortMapperServerVerbose() { + static bool verbose = GetBoolValue("VEOS_COSIM_PORTMAPPER_SERVER_VERBOSE"); + return verbose; +} + +[[nodiscard]] bool IsPortMapperClientVerbose() { + static bool verbose = GetBoolValue("VEOS_COSIM_PORTMAPPER_CLIENT_VERBOSE"); + return verbose; +} + +[[nodiscard]] uint16_t GetPortMapperPort() { + static uint16_t port = GetPortMapperPortInitial(); + return port; +} + +} // namespace DsVeosCoSim diff --git a/src/Helpers/Environment.h b/src/Helpers/Environment.h new file mode 100644 index 0000000..d2208f3 --- /dev/null +++ b/src/Helpers/Environment.h @@ -0,0 +1,14 @@ +// Copyright dSPACE GmbH. All rights reserved. + +#pragma once + +#include + +namespace DsVeosCoSim { + +[[nodiscard]] bool IsPortMapperServerVerbose(); +[[nodiscard]] bool IsPortMapperClientVerbose(); + +[[nodiscard]] uint16_t GetPortMapperPort(); + +} // namespace DsVeosCoSim diff --git a/src/IoBuffer.cpp b/src/IoBuffer.cpp index 8f63bed..9c40c4b 100644 --- a/src/IoBuffer.cpp +++ b/src/IoBuffer.cpp @@ -3,6 +3,7 @@ #include "IoBuffer.h" #include +#include #include "CoSimHelper.h" #include "CoSimTypes.h" @@ -13,7 +14,7 @@ namespace DsVeosCoSim { namespace { void CheckSizeKind(DsVeosCoSim_SizeKind sizeKind, const std::string& name) { - switch (sizeKind) { // NOLINT + switch (sizeKind) { case DsVeosCoSim_SizeKind_Fixed: case DsVeosCoSim_SizeKind_Variable: return; @@ -25,22 +26,18 @@ void CheckSizeKind(DsVeosCoSim_SizeKind sizeKind, const std::string& name) { } // namespace IoPartBufferBase::IoPartBufferBase(CoSimType coSimType, const std::vector& signals) - : _changedSignalsQueue(signals.size()) { - _coSimType = coSimType; - + : _coSimType(coSimType), _changedSignalsQueue(signals.size()) { size_t nextSignalIndex = 0; for (const auto& signal : signals) { if (signal.length == 0) { - throw CoSimException("Invalid length " + std::to_string(signal.length) + " for IO signal '" + signal.name + - "'."); + throw CoSimException("Invalid length 0 for IO signal '" + std::string(signal.name) + "'."); } CheckSizeKind(signal.sizeKind, signal.name); const size_t dataTypeSize = GetDataTypeSize(signal.dataType); if (dataTypeSize == 0) { - throw CoSimException("Invalid data type " + ToString(signal.dataType) + " for IO signal '" + signal.name + - "'."); + throw CoSimException("Invalid data type for IO signal '" + std::string(signal.name) + "'."); } if (_metaDataLookup.contains(signal.id)) { @@ -99,7 +96,7 @@ void IoPartBufferBase::Read(DsVeosCoSim_IoSignalId signalId, uint32_t& length, c ReadInternal(signalId, length, value); } -bool IoPartBufferBase::Serialize(ChannelWriter& writer) { +[[nodiscard]] bool IoPartBufferBase::Serialize(ChannelWriter& writer) { if (_coSimType == CoSimType::Client) { std::lock_guard lock(_mutex); return SerializeInternal(writer); @@ -108,9 +105,9 @@ bool IoPartBufferBase::Serialize(ChannelWriter& writer) { return SerializeInternal(writer); } -bool IoPartBufferBase::Deserialize(ChannelReader& reader, - DsVeosCoSim_SimulationTime simulationTime, - const Callbacks& callbacks) { +[[nodiscard]] bool IoPartBufferBase::Deserialize(ChannelReader& reader, + DsVeosCoSim_SimulationTime simulationTime, + const Callbacks& callbacks) { if (_coSimType == CoSimType::Client) { std::lock_guard lock(_mutex); return DeserializeInternal(reader, simulationTime, callbacks); @@ -129,7 +126,7 @@ IoPartBufferBase::MetaData& IoPartBufferBase::FindMetaData(DsVeosCoSim_IoSignalI } RemoteIoPartBuffer::RemoteIoPartBuffer(CoSimType coSimType, - [[maybe_unused]] std::string_view name, + [[maybe_unused]] const std::string& name, const std::vector& signals) : IoPartBufferBase(coSimType, signals) { _dataVector.resize(_metaDataLookup.size()); @@ -214,7 +211,7 @@ void RemoteIoPartBuffer::ReadInternal(DsVeosCoSim_IoSignalId signalId, uint32_t& *value = data.buffer.data(); } -bool RemoteIoPartBuffer::SerializeInternal(ChannelWriter& writer) { +[[nodiscard]] bool RemoteIoPartBuffer::SerializeInternal(ChannelWriter& writer) { auto size = static_cast(_changedSignalsQueue.Size()); CheckResultWithMessage(writer.Write(size), "Could not write count of changed signals."); if (_changedSignalsQueue.IsEmpty()) { @@ -240,9 +237,9 @@ bool RemoteIoPartBuffer::SerializeInternal(ChannelWriter& writer) { return true; } -bool RemoteIoPartBuffer::DeserializeInternal(ChannelReader& reader, - DsVeosCoSim_SimulationTime simulationTime, - const Callbacks& callbacks) { +[[nodiscard]] bool RemoteIoPartBuffer::DeserializeInternal(ChannelReader& reader, + DsVeosCoSim_SimulationTime simulationTime, + const Callbacks& callbacks) { uint32_t ioSignalChangedCount = 0; CheckResultWithMessage(reader.Read(ioSignalChangedCount), "Could not read count of changed signals."); @@ -281,7 +278,7 @@ bool RemoteIoPartBuffer::DeserializeInternal(ChannelReader& reader, #ifdef _WIN32 LocalIoPartBuffer::LocalIoPartBuffer(CoSimType coSimType, - std::string_view name, + const std::string& name, const std::vector& signals) : IoPartBufferBase(coSimType, signals) { // The memory layout looks like this: @@ -407,7 +404,7 @@ void LocalIoPartBuffer::ReadInternal(DsVeosCoSim_IoSignalId signalId, uint32_t& *value = dataBuffer->data; } -bool LocalIoPartBuffer::SerializeInternal(ChannelWriter& writer) { +[[nodiscard]] bool LocalIoPartBuffer::SerializeInternal(ChannelWriter& writer) { auto size = static_cast(_changedSignalsQueue.Size()); CheckResultWithMessage(writer.Write(size), "Could not write count of changed signals."); if (_changedSignalsQueue.IsEmpty()) { @@ -426,9 +423,9 @@ bool LocalIoPartBuffer::SerializeInternal(ChannelWriter& writer) { return true; } -bool LocalIoPartBuffer::DeserializeInternal(ChannelReader& reader, - DsVeosCoSim_SimulationTime simulationTime, - const Callbacks& callbacks) { +[[nodiscard]] bool LocalIoPartBuffer::DeserializeInternal(ChannelReader& reader, + DsVeosCoSim_SimulationTime simulationTime, + const Callbacks& callbacks) { uint32_t ioSignalChangedCount = 0; CheckResultWithMessage(reader.Read(ioSignalChangedCount), "Could not read count of changed signals."); @@ -454,7 +451,7 @@ bool LocalIoPartBuffer::DeserializeInternal(ChannelReader& reader, return true; } -LocalIoPartBuffer::DataBuffer* LocalIoPartBuffer::GetDataBuffer(size_t offset) const { +[[nodiscard]] LocalIoPartBuffer::DataBuffer* LocalIoPartBuffer::GetDataBuffer(size_t offset) const { return reinterpret_cast((static_cast(_sharedMemory.data()) + offset)); } @@ -466,11 +463,11 @@ void LocalIoPartBuffer::FlipBuffers(Data& data) { IoBuffer::IoBuffer(CoSimType coSimType, [[maybe_unused]] ConnectionKind connectionKind, - std::string_view name, + const std::string& name, const std::vector& incomingSignals, const std::vector& outgoingSignals) { - std::string outgoingName = std::string(name) + ".Outgoing"; - std::string incomingName = std::string(name) + ".Incoming"; + std::string outgoingName = name + ".Outgoing"; + std::string incomingName = name + ".Incoming"; const std::vector* writeSignals = &outgoingSignals; const std::vector* readSignals = &incomingSignals; if (coSimType == CoSimType::Server) { @@ -511,13 +508,13 @@ void IoBuffer::Read(DsVeosCoSim_IoSignalId signalId, uint32_t& length, const voi _readBuffer->Read(signalId, length, value); } -bool IoBuffer::Serialize(ChannelWriter& writer) const { +[[nodiscard]] bool IoBuffer::Serialize(ChannelWriter& writer) const { return _writeBuffer->Serialize(writer); } -bool IoBuffer::Deserialize(ChannelReader& reader, - DsVeosCoSim_SimulationTime simulationTime, - const Callbacks& callbacks) const { +[[nodiscard]] bool IoBuffer::Deserialize(ChannelReader& reader, + DsVeosCoSim_SimulationTime simulationTime, + const Callbacks& callbacks) const { return _readBuffer->Deserialize(reader, simulationTime, callbacks); } diff --git a/src/IoBuffer.h b/src/IoBuffer.h index 7f9ea66..1b907ac 100644 --- a/src/IoBuffer.h +++ b/src/IoBuffer.h @@ -4,7 +4,7 @@ #include #include -#include +#include #include #include @@ -78,7 +78,7 @@ class RemoteIoPartBuffer final : public IoPartBufferBase { }; public: - RemoteIoPartBuffer(CoSimType coSimType, std::string_view name, const std::vector& signals); + RemoteIoPartBuffer(CoSimType coSimType, const std::string& name, const std::vector& signals); ~RemoteIoPartBuffer() noexcept override = default; RemoteIoPartBuffer(const RemoteIoPartBuffer&) = delete; @@ -118,7 +118,7 @@ class LocalIoPartBuffer final : public IoPartBufferBase { }; public: - LocalIoPartBuffer(CoSimType coSimType, std::string_view name, const std::vector& signals); + LocalIoPartBuffer(CoSimType coSimType, const std::string& name, const std::vector& signals); ~LocalIoPartBuffer() noexcept override = default; LocalIoPartBuffer(const LocalIoPartBuffer&) = delete; @@ -154,7 +154,7 @@ class IoBuffer { public: IoBuffer(CoSimType coSimType, ConnectionKind connectionKind, - std::string_view name, + const std::string& name, const std::vector& incomingSignals, const std::vector& outgoingSignals); ~IoBuffer() noexcept = default; diff --git a/src/OsAbstraction/Handle.cpp b/src/OsAbstraction/Handle.cpp index 9f75ce0..179c187 100644 --- a/src/OsAbstraction/Handle.cpp +++ b/src/OsAbstraction/Handle.cpp @@ -18,9 +18,7 @@ Handle::~Handle() noexcept { (void)::CloseHandle(_handle); } -Handle::Handle(Handle&& other) noexcept { - _handle = other._handle; - +Handle::Handle(Handle&& other) noexcept : _handle(other._handle) { other._handle = {}; } @@ -40,7 +38,7 @@ void Handle::Wait() const { (void)Wait(Infinite); } -bool Handle::Wait(uint32_t milliseconds) const { +[[nodiscard]] bool Handle::Wait(uint32_t milliseconds) const { DWORD result = ::WaitForSingleObject(_handle, milliseconds); switch (result) { case WAIT_OBJECT_0: @@ -55,7 +53,7 @@ bool Handle::Wait(uint32_t milliseconds) const { } } -bool SignalAndWait(const Handle& toSignal, const Handle& toWait, uint32_t milliseconds) { +[[nodiscard]] bool SignalAndWait(const Handle& toSignal, const Handle& toWait, uint32_t milliseconds) { DWORD result = ::SignalObjectAndWait(toSignal, toWait, milliseconds, FALSE); switch (result) { case WAIT_OBJECT_0: diff --git a/src/OsAbstraction/NamedEvent.cpp b/src/OsAbstraction/NamedEvent.cpp index dcf29b3..dc3cf40 100644 --- a/src/OsAbstraction/NamedEvent.cpp +++ b/src/OsAbstraction/NamedEvent.cpp @@ -5,6 +5,8 @@ #include "NamedEvent.h" #include +#include +#include #include "CoSimHelper.h" #include "OsUtilities.h" @@ -13,43 +15,43 @@ namespace DsVeosCoSim { namespace { -[[nodiscard]] std::wstring GetFullNamedEventName(std::string_view name) { - return Utf8ToWide("Local\\dSPACE.VEOS.CoSim.Event." + std::string(name)); +[[nodiscard]] std::wstring GetFullNamedEventName(const std::string& name) { + return Utf8ToWide("Local\\dSPACE.VEOS.CoSim.Event." + name); } } // namespace -NamedEvent::NamedEvent(Handle handle) : _handle(std::move(handle)) { +NamedEvent::NamedEvent(Handle handle, const std::string& name) : _handle(std::move(handle)), _name(name) { } -NamedEvent NamedEvent::CreateOrOpen(std::string_view name) { +[[nodiscard]] NamedEvent NamedEvent::CreateOrOpen(const std::string& name) { std::wstring fullName = GetFullNamedEventName(name); void* handle = ::CreateEventW(nullptr, FALSE, FALSE, fullName.c_str()); if (!handle) { - throw CoSimException("Could not create event '" + std::string(name) + "'.", GetLastWindowsError()); + throw CoSimException("Could not create event '" + name + "'.", GetLastWindowsError()); } - return NamedEvent(handle); + return {handle, name}; } -NamedEvent NamedEvent::OpenExisting(std::string_view name) { +[[nodiscard]] NamedEvent NamedEvent::OpenExisting(const std::string& name) { std::wstring fullName = GetFullNamedEventName(name); void* handle = ::OpenEventW(EVENT_ALL_ACCESS, FALSE, fullName.c_str()); if (!handle) { - throw CoSimException("Could not open event '" + std::string(name) + "'.", GetLastWindowsError()); + throw CoSimException("Could not open event '" + name + "'.", GetLastWindowsError()); } - return NamedEvent(handle); + return {handle, name}; } -std::optional NamedEvent::TryOpenExisting(std::string_view name) { +[[nodiscard]] std::optional NamedEvent::TryOpenExisting(const std::string& name) { std::wstring fullName = GetFullNamedEventName(name); void* handle = ::OpenEventW(EVENT_ALL_ACCESS, FALSE, fullName.c_str()); if (!handle) { return {}; } - return NamedEvent(handle); + return NamedEvent(handle, name); } NamedEvent::operator Handle&() noexcept { @@ -58,7 +60,7 @@ NamedEvent::operator Handle&() noexcept { void NamedEvent::Set() { if (::SetEvent(_handle) == FALSE) { - throw CoSimException("Could not set event.", GetLastWindowsError()); + throw CoSimException("Could not set event '" + _name + "'.", GetLastWindowsError()); } } @@ -66,7 +68,7 @@ void NamedEvent::Wait() const { (void)Wait(Infinite); } -bool NamedEvent::Wait(uint32_t milliseconds) const { +[[nodiscard]] bool NamedEvent::Wait(uint32_t milliseconds) const { return _handle.Wait(milliseconds); } diff --git a/src/OsAbstraction/NamedEvent.h b/src/OsAbstraction/NamedEvent.h index 37d6e1d..af1c1a4 100644 --- a/src/OsAbstraction/NamedEvent.h +++ b/src/OsAbstraction/NamedEvent.h @@ -6,14 +6,14 @@ #include #include -#include +#include #include "Handle.h" namespace DsVeosCoSim { class NamedEvent final { - explicit NamedEvent(Handle handle); + NamedEvent(Handle handle, const std::string& name); public: NamedEvent() = default; @@ -25,9 +25,9 @@ class NamedEvent final { NamedEvent(NamedEvent&&) noexcept = default; NamedEvent& operator=(NamedEvent&&) noexcept = default; - [[nodiscard]] static NamedEvent CreateOrOpen(std::string_view name); - [[nodiscard]] static NamedEvent OpenExisting(std::string_view name); - [[nodiscard]] static std::optional TryOpenExisting(std::string_view name); + [[nodiscard]] static NamedEvent CreateOrOpen(const std::string& name); + [[nodiscard]] static NamedEvent OpenExisting(const std::string& name); + [[nodiscard]] static std::optional TryOpenExisting(const std::string& name); operator Handle&() noexcept; // NOLINT @@ -37,6 +37,7 @@ class NamedEvent final { private: Handle _handle; + std::string _name; }; } // namespace DsVeosCoSim diff --git a/src/OsAbstraction/NamedMutex.cpp b/src/OsAbstraction/NamedMutex.cpp index 239371b..a3ceed3 100644 --- a/src/OsAbstraction/NamedMutex.cpp +++ b/src/OsAbstraction/NamedMutex.cpp @@ -5,6 +5,8 @@ #include "NamedMutex.h" #include +#include +#include #include "CoSimHelper.h" #include "OsUtilities.h" @@ -13,8 +15,8 @@ namespace DsVeosCoSim { namespace { -[[nodiscard]] std::wstring GetFullNamedMutexName(std::string_view name) { - return Utf8ToWide("Local\\dSPACE.VEOS.CoSim.Mutex." + std::string(name)); +[[nodiscard]] std::wstring GetFullNamedMutexName(const std::string& name) { + return Utf8ToWide("Local\\dSPACE.VEOS.CoSim.Mutex." + name); } } // namespace @@ -22,27 +24,27 @@ namespace { NamedMutex::NamedMutex(Handle handle) : _handle(std::move(handle)) { } -NamedMutex NamedMutex::CreateOrOpen(std::string_view name) { +[[nodiscard]] NamedMutex NamedMutex::CreateOrOpen(const std::string& name) { std::wstring fullName = GetFullNamedMutexName(name); void* handle = ::CreateMutexW(nullptr, FALSE, fullName.c_str()); if (!handle) { - throw CoSimException("Could not create or open mutex '" + std::string(name) + "'.", GetLastWindowsError()); + throw CoSimException("Could not create or open mutex '" + name + "'.", GetLastWindowsError()); } return NamedMutex(handle); } -NamedMutex NamedMutex::OpenExisting(std::string_view name) { +[[nodiscard]] NamedMutex NamedMutex::OpenExisting(const std::string& name) { std::wstring fullName = GetFullNamedMutexName(name); void* handle = ::OpenMutexW(MUTEX_ALL_ACCESS, FALSE, fullName.c_str()); if (!handle) { - throw CoSimException("Could not open mutex '" + std::string(name) + "'.", GetLastWindowsError()); + throw CoSimException("Could not open mutex '" + name + "'.", GetLastWindowsError()); } return NamedMutex(handle); } -std::optional NamedMutex::TryOpenExisting(std::string_view name) { +[[nodiscard]] std::optional NamedMutex::TryOpenExisting(const std::string& name) { std::wstring fullName = GetFullNamedMutexName(name); void* handle = ::OpenMutexW(MUTEX_ALL_ACCESS, FALSE, fullName.c_str()); if (!handle) { @@ -56,7 +58,7 @@ void NamedMutex::lock() const { (void)lock(Infinite); } -bool NamedMutex::lock(uint32_t milliseconds) const { +[[nodiscard]] bool NamedMutex::lock(uint32_t milliseconds) const { return _handle.Wait(milliseconds); } diff --git a/src/OsAbstraction/NamedMutex.h b/src/OsAbstraction/NamedMutex.h index 300c686..076f6ed 100644 --- a/src/OsAbstraction/NamedMutex.h +++ b/src/OsAbstraction/NamedMutex.h @@ -6,7 +6,7 @@ #include #include -#include +#include #include "Handle.h" @@ -25,9 +25,9 @@ class NamedMutex final { NamedMutex(NamedMutex&&) noexcept = default; NamedMutex& operator=(NamedMutex&&) noexcept = default; - [[nodiscard]] static NamedMutex CreateOrOpen(std::string_view name); - [[nodiscard]] static NamedMutex OpenExisting(std::string_view name); - [[nodiscard]] static std::optional TryOpenExisting(std::string_view name); + [[nodiscard]] static NamedMutex CreateOrOpen(const std::string& name); + [[nodiscard]] static NamedMutex OpenExisting(const std::string& name); + [[nodiscard]] static std::optional TryOpenExisting(const std::string& name); // Small case, so this mutex can directly be used in std::lock_guard void lock() const; // NOLINT(readability-identifier-naming) diff --git a/src/OsAbstraction/OsUtilities.cpp b/src/OsAbstraction/OsUtilities.cpp index 1c824f7..df0aa81 100644 --- a/src/OsAbstraction/OsUtilities.cpp +++ b/src/OsAbstraction/OsUtilities.cpp @@ -11,7 +11,7 @@ namespace DsVeosCoSim { -std::wstring Utf8ToWide(std::string_view utf8String) { +[[nodiscard]] std::wstring Utf8ToWide(std::string_view utf8String) { if (utf8String.empty()) { return {}; } @@ -30,11 +30,11 @@ std::wstring Utf8ToWide(std::string_view utf8String) { return wideString; } -int32_t GetLastWindowsError() { +[[nodiscard]] int32_t GetLastWindowsError() { return static_cast(::GetLastError()); } -uint32_t GetCurrentProcessId() { +[[nodiscard]] uint32_t GetCurrentProcessId() { static uint32_t processId{}; if (processId == 0) { processId = static_cast(::GetCurrentProcessId()); @@ -43,7 +43,7 @@ uint32_t GetCurrentProcessId() { return processId; } -bool IsProcessRunning(uint32_t processId) { +[[nodiscard]] bool IsProcessRunning(uint32_t processId) { void* processHandle = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, processId); if (processHandle == nullptr) { return false; diff --git a/src/OsAbstraction/SharedMemory.cpp b/src/OsAbstraction/SharedMemory.cpp index cbbfdc7..f9e1c23 100644 --- a/src/OsAbstraction/SharedMemory.cpp +++ b/src/OsAbstraction/SharedMemory.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include "CoSimHelper.h" #include "OsUtilities.h" @@ -16,26 +15,22 @@ namespace DsVeosCoSim { namespace { -[[nodiscard]] std::wstring GetFullSharedMemoryName(std::string_view name) { - return Utf8ToWide("Local\\dSPACE.VEOS.CoSim.SharedMemory." + std::string(name)); +[[nodiscard]] std::wstring GetFullSharedMemoryName(const std::string& name) { + return Utf8ToWide("Local\\dSPACE.VEOS.CoSim.SharedMemory." + name); } } // namespace -SharedMemory::SharedMemory(std::string_view name, size_t size, Handle handle) - : _size(size), _handle(std::move(handle)) { - _data = ::MapViewOfFile(_handle, FILE_MAP_ALL_ACCESS, 0, 0, _size); +SharedMemory::SharedMemory(const std::string& name, size_t size, Handle handle) + : _size(size), _handle(std::move(handle)), _data(::MapViewOfFile(_handle, FILE_MAP_ALL_ACCESS, 0, 0, _size)) { if (!_data) { (void)::CloseHandle(_handle); - throw CoSimException("Could not map view of shared memory '" + std::string(name) + "'.", GetLastWindowsError()); + throw CoSimException("Could not map view of shared memory '" + name + "'.", GetLastWindowsError()); } } -SharedMemory::SharedMemory(SharedMemory&& sharedMemory) noexcept { - _size = sharedMemory._size; - _handle = std::move(sharedMemory._handle); - _data = sharedMemory._data; - +SharedMemory::SharedMemory(SharedMemory&& sharedMemory) noexcept + : _size(sharedMemory._size), _handle(std::move(sharedMemory._handle)), _data(sharedMemory._data) { sharedMemory._size = {}; sharedMemory._data = {}; } @@ -51,31 +46,30 @@ SharedMemory& SharedMemory::operator=(SharedMemory&& sharedMemory) noexcept { return *this; } -SharedMemory SharedMemory::CreateOrOpen(std::string_view name, size_t size) { +[[nodiscard]] SharedMemory SharedMemory::CreateOrOpen(const std::string& name, size_t size) { std::wstring fullName = GetFullSharedMemoryName(name); DWORD sizeHigh = 0U; auto sizeLow = static_cast(size); void* handle = ::CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, sizeHigh, sizeLow, fullName.c_str()); if (!handle) { - throw CoSimException("Could not create or open shared memory '" + std::string(name) + "'.", - GetLastWindowsError()); + throw CoSimException("Could not create or open shared memory '" + name + "'.", GetLastWindowsError()); } return {name, size, handle}; } -SharedMemory SharedMemory::OpenExisting(std::string_view name, size_t size) { +[[nodiscard]] SharedMemory SharedMemory::OpenExisting(const std::string& name, size_t size) { std::wstring fullName = GetFullSharedMemoryName(name); void* handle = ::OpenFileMappingW(FILE_MAP_WRITE, FALSE, fullName.c_str()); if (!handle) { - throw CoSimException("Could not open shared memory '" + std::string(name) + "'.", GetLastWindowsError()); + throw CoSimException("Could not open shared memory '" + name + "'.", GetLastWindowsError()); } return {name, size, handle}; } -std::optional SharedMemory::TryOpenExisting(std::string_view name, size_t size) { +[[nodiscard]] std::optional SharedMemory::TryOpenExisting(const std::string& name, size_t size) { std::wstring fullName = GetFullSharedMemoryName(name); void* handle = ::OpenFileMappingW(FILE_MAP_WRITE, FALSE, fullName.c_str()); if (!handle) { @@ -85,11 +79,11 @@ std::optional SharedMemory::TryOpenExisting(std::string_view name, return SharedMemory(name, size, handle); } -void* SharedMemory::data() const noexcept { +[[nodiscard]] void* SharedMemory::data() const noexcept { return _data; } -size_t SharedMemory::size() const noexcept { +[[nodiscard]] size_t SharedMemory::size() const noexcept { return _size; } diff --git a/src/OsAbstraction/SharedMemory.h b/src/OsAbstraction/SharedMemory.h index 78c5b68..3aedf89 100644 --- a/src/OsAbstraction/SharedMemory.h +++ b/src/OsAbstraction/SharedMemory.h @@ -6,14 +6,14 @@ #include #include -#include +#include #include "Handle.h" namespace DsVeosCoSim { class SharedMemory final { - SharedMemory(std::string_view name, size_t size, Handle handle); + SharedMemory(const std::string& name, size_t size, Handle handle); public: SharedMemory() = default; @@ -25,9 +25,9 @@ class SharedMemory final { SharedMemory(SharedMemory&&) noexcept; SharedMemory& operator=(SharedMemory&&) noexcept; - [[nodiscard]] static SharedMemory CreateOrOpen(std::string_view name, size_t size); - [[nodiscard]] static SharedMemory OpenExisting(std::string_view name, size_t size); - [[nodiscard]] static std::optional TryOpenExisting(std::string_view name, size_t size); + [[nodiscard]] static SharedMemory CreateOrOpen(const std::string& name, size_t size); + [[nodiscard]] static SharedMemory OpenExisting(const std::string& name, size_t size); + [[nodiscard]] static std::optional TryOpenExisting(const std::string& name, size_t size); [[nodiscard]] void* data() const noexcept; // NOLINT(readability-identifier-naming) [[nodiscard]] size_t size() const noexcept; // NOLINT(readability-identifier-naming) diff --git a/src/OsAbstraction/Socket.cpp b/src/OsAbstraction/Socket.cpp index 2b8c9ea..c072c02 100644 --- a/src/OsAbstraction/Socket.cpp +++ b/src/OsAbstraction/Socket.cpp @@ -2,6 +2,9 @@ #include "Socket.h" +#include +#include + #include "CoSimHelper.h" #ifdef _WIN32 @@ -12,6 +15,7 @@ #include #else #include +#include #include #include #include @@ -25,7 +29,6 @@ #include #include #include -#include #endif #ifdef _WIN32 @@ -54,13 +57,13 @@ constexpr int32_t ErrorCodeConnectionAborted = ECONNABORTED; constexpr int32_t ErrorCodeConnectionReset = ECONNRESET; #endif -[[nodiscard]] std::string GetUdsPath(std::string_view name) { +[[nodiscard]] std::string GetUdsPath(const std::string& name) { #ifdef _WIN32 fs::path tempDir = fs::temp_directory_path(); - fs::path fileDir = tempDir / ("dSPACE.VEOS.CoSim." + std::string(name)); + fs::path fileDir = tempDir / ("dSPACE.VEOS.CoSim." + name); return fileDir.string(); #else - return "dSPACE.VEOS.CoSim." + std::string(name); + return "dSPACE.VEOS.CoSim." + name; #endif } @@ -75,10 +78,10 @@ constexpr int32_t ErrorCodeConnectionReset = ECONNRESET; return static_cast(largeInteger.QuadPart / 10000); #else - timeval tv{}; - (void)::gettimeofday(&tv, nullptr); + timeval currentTime{}; + (void)::gettimeofday(¤tTime, nullptr); - return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); + return (currentTime.tv_sec * 1000) + (currentTime.tv_usec / 1000); #endif } @@ -113,13 +116,13 @@ constexpr int32_t ErrorCodeConnectionReset = ECONNRESET; socketAddress.port = ::ntohs(ipv4Address.sin_port); if (ipv4Address.sin_addr.s_addr != 0) { - char ipAddressArray[INET_ADDRSTRLEN]{}; - const char* result = ::inet_ntop(AF_INET, &ipv4Address.sin_addr.s_addr, ipAddressArray, INET_ADDRSTRLEN); + std::string ipAddress(INET_ADDRSTRLEN, '\0'); + const char* result = ::inet_ntop(AF_INET, &ipv4Address.sin_addr.s_addr, ipAddress.data(), INET_ADDRSTRLEN); if (!result) { throw CoSimException("Could not get address information.", GetLastNetworkError()); } - socketAddress.ipAddress = ipAddressArray; + socketAddress.ipAddress = ipAddress; } else { socketAddress.ipAddress = "127.0.0.1"; } @@ -131,13 +134,13 @@ constexpr int32_t ErrorCodeConnectionReset = ECONNRESET; SocketAddress socketAddress; socketAddress.port = ::ntohs(ipv6Address.sin6_port); - char ipAddressArray[INET6_ADDRSTRLEN]{}; - const char* result = ::inet_ntop(AF_INET6, &ipv6Address.sin6_addr, ipAddressArray, INET6_ADDRSTRLEN); + std::string ipAddress(INET6_ADDRSTRLEN, '\0'); + const char* result = ::inet_ntop(AF_INET6, &ipv6Address.sin6_addr, ipAddress.data(), INET6_ADDRSTRLEN); if (!result) { throw CoSimException("Could not get address information.", GetLastNetworkError()); } - socketAddress.ipAddress = ipAddressArray; + socketAddress.ipAddress = ipAddress; return socketAddress; } @@ -218,10 +221,10 @@ void SwitchToBlockingMode(const socket_t& socket) { #endif } -bool ConnectWithTimeout(socket_t& socket, - const sockaddr* socketAddress, - socklen_t sizeOfSocketAddress, - uint32_t timeoutInMilliseconds) { +[[nodiscard]] bool ConnectWithTimeout(socket_t& socket, + const sockaddr* socketAddress, + socklen_t sizeOfSocketAddress, + uint32_t timeoutInMilliseconds) { SwitchToNonBlockingMode(socket); if (::connect(socket, socketAddress, sizeOfSocketAddress) >= 0) { @@ -272,26 +275,25 @@ void StartupNetwork() { #endif } -Socket::Socket(AddressFamily addressFamily) { - _addressFamily = addressFamily; +Socket::Socket(AddressFamily addressFamily) : _addressFamily(addressFamily) { int32_t protocol{}; - int32_t af{}; + int32_t domain{}; switch (addressFamily) { case AddressFamily::Ipv4: protocol = IPPROTO_TCP; - af = AF_INET; + domain = AF_INET; break; case AddressFamily::Ipv6: protocol = IPPROTO_TCP; - af = AF_INET6; + domain = AF_INET6; break; case AddressFamily::Uds: protocol = 0; - af = AF_UNIX; + domain = AF_UNIX; break; } - _socket = ::socket(af, SOCK_STREAM, protocol); + _socket = ::socket(domain, SOCK_STREAM, protocol); if (_socket == InvalidSocket) { throw CoSimException("Could not create socket.", GetLastNetworkError()); @@ -308,9 +310,9 @@ Socket::~Socket() noexcept { Socket::Socket(Socket&& other) noexcept { Close(); - _socket = other._socket; - _addressFamily = other._addressFamily; - _path = other._path; + _socket = other._socket; // NOLINT(cppcoreguidelines-prefer-member-initializer) + _addressFamily = other._addressFamily; // NOLINT(cppcoreguidelines-prefer-member-initializer) + _path = other._path; // NOLINT(cppcoreguidelines-prefer-member-initializer) other._socket = InvalidSocket; other._addressFamily = {}; @@ -331,7 +333,7 @@ Socket& Socket::operator=(Socket&& other) noexcept { return *this; } -bool Socket::IsIpv4Supported() { +[[nodiscard]] bool Socket::IsIpv4Supported() { static bool hasValue = false; static bool isSupported = false; @@ -347,7 +349,7 @@ bool Socket::IsIpv4Supported() { return isSupported; } -bool Socket::IsIpv6Supported() { +[[nodiscard]] bool Socket::IsIpv6Supported() { static bool hasValue = false; static bool isSupported = false; @@ -363,7 +365,7 @@ bool Socket::IsIpv6Supported() { return isSupported; } -bool Socket::IsUdsSupported() { +[[nodiscard]] bool Socket::IsUdsSupported() { static bool hasValue = false; static bool isSupported = false; @@ -410,11 +412,11 @@ void Socket::Close() { CloseSocket(socket); } -bool Socket::IsValid() const { +[[nodiscard]] bool Socket::IsValid() const { return _socket != InvalidSocket; } -void Socket::EnableIpv6Only() const { // NOLINT +void Socket::EnableIpv6Only() const { // On windows, IPv6 only is enabled by default #ifndef _WIN32 int32_t flags = 1; @@ -428,10 +430,10 @@ void Socket::EnableIpv6Only() const { // NOLINT #endif } -std::optional Socket::TryConnect(std::string_view ipAddress, - uint16_t remotePort, - uint16_t localPort, - uint32_t timeoutInMilliseconds) { +[[nodiscard]] std::optional Socket::TryConnect(std::string_view ipAddress, + uint16_t remotePort, + uint16_t localPort, + uint32_t timeoutInMilliseconds) { if (remotePort == 0) { throw CoSimException("Remote port 0 is not valid."); } @@ -477,7 +479,7 @@ std::optional Socket::TryConnect(std::string_view ipAddress, return {}; } -bool Socket::TryConnect(std::string_view name) const { +[[nodiscard]] bool Socket::TryConnect(const std::string& name) const { EnsureIsValid(); if (_addressFamily != AddressFamily::Uds) { @@ -537,7 +539,7 @@ void Socket::BindForIpv6(uint16_t port, bool enableRemoteAccess) const { } } -void Socket::Bind(std::string_view name) { +void Socket::Bind(const std::string& name) { EnsureIsValid(); if (_addressFamily != AddressFamily::Uds) { @@ -596,7 +598,7 @@ void Socket::Listen() const { } } -std::optional Socket::TryAccept(uint32_t timeoutInMilliseconds) const { +[[nodiscard]] std::optional Socket::TryAccept(uint32_t timeoutInMilliseconds) const { EnsureIsValid(); if (!Poll(_socket, POLLRDNORM, timeoutInMilliseconds)) { @@ -611,7 +613,7 @@ std::optional Socket::TryAccept(uint32_t timeoutInMilliseconds) const { return Socket(socket, _addressFamily); } -uint16_t Socket::GetLocalPort() const { +[[nodiscard]] uint16_t Socket::GetLocalPort() const { EnsureIsValid(); if (_addressFamily == AddressFamily::Ipv4) { @@ -625,7 +627,7 @@ uint16_t Socket::GetLocalPort() const { return 0; } -uint16_t Socket::GetLocalPortForIpv4() const { +[[nodiscard]] uint16_t Socket::GetLocalPortForIpv4() const { sockaddr_in address{}; auto addressLength = static_cast(sizeof(address)); address.sin_family = AF_INET; @@ -638,7 +640,7 @@ uint16_t Socket::GetLocalPortForIpv4() const { return socketAddress.port; } -uint16_t Socket::GetLocalPortForIpv6() const { +[[nodiscard]] uint16_t Socket::GetLocalPortForIpv6() const { sockaddr_in6 address{}; auto addressLength = static_cast(sizeof(address)); address.sin6_family = AF_INET6; @@ -651,7 +653,7 @@ uint16_t Socket::GetLocalPortForIpv6() const { return socketAddress.port; } -SocketAddress Socket::GetRemoteAddress() const { +[[nodiscard]] SocketAddress Socket::GetRemoteAddress() const { EnsureIsValid(); if (_addressFamily == AddressFamily::Ipv4) { @@ -665,7 +667,7 @@ SocketAddress Socket::GetRemoteAddress() const { return {"127.0.0.1", 0}; } -SocketAddress Socket::GetRemoteAddressForIpv4() const { +[[nodiscard]] SocketAddress Socket::GetRemoteAddressForIpv4() const { sockaddr_in address{}; auto addressLength = static_cast(sizeof(address)); address.sin_family = AF_INET; @@ -677,7 +679,7 @@ SocketAddress Socket::GetRemoteAddressForIpv4() const { return ConvertFromInternetAddress(address); } -SocketAddress Socket::GetRemoteAddressForIpv6() const { +[[nodiscard]] SocketAddress Socket::GetRemoteAddressForIpv6() const { sockaddr_in6 address{}; auto addressLength = static_cast(sizeof(address)); address.sin6_family = AF_INET6; @@ -693,7 +695,7 @@ SocketAddress Socket::GetRemoteAddressForIpv6() const { return ConvertFromInternetAddress(address); } -bool Socket::Receive(void* destination, int32_t size, int32_t& receivedSize) const { +[[nodiscard]] bool Socket::Receive(void* destination, int32_t size, int32_t& receivedSize) const { #ifdef _WIN32 receivedSize = ::recv(_socket, static_cast(destination), size, 0); #else @@ -724,7 +726,7 @@ bool Socket::Receive(void* destination, int32_t size, int32_t& receivedSize) con return false; } -bool Socket::Send(const void* source, int32_t size, int32_t& sentSize) const { +[[nodiscard]] bool Socket::Send(const void* source, int32_t size, int32_t& sentSize) const { #ifdef _WIN32 sentSize = ::send(_socket, static_cast(source), size, 0); #else diff --git a/src/OsAbstraction/Socket.h b/src/OsAbstraction/Socket.h index 68b8586..c3708ec 100644 --- a/src/OsAbstraction/Socket.h +++ b/src/OsAbstraction/Socket.h @@ -17,7 +17,7 @@ enum class AddressFamily { Ipv6 = 23 }; -[[nodiscard]] inline std::string_view ToString(AddressFamily addressFamily) { +[[nodiscard]] inline std::string ToString(AddressFamily addressFamily) { switch (addressFamily) { case DsVeosCoSim::AddressFamily::Ipv4: return "Ipv4"; @@ -60,9 +60,9 @@ class Socket { Socket(Socket&&) noexcept; Socket& operator=(Socket&&) noexcept; - static bool IsIpv4Supported(); - static bool IsIpv6Supported(); - static bool IsUdsSupported(); + [[nodiscard]] static bool IsIpv4Supported(); + [[nodiscard]] static bool IsIpv6Supported(); + [[nodiscard]] static bool IsUdsSupported(); void Shutdown() const; void Close(); @@ -74,10 +74,10 @@ class Socket { uint16_t localPort, uint32_t timeoutInMilliseconds); - [[nodiscard]] bool TryConnect(std::string_view name) const; + [[nodiscard]] bool TryConnect(const std::string& name) const; void EnableIpv6Only() const; void Bind(uint16_t port, bool enableRemoteAccess) const; - void Bind(std::string_view name); + void Bind(const std::string& name); void EnableReuseAddress() const; void EnableNoDelay() const; void Listen() const; diff --git a/src/PortMapper.cpp b/src/PortMapper.cpp index 8894c29..7f48b99 100644 --- a/src/PortMapper.cpp +++ b/src/PortMapper.cpp @@ -2,7 +2,10 @@ #include "PortMapper.h" +#include + #include "CoSimHelper.h" +#include "Environment.h" #include "Protocol.h" #include "SocketChannel.h" @@ -12,49 +15,6 @@ namespace { constexpr uint32_t ClientTimeoutInMilliseconds = 1000; -bool IsPortMapperServerVerbose() { - constexpr bool defaultVerbose = false; - - const char* verboseString = std::getenv("VEOS_COSIM_PORTMAPPER_SERVER_VERBOSE"); // NOLINT(concurrency-mt-unsafe) - if (verboseString) { - const int32_t verbose = std::atoi(verboseString); // NOLINT(cert-err34-c) - return verbose != 0; - } - - return defaultVerbose; -} - -bool IsPortMapperClientVerbose() { - constexpr bool defaultVerbose = false; - - const char* verboseString = std::getenv("VEOS_COSIM_PORTMAPPER_CLIENT_VERBOSE"); // NOLINT(concurrency-mt-unsafe) - if (verboseString) { - const int32_t verbose = std::atoi(verboseString); // NOLINT(cert-err34-c) - return verbose != 0; - } - - return defaultVerbose; -} - -[[nodiscard]] uint16_t GetPortMapperPortInitial() { - constexpr uint16_t defaultPort = 27027; - - const char* portString = std::getenv("VEOS_COSIM_PORTMAPPER_PORT"); // NOLINT(concurrency-mt-unsafe) - if (portString) { - const int32_t port = std::atoi(portString); // NOLINT(cert-err34-c) - if (port > 0 && port <= UINT16_MAX) { - return static_cast(port); - } - } - - return defaultPort; -} - -uint16_t GetPortMapperPort() { - static uint16_t port = GetPortMapperPortInitial(); - return port; -} - } // namespace PortMapperServer::PortMapperServer(bool enableRemoteAccess) : _server(GetPortMapperPort(), enableRemoteAccess) { @@ -86,11 +46,11 @@ void PortMapperServer::RunPortMapperServer() { } } -bool PortMapperServer::HandleClient(Channel& channel) { +[[nodiscard]] bool PortMapperServer::HandleClient(Channel& channel) { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(channel.GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::GetPort: CheckResultWithMessage(HandleGetPort(channel), "Could not handle get port request."); return true; @@ -105,7 +65,7 @@ bool PortMapperServer::HandleClient(Channel& channel) { } } -bool PortMapperServer::HandleGetPort(Channel& channel) { +[[nodiscard]] bool PortMapperServer::HandleGetPort(Channel& channel) { std::string name; CheckResultWithMessage(Protocol::ReadGetPort(channel.GetReader(), name), "Could not read get port frame."); @@ -126,7 +86,7 @@ bool PortMapperServer::HandleGetPort(Channel& channel) { return true; } -bool PortMapperServer::HandleSetPort(Channel& channel) { +[[nodiscard]] bool PortMapperServer::HandleSetPort(Channel& channel) { std::string name; uint16_t port = 0; CheckResultWithMessage(Protocol::ReadSetPort(channel.GetReader(), name, port), "Could not read set port frame."); @@ -145,7 +105,7 @@ bool PortMapperServer::HandleSetPort(Channel& channel) { return true; } -bool PortMapperServer::HandleUnsetPort(Channel& channel) { +[[nodiscard]] bool PortMapperServer::HandleUnsetPort(Channel& channel) { std::string name; CheckResultWithMessage(Protocol::ReadUnsetPort(channel.GetReader(), name), "Could not read unset port frame."); @@ -175,10 +135,9 @@ void PortMapperServer::DumpEntries() { } } -bool PortMapper_GetPort(std::string_view ipAddress, std::string_view serverName, uint16_t& port) { +[[nodiscard]] bool PortMapper_GetPort(const std::string& ipAddress, const std::string& serverName, uint16_t& port) { if (IsPortMapperClientVerbose()) { - LogTrace("PortMapper_GetPort(ipAddress: '" + std::string(ipAddress) + "', serverName: '" + - std::string(serverName) + "')"); + LogTrace("PortMapper_GetPort(ipAddress: '" + ipAddress + "', serverName: '" + serverName + "')"); } std::optional channel = @@ -190,7 +149,7 @@ bool PortMapper_GetPort(std::string_view ipAddress, std::string_view serverName, FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::GetPortOk: { CheckResultWithMessage(Protocol::ReadGetPortOk(channel->GetReader(), port), "Could not receive port ok frame."); @@ -207,7 +166,7 @@ bool PortMapper_GetPort(std::string_view ipAddress, std::string_view serverName, } } -bool PortMapper_SetPort(std::string_view name, uint16_t port) { +[[nodiscard]] bool PortMapper_SetPort(const std::string& name, uint16_t port) { std::optional channel = TryConnectToTcpChannel("127.0.0.1", GetPortMapperPort(), 0, ClientTimeoutInMilliseconds); CheckResultWithMessage(channel, "Could not connect to port mapper."); @@ -217,7 +176,7 @@ bool PortMapper_SetPort(std::string_view name, uint16_t port) { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::Ok: return true; case FrameKind::Error: { @@ -231,7 +190,7 @@ bool PortMapper_SetPort(std::string_view name, uint16_t port) { } } -bool PortMapper_UnsetPort(std::string_view name) { +[[nodiscard]] bool PortMapper_UnsetPort(const std::string& name) { std::optional channel = TryConnectToTcpChannel("127.0.0.1", GetPortMapperPort(), 0, ClientTimeoutInMilliseconds); CheckResultWithMessage(channel, "Could not connect to port mapper."); @@ -241,7 +200,7 @@ bool PortMapper_UnsetPort(std::string_view name) { FrameKind frameKind{}; CheckResult(Protocol::ReceiveHeader(channel->GetReader(), frameKind)); - switch (frameKind) { // NOLINT(clang-diagnostic-switch-enum) + switch (frameKind) { case FrameKind::Ok: return true; case FrameKind::Error: { diff --git a/src/PortMapper.h b/src/PortMapper.h index 232e0d6..ef76724 100644 --- a/src/PortMapper.h +++ b/src/PortMapper.h @@ -3,6 +3,7 @@ #pragma once #include +#include #include #include @@ -37,8 +38,8 @@ class PortMapperServer { Event _stopEvent; }; -[[nodiscard]] bool PortMapper_GetPort(std::string_view ipAddress, std::string_view serverName, uint16_t& port); -[[nodiscard]] bool PortMapper_SetPort(std::string_view name, uint16_t port); -[[nodiscard]] bool PortMapper_UnsetPort(std::string_view name); +[[nodiscard]] bool PortMapper_GetPort(const std::string& ipAddress, const std::string& serverName, uint16_t& port); +[[nodiscard]] bool PortMapper_SetPort(const std::string& name, uint16_t port); +[[nodiscard]] bool PortMapper_UnsetPort(const std::string& name); } // namespace DsVeosCoSim diff --git a/src/Protocol.cpp b/src/Protocol.cpp index ea02993..df27227 100644 --- a/src/Protocol.cpp +++ b/src/Protocol.cpp @@ -3,6 +3,8 @@ #include "Protocol.h" #include +#include +#include #include "CoSimHelper.h" @@ -208,83 +210,177 @@ namespace { namespace Protocol { -bool ReceiveHeader(ChannelReader& reader, FrameKind& frameKind) { +[[nodiscard]] bool ReceiveHeader(ChannelReader& reader, FrameKind& frameKind) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReceiveHeader()"); +#endif + CheckResultWithMessage(reader.Read(frameKind), "Could not receive frame header."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReceiveHeader(FrameKind: " + ToString(frameKind) + ")"); +#endif + return true; } -bool SendOk(ChannelWriter& writer) { +[[nodiscard]] bool SendOk(ChannelWriter& writer) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendOk()"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Ok)); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendOk()"); +#endif + return true; } -bool SendError(ChannelWriter& writer, std::string_view errorStr) { +[[nodiscard]] bool SendError(ChannelWriter& writer, const std::string& errorMessage) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendError(ErrorMessage: \"" + errorMessage + "\")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Error)); - CheckResultWithMessage(WriteString(writer, errorStr), "Could not write error message."); + CheckResultWithMessage(WriteString(writer, errorMessage), "Could not write error message."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendError()"); +#endif + return true; } -bool ReadError(ChannelReader& reader, std::string& errorStr) { - CheckResultWithMessage(ReadString(reader, errorStr), "Could not read error message."); +[[nodiscard]] bool ReadError(ChannelReader& reader, std::string& errorMessage) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadError()"); +#endif + + CheckResultWithMessage(ReadString(reader, errorMessage), "Could not read error message."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadError(ErrorMessage: \"" + errorMessage + "\")"); +#endif + return true; } -bool SendPing(ChannelWriter& writer) { +[[nodiscard]] bool SendPing(ChannelWriter& writer) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendPing()"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Ping)); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendPing()"); +#endif + return true; } -bool SendPingOk(ChannelWriter& writer, Command command) { +[[nodiscard]] bool SendPingOk(ChannelWriter& writer, Command command) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendPingOk(Command: " + ToString(command) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::PingOk)); CheckResultWithMessage(writer.Write(command), "Could not write command."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendPingOk()"); +#endif + return true; } -bool ReadPingOk(ChannelReader& reader, Command& command) { +[[nodiscard]] bool ReadPingOk(ChannelReader& reader, Command& command) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadPingOk()"); +#endif + CheckResultWithMessage(reader.Read(command), "Could not read command."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadPingOk(Command: " + ToString(command) + ")"); +#endif + return true; } -bool SendConnect(ChannelWriter& writer, - uint32_t protocolVersion, - Mode clientMode, - std::string_view serverName, - std::string_view clientName) { +[[nodiscard]] bool SendConnect(ChannelWriter& writer, + uint32_t protocolVersion, + Mode clientMode, + const std::string& serverName, + const std::string& clientName) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendConnect(ProtocolVersion: " + std::to_string(protocolVersion) + + ", ClientMode: " + ToString(clientMode) + ", ServerName: \"" + serverName + + "\", ClientName: \"" + clientName + "\")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Connect)); CheckResultWithMessage(writer.Write(protocolVersion), "Could not write protocol version."); CheckResultWithMessage(writer.Write(clientMode), "Could not write client mode."); CheckResultWithMessage(WriteString(writer, serverName), "Could not write server name."); CheckResultWithMessage(WriteString(writer, clientName), "Could not write client name."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendConnect()"); +#endif + return true; } -bool ReadConnect(ChannelReader& reader, - uint32_t& protocolVersion, - Mode& clientMode, - std::string& serverName, - std::string& clientName) { +[[nodiscard]] bool ReadConnect(ChannelReader& reader, + uint32_t& protocolVersion, + Mode& clientMode, + std::string& serverName, + std::string& clientName) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadConnect()"); +#endif + CheckResultWithMessage(reader.Read(protocolVersion), "Could not read protocol version."); CheckResultWithMessage(reader.Read(clientMode), "Could not read client mode."); CheckResultWithMessage(ReadString(reader, serverName), "Could not read server name."); CheckResultWithMessage(ReadString(reader, clientName), "Could not read client name."); - return true; -} -bool SendConnectOk(ChannelWriter& writer, - uint32_t protocolVersion, - Mode clientMode, - DsVeosCoSim_SimulationTime stepSize, - SimulationState simulationState, - const std::vector& incomingSignals, - const std::vector& outgoingSignals, - const std::vector& canControllers, - const std::vector& ethControllers, - const std::vector& linControllers) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadConnect(ProtocolVersion: " + std::to_string(protocolVersion) + + ", ClientMode: " + ToString(clientMode) + ", ServerName: \"" + serverName + + "\", ClientName: \"" + clientName + "\")"); +#endif + + return true; +} + +[[nodiscard]] bool SendConnectOk(ChannelWriter& writer, + uint32_t protocolVersion, + Mode clientMode, + DsVeosCoSim_SimulationTime stepSize, + SimulationState simulationState, + const std::vector& incomingSignals, + const std::vector& outgoingSignals, + const std::vector& canControllers, + const std::vector& ethControllers, + const std::vector& linControllers) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace( + "SendConnectOk(ProtocolVersion: " + std::to_string(protocolVersion) + ", ClientMode: " + ToString(clientMode) + + ", StepSize: " + SimulationTimeToString(stepSize) + ", SimulationState: " + ToString(simulationState) + + ", IncomingSignals: " + ToString(incomingSignals) + ", OutgoingSignals: " + ToString(outgoingSignals) + + ", CanControllers: " + ToString(canControllers) + ", EthControllers: " + ToString(ethControllers) + + ", LinControllers: " + ToString(linControllers) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::ConnectOk)); CheckResultWithMessage(writer.Write(protocolVersion), "Could not write protocol version."); CheckResultWithMessage(writer.Write(clientMode), "Could not write client mode."); @@ -296,19 +392,28 @@ bool SendConnectOk(ChannelWriter& writer, CheckResultWithMessage(WriteControllerInfos(writer, ethControllers), "Could not write ETH controllers."); CheckResultWithMessage(WriteControllerInfos(writer, linControllers), "Could not write LIN controllers."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendConnectOk()"); +#endif + return true; } -bool ReadConnectOk(ChannelReader& reader, - uint32_t& protocolVersion, - Mode& clientMode, - DsVeosCoSim_SimulationTime& stepSize, - SimulationState& simulationState, - std::vector& incomingSignals, - std::vector& outgoingSignals, - std::vector& canControllers, - std::vector& ethControllers, - std::vector& linControllers) { +[[nodiscard]] bool ReadConnectOk(ChannelReader& reader, + uint32_t& protocolVersion, + Mode& clientMode, + DsVeosCoSim_SimulationTime& stepSize, + SimulationState& simulationState, + std::vector& incomingSignals, + std::vector& outgoingSignals, + std::vector& canControllers, + std::vector& ethControllers, + std::vector& linControllers) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadConnectOk()"); +#endif + CheckResultWithMessage(reader.Read(protocolVersion), "Could not read protocol version."); CheckResultWithMessage(reader.Read(clientMode), "Could not read client mode."); CheckResultWithMessage(reader.Read(stepSize), "Could not read step size."); @@ -318,92 +423,207 @@ bool ReadConnectOk(ChannelReader& reader, CheckResultWithMessage(ReadControllerInfos(reader, canControllers), "Could not read CAN controllers."); CheckResultWithMessage(ReadControllerInfos(reader, ethControllers), "Could not read ETH controllers."); CheckResultWithMessage(ReadControllerInfos(reader, linControllers), "Could not read LIN controllers."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace( + "ReadConnectOk(ProtocolVersion: " + std::to_string(protocolVersion) + ", ClientMode: " + ToString(clientMode) + + ", StepSize: " + SimulationTimeToString(stepSize) + ", SimulationState: " + ToString(simulationState) + + ", IncomingSignals: " + ToString(incomingSignals) + ", OutgoingSignals: " + ToString(outgoingSignals) + + ", CanControllers: " + ToString(canControllers) + ", EthControllers: " + ToString(ethControllers) + + ", LinControllers: " + ToString(linControllers) + ")"); +#endif + return true; } -bool SendStart(ChannelWriter& writer, DsVeosCoSim_SimulationTime simulationTime) { +[[nodiscard]] bool SendStart(ChannelWriter& writer, DsVeosCoSim_SimulationTime simulationTime) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendStart(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Start)); CheckResultWithMessage(writer.Write(simulationTime), "Could not write simulation time."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendStart()"); +#endif + return true; } -bool ReadStart(ChannelReader& reader, DsVeosCoSim_SimulationTime& simulationTime) { +[[nodiscard]] bool ReadStart(ChannelReader& reader, DsVeosCoSim_SimulationTime& simulationTime) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadStart()"); +#endif + CheckResultWithMessage(reader.Read(simulationTime), "Could not read simulation time."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadStart(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + return true; } -bool SendStop(ChannelWriter& writer, DsVeosCoSim_SimulationTime simulationTime) { +[[nodiscard]] bool SendStop(ChannelWriter& writer, DsVeosCoSim_SimulationTime simulationTime) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendStop(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Stop)); CheckResultWithMessage(writer.Write(simulationTime), "Could not write simulation time."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendStop()"); +#endif + return true; } -bool ReadStop(ChannelReader& reader, DsVeosCoSim_SimulationTime& simulationTime) { +[[nodiscard]] bool ReadStop(ChannelReader& reader, DsVeosCoSim_SimulationTime& simulationTime) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadStop()"); +#endif + CheckResultWithMessage(reader.Read(simulationTime), "Could not read simulation time."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadStop(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + return true; } -bool SendTerminate(ChannelWriter& writer, - DsVeosCoSim_SimulationTime simulationTime, - DsVeosCoSim_TerminateReason reason) { +[[nodiscard]] bool SendTerminate(ChannelWriter& writer, + DsVeosCoSim_SimulationTime simulationTime, + DsVeosCoSim_TerminateReason reason) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendTerminate(SimulationTime: " + SimulationTimeToString(simulationTime) + + ", Reason: " + ToString(reason) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Terminate)); CheckResultWithMessage(writer.Write(simulationTime), "Could not write simulation time."); CheckResultWithMessage(writer.Write(reason), "Could not write reason."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendTerminate()"); +#endif + return true; } -bool ReadTerminate(ChannelReader& reader, - DsVeosCoSim_SimulationTime& simulationTime, - DsVeosCoSim_TerminateReason& reason) { +[[nodiscard]] bool ReadTerminate(ChannelReader& reader, + DsVeosCoSim_SimulationTime& simulationTime, + DsVeosCoSim_TerminateReason& reason) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadTerminate()"); +#endif + CheckResultWithMessage(reader.Read(simulationTime), "Could not read simulation time."); CheckResultWithMessage(reader.Read(reason), "Could not read reason."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadTerminate(SimulationTime: " + SimulationTimeToString(simulationTime) + + ", Reason: " + ToString(reason) + ")"); +#endif + return true; } -bool SendPause(ChannelWriter& writer, DsVeosCoSim_SimulationTime simulationTime) { +[[nodiscard]] bool SendPause(ChannelWriter& writer, DsVeosCoSim_SimulationTime simulationTime) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendPause(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Pause)); CheckResultWithMessage(writer.Write(simulationTime), "Could not write simulation time."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendPause()"); +#endif + return true; } -bool ReadPause(ChannelReader& reader, DsVeosCoSim_SimulationTime& simulationTime) { +[[nodiscard]] bool ReadPause(ChannelReader& reader, DsVeosCoSim_SimulationTime& simulationTime) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadPause()"); +#endif + CheckResultWithMessage(reader.Read(simulationTime), "Could not read simulation time."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadPause(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + return true; } -bool SendContinue(ChannelWriter& writer, DsVeosCoSim_SimulationTime simulationTime) { +[[nodiscard]] bool SendContinue(ChannelWriter& writer, DsVeosCoSim_SimulationTime simulationTime) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendContinue(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Continue)); CheckResultWithMessage(writer.Write(simulationTime), "Could not write simulation time."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendContinue()"); +#endif + return true; } -bool ReadContinue(ChannelReader& reader, DsVeosCoSim_SimulationTime& simulationTime) { +[[nodiscard]] bool ReadContinue(ChannelReader& reader, DsVeosCoSim_SimulationTime& simulationTime) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadContinue()"); +#endif + CheckResultWithMessage(reader.Read(simulationTime), "Could not read simulation time."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendStep(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + return true; } -bool SendStep(ChannelWriter& writer, - DsVeosCoSim_SimulationTime simulationTime, - const IoBuffer& ioBuffer, - const BusBuffer& busBuffer) { +[[nodiscard]] bool SendStep(ChannelWriter& writer, + DsVeosCoSim_SimulationTime simulationTime, + const IoBuffer& ioBuffer, + const BusBuffer& busBuffer) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendStep(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::Step)); CheckResultWithMessage(writer.Write(simulationTime), "Could not write simulation time."); CheckResultWithMessage(ioBuffer.Serialize(writer), "Could not write IO buffer data."); CheckResultWithMessage(busBuffer.Serialize(writer), "Could not write bus buffer data."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendStep()"); +#endif + return true; } -bool ReadStep(ChannelReader& reader, - DsVeosCoSim_SimulationTime& simulationTime, - const IoBuffer& ioBuffer, - const BusBuffer& busBuffer, - const Callbacks& callbacks) { +[[nodiscard]] bool ReadStep(ChannelReader& reader, + DsVeosCoSim_SimulationTime& simulationTime, + const IoBuffer& ioBuffer, + const BusBuffer& busBuffer, + const Callbacks& callbacks) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadStep()"); +#endif + CheckResultWithMessage(reader.Read(simulationTime), "Could not read simulation time."); if (callbacks.simulationBeginStepCallback) { @@ -412,29 +632,48 @@ bool ReadStep(ChannelReader& reader, CheckResultWithMessage(ioBuffer.Deserialize(reader, simulationTime, callbacks), "Could not read IO buffer data."); CheckResultWithMessage(busBuffer.Deserialize(reader, simulationTime, callbacks), "Could not read bus buffer data."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadStep(SimulationTime: " + SimulationTimeToString(simulationTime) + ")"); +#endif + return true; } -bool SendStepOk(ChannelWriter& writer, - DsVeosCoSim_SimulationTime nextSimulationTime, - Command command, - const IoBuffer& ioBuffer, - const BusBuffer& busBuffer) { +[[nodiscard]] bool SendStepOk(ChannelWriter& writer, + DsVeosCoSim_SimulationTime nextSimulationTime, + Command command, + const IoBuffer& ioBuffer, + const BusBuffer& busBuffer) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendStepOk(NextSimulationTime: " + SimulationTimeToString(nextSimulationTime) + + ", Command: " + ToString(command) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::StepOk)); CheckResultWithMessage(writer.Write(nextSimulationTime), "Could not write simulation time."); CheckResultWithMessage(writer.Write(command), "Could not write command."); CheckResultWithMessage(ioBuffer.Serialize(writer), "Could not write IO buffer data."); CheckResultWithMessage(busBuffer.Serialize(writer), "Could not write bus buffer data."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendStepOk()"); +#endif + return true; } -bool ReadStepOk(ChannelReader& reader, - DsVeosCoSim_SimulationTime& nextSimulationTime, - Command& command, - const IoBuffer& ioBuffer, - const BusBuffer& busBuffer, - const Callbacks& callbacks) { +[[nodiscard]] bool ReadStepOk(ChannelReader& reader, + DsVeosCoSim_SimulationTime& nextSimulationTime, + Command& command, + const IoBuffer& ioBuffer, + const BusBuffer& busBuffer, + const Callbacks& callbacks) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadStepOk()"); +#endif + CheckResultWithMessage(reader.Read(nextSimulationTime), "Could not read simulation time."); CheckResultWithMessage(reader.Read(command), "Could not read command."); @@ -446,56 +685,134 @@ bool ReadStepOk(ChannelReader& reader, "Could not read IO buffer data."); CheckResultWithMessage(busBuffer.Deserialize(reader, nextSimulationTime, callbacks), "Could not read bus buffer data."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadStepOk(NextSimulationTime: " + SimulationTimeToString(nextSimulationTime) + + ", Command: " + ToString(command) + ")"); +#endif + return true; } -bool SendSetPort(ChannelWriter& writer, std::string_view serverName, uint16_t port) { +[[nodiscard]] bool SendSetPort(ChannelWriter& writer, const std::string& serverName, uint16_t port) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendSetPort(ServerName: \"" + serverName + "\", Port: " + std::to_string(port) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::SetPort)); CheckResultWithMessage(WriteString(writer, serverName), "Could not write server name."); CheckResultWithMessage(writer.Write(port), "Could not write port."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendSetPort()"); +#endif + return true; } -bool ReadSetPort(ChannelReader& reader, std::string& serverName, uint16_t& port) { +[[nodiscard]] bool ReadSetPort(ChannelReader& reader, std::string& serverName, uint16_t& port) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadSetPort()"); +#endif + CheckResultWithMessage(ReadString(reader, serverName), "Could not read server name."); CheckResultWithMessage(reader.Read(port), "Could not read port."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadSetPort(ServerName: \"" + serverName + "\", Port: " + std::to_string(port) + ")"); +#endif + return true; } -bool SendUnsetPort(ChannelWriter& writer, std::string_view serverName) { +[[nodiscard]] bool SendUnsetPort(ChannelWriter& writer, const std::string& serverName) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendUnsetPort(ServerName: \"" + serverName + "\")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::UnsetPort)); CheckResultWithMessage(WriteString(writer, serverName), "Could not write server name."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendUnsetPort()"); +#endif + return true; } -bool ReadUnsetPort(ChannelReader& reader, std::string& serverName) { +[[nodiscard]] bool ReadUnsetPort(ChannelReader& reader, std::string& serverName) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadUnsetPort()"); +#endif + CheckResultWithMessage(ReadString(reader, serverName), "Could not read server name."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadUnsetPort(ServerName: \"" + serverName + "\")"); +#endif + return true; } -bool SendGetPort(ChannelWriter& writer, std::string_view serverName) { +[[nodiscard]] bool SendGetPort(ChannelWriter& writer, const std::string& serverName) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendGetPort(ServerName: \"" + serverName + "\")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::GetPort)); CheckResultWithMessage(WriteString(writer, serverName), "Could not write server name."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendGetPort()"); +#endif + return true; } -bool ReadGetPort(ChannelReader& reader, std::string& serverName) { +[[nodiscard]] bool ReadGetPort(ChannelReader& reader, std::string& serverName) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadGetPort()"); +#endif + CheckResultWithMessage(ReadString(reader, serverName), "Could not read server name."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadGetPort(ServerName: \"" + serverName + "\")"); +#endif + return true; } -bool SendGetPortOk(ChannelWriter& writer, uint16_t port) { +[[nodiscard]] bool SendGetPortOk(ChannelWriter& writer, uint16_t port) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("SendGetPortOk(Port: " + std::to_string(port) + ")"); +#endif + CheckResult(WriteHeader(writer, FrameKind::GetPortOk)); CheckResultWithMessage(writer.Write(port), "Could not write port."); CheckResultWithMessage(writer.EndWrite(), "Could not finish frame."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("SendGetPortOk()"); +#endif + return true; } -bool ReadGetPortOk(ChannelReader& reader, uint16_t& port) { +[[nodiscard]] bool ReadGetPortOk(ChannelReader& reader, uint16_t& port) { +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolBeginTrace("ReadGetPortOk()"); +#endif + CheckResultWithMessage(reader.Read(port), "Could not read port."); + +#ifdef DSVEOSCOSIM_ENABLE_TRACING + LogProtocolEndTrace("ReadGetPortOk(Port: " + std::to_string(port) + ")"); +#endif + return true; } diff --git a/src/Protocol.h b/src/Protocol.h index 6ca48d1..ac7fd0e 100644 --- a/src/Protocol.h +++ b/src/Protocol.h @@ -85,8 +85,8 @@ namespace Protocol { [[nodiscard]] bool SendOk(ChannelWriter& writer); -[[nodiscard]] bool SendError(ChannelWriter& writer, std::string_view errorStr); -[[nodiscard]] bool ReadError(ChannelReader& reader, std::string& errorStr); +[[nodiscard]] bool SendError(ChannelWriter& writer, const std::string& errorMessage); +[[nodiscard]] bool ReadError(ChannelReader& reader, std::string& errorMessage); [[nodiscard]] bool SendPing(ChannelWriter& writer); @@ -96,8 +96,8 @@ namespace Protocol { [[nodiscard]] bool SendConnect(ChannelWriter& writer, uint32_t protocolVersion, Mode clientMode, - std::string_view serverName, - std::string_view clientName); + const std::string& serverName, + const std::string& clientName); [[nodiscard]] bool ReadConnect(ChannelReader& reader, uint32_t& protocolVersion, Mode& clientMode, @@ -166,16 +166,16 @@ namespace Protocol { const BusBuffer& busBuffer, const Callbacks& callbacks); -[[nodiscard]] bool SendGetPort(ChannelWriter& writer, std::string_view serverName); +[[nodiscard]] bool SendGetPort(ChannelWriter& writer, const std::string& serverName); [[nodiscard]] bool ReadGetPort(ChannelReader& reader, std::string& serverName); [[nodiscard]] bool SendGetPortOk(ChannelWriter& writer, uint16_t port); [[nodiscard]] bool ReadGetPortOk(ChannelReader& reader, uint16_t& port); -[[nodiscard]] bool SendSetPort(ChannelWriter& writer, std::string_view serverName, uint16_t port); +[[nodiscard]] bool SendSetPort(ChannelWriter& writer, const std::string& serverName, uint16_t port); [[nodiscard]] bool ReadSetPort(ChannelReader& reader, std::string& serverName, uint16_t& port); -[[nodiscard]] bool SendUnsetPort(ChannelWriter& writer, std::string_view serverName); +[[nodiscard]] bool SendUnsetPort(ChannelWriter& writer, const std::string& serverName); [[nodiscard]] bool ReadUnsetPort(ChannelReader& reader, std::string& serverName); } // namespace Protocol diff --git a/test/Communication/TestTcpChannel.cpp b/test/Communication/TestTcpChannel.cpp index c58c741..e59791b 100644 --- a/test/Communication/TestTcpChannel.cpp +++ b/test/Communication/TestTcpChannel.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -25,7 +24,7 @@ struct Param { AddressFamily addressFamily{}; }; -std::vector GetValues() { +[[nodiscard]] std::vector GetValues() { std::vector values; if (Socket::IsIpv4Supported()) { @@ -45,7 +44,7 @@ INSTANTIATE_TEST_SUITE_P(, TestTcpChannel, testing::ValuesIn(GetValues()), [](const testing::TestParamInfo& info) { - return std::string(ToString(info.param.addressFamily)); + return ToString(info.param.addressFamily); }); TEST_F(TestTcpChannel, StartServer) { diff --git a/test/Communication/TestUdsChannel.cpp b/test/Communication/TestUdsChannel.cpp index 43d3c55..f1924fd 100644 --- a/test/Communication/TestUdsChannel.cpp +++ b/test/Communication/TestUdsChannel.cpp @@ -18,7 +18,7 @@ namespace { constexpr uint32_t BigNumber = 4 * 1024 * 1024; -std::string GenerateName() { +[[nodiscard]] std::string GenerateName() { return GenerateString("UdsChannel"); } diff --git a/test/Helpers/TestHelper.cpp b/test/Helpers/TestHelper.cpp index 32458dc..68dc370 100644 --- a/test/Helpers/TestHelper.cpp +++ b/test/Helpers/TestHelper.cpp @@ -11,12 +11,12 @@ using namespace DsVeosCoSim; -CoSimType GetCounterPart(CoSimType coSimType) { +[[nodiscard]] CoSimType GetCounterPart(CoSimType coSimType) { return coSimType == CoSimType::Client ? CoSimType::Server : CoSimType::Client; } -std::string GetCounterPart(std::string_view name, ConnectionKind connectionKind) { - return connectionKind == ConnectionKind::Local ? std::string(name) : fmt::format("Other{}", name); +[[nodiscard]] std::string GetCounterPart(const std::string& name, ConnectionKind connectionKind) { + return connectionKind == ConnectionKind::Local ? name : fmt::format("Other{}", name); } void AssertByteArray(const void* expected, const void* actual, size_t size) { diff --git a/test/Helpers/TestHelper.h b/test/Helpers/TestHelper.h index 1c336d0..85315ce 100644 --- a/test/Helpers/TestHelper.h +++ b/test/Helpers/TestHelper.h @@ -10,8 +10,8 @@ #include "CoSimTypes.h" -DsVeosCoSim::CoSimType GetCounterPart(DsVeosCoSim::CoSimType coSimType); -std::string GetCounterPart(std::string_view name, DsVeosCoSim::ConnectionKind connectionKind); +[[nodiscard]] DsVeosCoSim::CoSimType GetCounterPart(DsVeosCoSim::CoSimType coSimType); +[[nodiscard]] std::string GetCounterPart(const std::string& name, DsVeosCoSim::ConnectionKind connectionKind); void AssertByteArray(const void* expected, const void* actual, size_t size); diff --git a/test/OsAbstraction/TestNamedEvent.cpp b/test/OsAbstraction/TestNamedEvent.cpp index 3dd27a5..d8cb4ab 100644 --- a/test/OsAbstraction/TestNamedEvent.cpp +++ b/test/OsAbstraction/TestNamedEvent.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include "Generator.h" @@ -18,7 +17,7 @@ namespace { return GenerateString("Event名前\xF0\x9F\x98\x80"); } -void WaitAndSet(std::string_view eventName1, std::string_view eventName2) { +void WaitAndSet(const std::string& eventName1, const std::string& eventName2) { NamedEvent event1 = NamedEvent::OpenExisting(eventName1); NamedEvent event2 = NamedEvent::OpenExisting(eventName2); diff --git a/test/OsAbstraction/TestNamedMutex.cpp b/test/OsAbstraction/TestNamedMutex.cpp index 668221b..b59cd79 100644 --- a/test/OsAbstraction/TestNamedMutex.cpp +++ b/test/OsAbstraction/TestNamedMutex.cpp @@ -3,7 +3,7 @@ #ifdef _WIN32 #include -#include +#include #include "Generator.h" #include "NamedMutex.h" @@ -16,7 +16,7 @@ namespace { return GenerateString("Mutex名前\xF0\x9F\x98\x80"); } -void DifferentThread(std::string_view name, int32_t& counter) { +void DifferentThread(const std::string& name, int32_t& counter) { NamedMutex mutex = NamedMutex::CreateOrOpen(name); for (int32_t i = 0; i < 10000; i++) { diff --git a/test/OsAbstraction/TestSharedMemory.cpp b/test/OsAbstraction/TestSharedMemory.cpp index a415332..7cb3626 100644 --- a/test/OsAbstraction/TestSharedMemory.cpp +++ b/test/OsAbstraction/TestSharedMemory.cpp @@ -3,6 +3,7 @@ #ifdef _WIN32 #include +#include #include "Generator.h" #include "SharedMemory.h" @@ -11,7 +12,7 @@ using namespace DsVeosCoSim; namespace { -std::string GenerateName() { +[[nodiscard]] std::string GenerateName() { return GenerateString("SharedMemory名前\xF0\x9F\x98\x80"); } diff --git a/test/OsAbstraction/TestTcpSocket.cpp b/test/OsAbstraction/TestTcpSocket.cpp index d0754ad..7db496a 100644 --- a/test/OsAbstraction/TestTcpSocket.cpp +++ b/test/OsAbstraction/TestTcpSocket.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include "Generator.h" @@ -17,7 +18,7 @@ struct Param { bool enableRemoteAccess{}; }; -std::vector GetValues() { +[[nodiscard]] std::vector GetValues() { std::vector values; if (Socket::IsIpv4Supported()) { diff --git a/test/Program.cpp b/test/Program.cpp index f41d456..f7d5d2d 100644 --- a/test/Program.cpp +++ b/test/Program.cpp @@ -1,6 +1,7 @@ // Copyright dSPACE GmbH. All rights reserved. #include +#include #include "Helper.h" diff --git a/test/TestBusBuffer.cpp b/test/TestBusBuffer.cpp index 7f7ec51..497c3ac 100644 --- a/test/TestBusBuffer.cpp +++ b/test/TestBusBuffer.cpp @@ -1,10 +1,11 @@ // Copyright dSPACE GmbH. All rights reserved. -#include #include #include #include +#include #include +#include #include #include "BusBuffer.h" @@ -245,7 +246,7 @@ using Parameters = Types - static std::string GetName([[maybe_unused]] int32_t index) { // NOLINT + static std::string GetName([[maybe_unused]] int32_t index) { using TController = typename T::Controller; CoSimType coSimType = T::GetCoSimType(); ConnectionKind connectionKind = T::GetConnectionKind(); diff --git a/test/TestCoSim.cpp b/test/TestCoSim.cpp index 5f766c7..51b9c4b 100644 --- a/test/TestCoSim.cpp +++ b/test/TestCoSim.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include "BackgroundService.h" @@ -18,7 +17,7 @@ namespace { auto connectionKinds = testing::Values(ConnectionKind::Local, ConnectionKind::Remote); -CoSimServerConfig CreateServerConfig(bool isClientOptional = false) { +[[nodiscard]] CoSimServerConfig CreateServerConfig(bool isClientOptional = false) { CoSimServerConfig config{}; config.serverName = GenerateString("Server名前"); config.startPortMapper = false; @@ -28,7 +27,9 @@ CoSimServerConfig CreateServerConfig(bool isClientOptional = false) { return config; } -ConnectConfig CreateConnectConfig(ConnectionKind connectionKind, std::string_view serverName, uint16_t port = 0) { +[[nodiscard]] ConnectConfig CreateConnectConfig(ConnectionKind connectionKind, + std::string_view serverName, + uint16_t port = 0) { ConnectConfig connectConfig{}; connectConfig.serverName = serverName; connectConfig.clientName = GenerateString("Client名前"); @@ -47,8 +48,8 @@ class TestCoSim : public testing::TestWithParam { } }; -INSTANTIATE_TEST_SUITE_P(Test, TestCoSim, connectionKinds, [](const testing::TestParamInfo& info) { - return std::string(ToString(info.param)); +INSTANTIATE_TEST_SUITE_P(, TestCoSim, connectionKinds, [](const testing::TestParamInfo& info) { + return ToString(info.param); }); TEST_F(TestCoSim, LoadServer) { diff --git a/test/TestIoBuffer.cpp b/test/TestIoBuffer.cpp index 87b1880..6c74045 100644 --- a/test/TestIoBuffer.cpp +++ b/test/TestIoBuffer.cpp @@ -1,9 +1,10 @@ // Copyright dSPACE GmbH. All rights reserved. -#include #include #include #include +#include +#include #include #include "CoSimTypes.h" diff --git a/test/TestPortMapper.cpp b/test/TestPortMapper.cpp index 4fecf56..5940e74 100644 --- a/test/TestPortMapper.cpp +++ b/test/TestPortMapper.cpp @@ -1,8 +1,9 @@ // Copyright dSPACE GmbH. All rights reserved. -#include #include #include +#include +#include #include "Generator.h" #include "LogHelper.h" diff --git a/test/TestProtocol.cpp b/test/TestProtocol.cpp index 290d27e..8d9a601 100644 --- a/test/TestProtocol.cpp +++ b/test/TestProtocol.cpp @@ -62,7 +62,7 @@ INSTANTIATE_TEST_SUITE_P(, TestProtocol, testing::Values(ConnectionKind::Local, ConnectionKind::Remote), [](const testing::TestParamInfo& info) { - return std::string(ToString(info.param)); + return ToString(info.param); }); TEST_P(TestProtocol, SendAndReceiveOk) { diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt index d5de8cb..0e86938 100644 --- a/third_party/CMakeLists.txt +++ b/third_party/CMakeLists.txt @@ -11,46 +11,6 @@ if(DSVEOSCOSIM_BUILD_TESTS) endif() if(DSVEOSCOSIM_BUILD_BENCHMARKS) -add_library( - asio - STATIC - asio/asio/src/asio.cpp -) - -target_include_directories( - asio - PUBLIC - $ -) - -target_compile_definitions( - asio - PUBLIC - -DASIO_STANDALONE - -DASIO_SEPARATE_COMPILATION - -DASIO_NO_DEPRECATED -) - -if(WIN32 AND CMAKE_SYSTEM_VERSION) - set(ver ${CMAKE_SYSTEM_VERSION}) - string(REPLACE "." "" ver ${ver}) - string(REGEX REPLACE "([0-9])" "0\\1" ver ${ver}) - set(version "0x${ver}") - target_compile_definitions( - asio - PUBLIC - -D_WIN32_WINNT=${version} - ) -endif() - -if(WIN32) -target_link_libraries( - asio - bcrypt - mswsock -) -endif() - set(BENCHMARK_ENABLE_INSTALL OFF) set(BENCHMARK_INSTALL_DOCS OFF) set(BENCHMARK_ENABLE_GTEST_TESTS OFF) diff --git a/third_party/asio b/third_party/asio deleted file mode 160000 index 1f53428..0000000 --- a/third_party/asio +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1f534288b4be0be2dd664aab43882a0aa3106a1d diff --git a/utilities/PerformanceTestClient/CMakeLists.txt b/utilities/PerformanceTestClient/CMakeLists.txt index 87befd0..6940b26 100644 --- a/utilities/PerformanceTestClient/CMakeLists.txt +++ b/utilities/PerformanceTestClient/CMakeLists.txt @@ -7,7 +7,6 @@ add_executable( target_sources( PerformanceTestClient PRIVATE - ClientAsioBlocking.cpp ClientCoSimCallbackBased.cpp ClientCoSimPollingBased.cpp ClientEvents.cpp @@ -31,5 +30,4 @@ target_link_libraries( PerformanceTestClient DsVeosCoSim shared - asio ) diff --git a/utilities/PerformanceTestClient/ClientAsioBlocking.cpp b/utilities/PerformanceTestClient/ClientAsioBlocking.cpp deleted file mode 100644 index ee2bb8b..0000000 --- a/utilities/PerformanceTestClient/ClientAsioBlocking.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright dSPACE GmbH. All rights reserved. - -#include -#include - -#include "CoSimHelper.h" -#include "LogHelper.h" -#include "PerformanceTestHelper.h" -#include "RunPerformanceTest.h" - -using namespace DsVeosCoSim; -using namespace asio; -using ip::tcp; - -namespace { - -void AsioBlockingClientRun(std::string_view host, Event& connectedEvent, uint64_t& counter, const bool& isStopped) { - try { - io_context io_context; - tcp::socket s(io_context); - tcp::resolver resolver(io_context); - connect(s, resolver.resolve(host, std::to_string(AsioBlockingPort))); - - char data[BufferSize]{}; - - connectedEvent.Set(); - - while (!isStopped) { - std::error_code error; - size_t length = write(s, buffer(data), error); - if (error == error::eof) { - throw std::runtime_error("Server disconnected."); - } - - if (error || (length != BufferSize)) { - throw std::system_error(error); - } - - length = read(s, buffer(data)); - if (error == error::eof) { - throw std::runtime_error("Server disconnected."); - } - - if (error || (length != BufferSize)) { - throw std::system_error(error); - } - - counter++; - } - } catch (const std::exception& e) { - LogError("Exception in ASIO blocking client thread: {}", e.what()); - connectedEvent.Set(); - } -} - -} // namespace - -void RunAsioBlockingTest(std::string_view host) { - LogTrace("ASIO blocking client:"); - RunPerformanceTest(AsioBlockingClientRun, host); - LogTrace(""); -} diff --git a/utilities/PerformanceTestClient/ClientCoSimCallbackBased.cpp b/utilities/PerformanceTestClient/ClientCoSimCallbackBased.cpp index b60b1c2..d319faf 100644 --- a/utilities/PerformanceTestClient/ClientCoSimCallbackBased.cpp +++ b/utilities/PerformanceTestClient/ClientCoSimCallbackBased.cpp @@ -1,6 +1,5 @@ // Copyright dSPACE GmbH. All rights reserved. -#include #include #include "CoSimClient.h" diff --git a/utilities/PerformanceTestClient/ClientCoSimPollingBased.cpp b/utilities/PerformanceTestClient/ClientCoSimPollingBased.cpp index 0c5926b..2e15864 100644 --- a/utilities/PerformanceTestClient/ClientCoSimPollingBased.cpp +++ b/utilities/PerformanceTestClient/ClientCoSimPollingBased.cpp @@ -1,7 +1,6 @@ // Copyright dSPACE GmbH. All rights reserved. #include -#include #include #include "CoSimClient.h" @@ -37,7 +36,7 @@ void CoSimClientRun(std::string_view host, Event& connectedEvent, uint64_t& coun Command command{}; MUST_BE_TRUE(coSimClient.PollCommand(simulationTime, command, false)); - switch (command) { // NOLINT(clang-diagnostic-switch-enum) + switch (command) { case Command::Step: counter++; break; diff --git a/utilities/PerformanceTestClient/ClientEvents.cpp b/utilities/PerformanceTestClient/ClientEvents.cpp index d54a7c2..8dae495 100644 --- a/utilities/PerformanceTestClient/ClientEvents.cpp +++ b/utilities/PerformanceTestClient/ClientEvents.cpp @@ -1,6 +1,9 @@ // Copyright dSPACE GmbH. All rights reserved. #ifdef _WIN32 +#include +#include + #include "CoSimHelper.h" #include "LogHelper.h" #include "NamedEvent.h" diff --git a/utilities/PerformanceTestClient/ClientLocalCommunication.cpp b/utilities/PerformanceTestClient/ClientLocalCommunication.cpp index 5725f99..06f8771 100644 --- a/utilities/PerformanceTestClient/ClientLocalCommunication.cpp +++ b/utilities/PerformanceTestClient/ClientLocalCommunication.cpp @@ -1,5 +1,9 @@ // Copyright dSPACE GmbH. All rights reserved. +#include +#include +#include + #include "CoSimHelper.h" #include "Helper.h" #include "LogHelper.h" @@ -27,15 +31,15 @@ void LocalCommunicationClientRun([[maybe_unused]] std::string_view host, std::optional channel = *TryConnectToUdsChannel(LocalName); #endif - char buffer[BufferSize]{}; + std::array buffer{}; connectedEvent.Set(); while (!isStopped) { - MUST_BE_TRUE(channel->GetWriter().Write(buffer, BufferSize)); + MUST_BE_TRUE(channel->GetWriter().Write(buffer.data(), BufferSize)); MUST_BE_TRUE(channel->GetWriter().EndWrite()); - MUST_BE_TRUE(channel->GetReader().Read(buffer, BufferSize)); + MUST_BE_TRUE(channel->GetReader().Read(buffer.data(), BufferSize)); counter++; } diff --git a/utilities/PerformanceTestClient/ClientPipe.cpp b/utilities/PerformanceTestClient/ClientPipe.cpp index 5527460..8aa7b95 100644 --- a/utilities/PerformanceTestClient/ClientPipe.cpp +++ b/utilities/PerformanceTestClient/ClientPipe.cpp @@ -1,5 +1,9 @@ // Copyright dSPACE GmbH. All rights reserved. +#include +#include +#include + #include "CoSimHelper.h" #include "Helper.h" #include "LogHelper.h" @@ -19,14 +23,14 @@ void PipeClientRun([[maybe_unused]] std::string_view host, Pipe pipe(PipeName); pipe.Connect(); - char buffer[BufferSize]{}; + std::array buffer{}; connectedEvent.Set(); while (!isStopped) { - MUST_BE_TRUE(pipe.Write(buffer, BufferSize)); + MUST_BE_TRUE(pipe.Write(buffer.data(), BufferSize)); - MUST_BE_TRUE(pipe.Read(buffer, BufferSize)); + MUST_BE_TRUE(pipe.Read(buffer.data(), BufferSize)); counter++; } diff --git a/utilities/PerformanceTestClient/ClientRemoteCommunication.cpp b/utilities/PerformanceTestClient/ClientRemoteCommunication.cpp index 111696c..1b465a7 100644 --- a/utilities/PerformanceTestClient/ClientRemoteCommunication.cpp +++ b/utilities/PerformanceTestClient/ClientRemoteCommunication.cpp @@ -1,6 +1,7 @@ // Copyright dSPACE GmbH. All rights reserved. -#include // IWYU pragma: keep +#include +#include #include "CoSimHelper.h" #include "Helper.h" @@ -20,15 +21,15 @@ void RemoteCommunicationClientRun(std::string_view host, try { std::optional channel = *TryConnectToTcpChannel(host, CommunicationPort, 0, Infinite); - char buffer[BufferSize]{}; + std::array buffer{}; connectedEvent.Set(); while (!isStopped) { - MUST_BE_TRUE(channel->GetWriter().Write(buffer, BufferSize)); + MUST_BE_TRUE(channel->GetWriter().Write(buffer.data(), BufferSize)); MUST_BE_TRUE(channel->GetWriter().EndWrite()); - MUST_BE_TRUE(channel->GetReader().Read(buffer, BufferSize)); + MUST_BE_TRUE(channel->GetReader().Read(buffer.data(), BufferSize)); counter++; } diff --git a/utilities/PerformanceTestClient/ClientTcp.cpp b/utilities/PerformanceTestClient/ClientTcp.cpp index dee5742..a9905b6 100644 --- a/utilities/PerformanceTestClient/ClientTcp.cpp +++ b/utilities/PerformanceTestClient/ClientTcp.cpp @@ -1,6 +1,7 @@ // Copyright dSPACE GmbH. All rights reserved. -#include // IWYU pragma: keep +#include +#include #include "CoSimHelper.h" #include "Helper.h" @@ -22,13 +23,13 @@ void TcpClientRun(std::string_view host, Event& connectedEvent, uint64_t& counte clientSocket->EnableNoDelay(); - char buffer[BufferSize]{}; + std::array buffer{}; connectedEvent.Set(); while (!isStopped) { - MUST_BE_TRUE(SendComplete(*clientSocket, buffer, BufferSize)); - MUST_BE_TRUE(ReceiveComplete(*clientSocket, buffer, BufferSize)); + MUST_BE_TRUE(SendComplete(*clientSocket, buffer.data(), BufferSize)); + MUST_BE_TRUE(ReceiveComplete(*clientSocket, buffer.data(), BufferSize)); counter++; } diff --git a/utilities/PerformanceTestClient/ClientUdp.cpp b/utilities/PerformanceTestClient/ClientUdp.cpp index 56600f4..f6765af 100644 --- a/utilities/PerformanceTestClient/ClientUdp.cpp +++ b/utilities/PerformanceTestClient/ClientUdp.cpp @@ -1,5 +1,6 @@ // Copyright dSPACE GmbH. All rights reserved. +#include #include #include "CoSimHelper.h" @@ -20,14 +21,14 @@ void UdpClientRun(std::string_view host, Event& connectedEvent, uint64_t& counte const InternetAddress sendAddress(host, UdpPort); InternetAddress receiveAddress(host, UdpPort); - char buffer[BufferSize]{}; + std::array buffer{}; connectedEvent.Set(); while (!isStopped) { - MUST_BE_TRUE(clientSocket.SendTo(buffer, BufferSize, sendAddress)); + MUST_BE_TRUE(clientSocket.SendTo(buffer.data(), BufferSize, sendAddress)); - MUST_BE_TRUE(clientSocket.ReceiveFrom(buffer, BufferSize, receiveAddress)); + MUST_BE_TRUE(clientSocket.ReceiveFrom(buffer.data(), BufferSize, receiveAddress)); counter++; } diff --git a/utilities/PerformanceTestClient/ClientUds.cpp b/utilities/PerformanceTestClient/ClientUds.cpp index bff12e2..3140ab4 100644 --- a/utilities/PerformanceTestClient/ClientUds.cpp +++ b/utilities/PerformanceTestClient/ClientUds.cpp @@ -1,5 +1,6 @@ // Copyright dSPACE GmbH. All rights reserved. +#include #include #include "CoSimHelper.h" @@ -21,13 +22,13 @@ void UdsClientRun([[maybe_unused]] std::string_view host, Socket clientSocket(AddressFamily::Uds); MUST_BE_TRUE(clientSocket.TryConnect(UdsName)); - char buffer[BufferSize]{}; + std::array buffer{}; connectedEvent.Set(); while (!isStopped) { - MUST_BE_TRUE(SendComplete(clientSocket, buffer, BufferSize)); - MUST_BE_TRUE(ReceiveComplete(clientSocket, buffer, BufferSize)); + MUST_BE_TRUE(SendComplete(clientSocket, buffer.data(), BufferSize)); + MUST_BE_TRUE(ReceiveComplete(clientSocket, buffer.data(), BufferSize)); counter++; } diff --git a/utilities/PerformanceTestClient/Program.cpp b/utilities/PerformanceTestClient/Program.cpp index 5b9f132..cc23e3d 100644 --- a/utilities/PerformanceTestClient/Program.cpp +++ b/utilities/PerformanceTestClient/Program.cpp @@ -1,9 +1,11 @@ // Copyright dSPACE GmbH. All rights reserved. +#include +#include + #include "CoSimHelper.h" #include "Helper.h" -extern void RunAsioBlockingTest(std::string_view host); extern void RunTcpTest(std::string_view host); extern void RunUdpTest(std::string_view host); extern void RunUdsTest(); @@ -23,7 +25,6 @@ int32_t main(int32_t argc, char* argv[]) { if (argc > 1) { RunTcpTest(argv[1]); - RunAsioBlockingTest(argv[1]); RunUdpTest(argv[1]); LogTrace("----------------------------------------\n"); @@ -33,7 +34,6 @@ int32_t main(int32_t argc, char* argv[]) { RunCoSimPollingTest(argv[1]); } else { RunTcpTest("127.0.0.1"); - RunAsioBlockingTest("127.0.0.1"); RunUdpTest("127.0.0.1"); RunUdsTest(); RunPipeTest(); diff --git a/utilities/PerformanceTestClient/RunPerformanceTest.cpp b/utilities/PerformanceTestClient/RunPerformanceTest.cpp index 1c1db50..5e14505 100644 --- a/utilities/PerformanceTestClient/RunPerformanceTest.cpp +++ b/utilities/PerformanceTestClient/RunPerformanceTest.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include "Event.h" diff --git a/utilities/PerformanceTestServer/CMakeLists.txt b/utilities/PerformanceTestServer/CMakeLists.txt index 29ea01d..488909d 100644 --- a/utilities/PerformanceTestServer/CMakeLists.txt +++ b/utilities/PerformanceTestServer/CMakeLists.txt @@ -8,7 +8,6 @@ target_sources( PerformanceTestServer PRIVATE Program.cpp - ServerAsioBlocking.cpp ServerCoSim.cpp ServerEvents.cpp ServerLocalCommunication.cpp @@ -23,5 +22,4 @@ target_link_libraries( PerformanceTestServer DsVeosCoSim shared - asio ) diff --git a/utilities/PerformanceTestServer/Program.cpp b/utilities/PerformanceTestServer/Program.cpp index 6f79606..4d12360 100644 --- a/utilities/PerformanceTestServer/Program.cpp +++ b/utilities/PerformanceTestServer/Program.cpp @@ -1,10 +1,10 @@ // Copyright dSPACE GmbH. All rights reserved. +#include #include #include "Helper.h" -extern void StartAsioBlockingServer(); extern void StartUdpServer(); extern void StartTcpServer(); extern void StartUdsServer(); @@ -19,7 +19,6 @@ int32_t main() { return 1; } - StartAsioBlockingServer(); StartTcpServer(); StartUdpServer(); StartUdsServer(); diff --git a/utilities/PerformanceTestServer/ServerAsioBlocking.cpp b/utilities/PerformanceTestServer/ServerAsioBlocking.cpp deleted file mode 100644 index fb5896d..0000000 --- a/utilities/PerformanceTestServer/ServerAsioBlocking.cpp +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright dSPACE GmbH. All rights reserved. - -#include -#include - -#include "CoSimHelper.h" -#include "LogHelper.h" -#include "PerformanceTestHelper.h" - -using namespace DsVeosCoSim; -using namespace asio; -using ip::tcp; - -namespace { - -void Session(tcp::socket s) { - LogTrace("ASIO blocking server: Client connected."); - try { - for (;;) { - char data[BufferSize]{}; - - std::error_code error; - size_t length = read(s, buffer(data), error); - if (error == error::eof) { - LogTrace("ASIO blocking server: Client disconnected."); - break; - } - - if (error || (length != BufferSize)) { - throw std::system_error(error); - } - - length = write(s, buffer(data, length)); - if (error == error::eof) { - LogTrace("ASIO blocking server: Client disconnected."); - break; - } - - if (error || (length != BufferSize)) { - throw std::system_error(error); - } - } - } catch (const std::exception& e) { - LogError("Exception in ASIO blocking server thread: {}", e.what()); - } -} - -[[noreturn]] void AsioBlockingServerRun() { - LogTrace("ASIO blocking server is listening on port {} ...", AsioBlockingPort); - - io_context ioContext; - tcp::acceptor a(ioContext, tcp::endpoint(tcp::v4(), AsioBlockingPort)); - - for (;;) { - std::thread(Session, a.accept()).detach(); - } -} - -} // namespace - -void StartAsioBlockingServer() { - std::thread thread(AsioBlockingServerRun); - thread.detach(); -} diff --git a/utilities/PerformanceTestServer/ServerPipe.cpp b/utilities/PerformanceTestServer/ServerPipe.cpp index ce8bc91..d0b26fa 100644 --- a/utilities/PerformanceTestServer/ServerPipe.cpp +++ b/utilities/PerformanceTestServer/ServerPipe.cpp @@ -1,5 +1,6 @@ // Copyright dSPACE GmbH. All rights reserved. +#include #include #include "LogHelper.h" @@ -12,18 +13,18 @@ void PipeServerRun() { try { LogTrace("Pipe server is listening on pipe {} ...", PipeName); - char buffer[BufferSize]{}; + std::array buffer{}; while (true) { Pipe pipe(PipeName); pipe.Accept(); while (true) { - if (!pipe.Read(buffer, BufferSize)) { + if (!pipe.Read(buffer.data(), BufferSize)) { break; } - if (!pipe.Write(buffer, BufferSize)) { + if (!pipe.Write(buffer.data(), BufferSize)) { break; } } diff --git a/utilities/PerformanceTestServer/ServerRemoteCommunication.cpp b/utilities/PerformanceTestServer/ServerRemoteCommunication.cpp index c568631..c2d5a27 100644 --- a/utilities/PerformanceTestServer/ServerRemoteCommunication.cpp +++ b/utilities/PerformanceTestServer/ServerRemoteCommunication.cpp @@ -1,5 +1,6 @@ // Copyright dSPACE GmbH. All rights reserved. +#include #include #include "CoSimHelper.h" @@ -18,17 +19,17 @@ void RemoteCommunicationServerRun() { TcpChannelServer server(CommunicationPort, true); - char buffer[BufferSize]{}; + std::array buffer{}; while (true) { std::optional acceptedChannel = server.TryAccept(Infinite); while (true) { - if (!acceptedChannel->GetReader().Read(buffer, BufferSize)) { + if (!acceptedChannel->GetReader().Read(buffer.data(), BufferSize)) { break; } - if (!acceptedChannel->GetWriter().Write(buffer, BufferSize)) { + if (!acceptedChannel->GetWriter().Write(buffer.data(), BufferSize)) { break; } diff --git a/utilities/PerformanceTestServer/ServerTcp.cpp b/utilities/PerformanceTestServer/ServerTcp.cpp index ed1a833..a1e8e0d 100644 --- a/utilities/PerformanceTestServer/ServerTcp.cpp +++ b/utilities/PerformanceTestServer/ServerTcp.cpp @@ -1,5 +1,6 @@ // Copyright dSPACE GmbH. All rights reserved. +#include #include #include "Helper.h" @@ -20,18 +21,18 @@ void TcpServerRun() { LogTrace("TCP server is listening on port {} ...", TcpPort); - char buffer[BufferSize]{}; + std::array buffer{}; while (true) { std::optional acceptedSocket = serverSocket.TryAccept(Infinite); acceptedSocket->EnableNoDelay(); while (true) { - if (!ReceiveComplete(*acceptedSocket, buffer, BufferSize)) { + if (!ReceiveComplete(*acceptedSocket, buffer.data(), BufferSize)) { break; } - if (!SendComplete(*acceptedSocket, buffer, BufferSize)) { + if (!SendComplete(*acceptedSocket, buffer.data(), BufferSize)) { break; } } diff --git a/utilities/PerformanceTestServer/ServerUdp.cpp b/utilities/PerformanceTestServer/ServerUdp.cpp index 4a2fc10..5c11628 100644 --- a/utilities/PerformanceTestServer/ServerUdp.cpp +++ b/utilities/PerformanceTestServer/ServerUdp.cpp @@ -1,5 +1,6 @@ // Copyright dSPACE GmbH. All rights reserved. +#include #include #include "LogHelper.h" @@ -12,7 +13,7 @@ void UdpServerRun() { try { LogTrace("UDP server is listening on port {} ...", UdpPort); - char buffer[BufferSize]{}; + std::array buffer{}; while (true) { UdpSocket serverSocket; @@ -21,11 +22,11 @@ void UdpServerRun() { InternetAddress address("127.0.0.1", 0); while (true) { - if (!serverSocket.ReceiveFrom(buffer, BufferSize, address)) { + if (!serverSocket.ReceiveFrom(buffer.data(), BufferSize, address)) { break; } - if (!serverSocket.SendTo(buffer, BufferSize, address)) { + if (!serverSocket.SendTo(buffer.data(), BufferSize, address)) { break; } } diff --git a/utilities/PerformanceTestServer/ServerUds.cpp b/utilities/PerformanceTestServer/ServerUds.cpp index a68db25..b5d013c 100644 --- a/utilities/PerformanceTestServer/ServerUds.cpp +++ b/utilities/PerformanceTestServer/ServerUds.cpp @@ -1,5 +1,6 @@ // Copyright dSPACE GmbH. All rights reserved. +#include #include #include "Helper.h" @@ -18,17 +19,17 @@ void UdsServerRun() { LogTrace("UDS server is listening on file {} ...", UdsName); - char buffer[BufferSize]{}; + std::array buffer{}; while (true) { std::optional acceptedSocket = serverSocket.TryAccept(Infinite); while (true) { - if (!ReceiveComplete(*acceptedSocket, buffer, BufferSize)) { + if (!ReceiveComplete(*acceptedSocket, buffer.data(), BufferSize)) { break; } - if (!SendComplete(*acceptedSocket, buffer, BufferSize)) { + if (!SendComplete(*acceptedSocket, buffer.data(), BufferSize)) { break; } } diff --git a/utilities/TestClient/Program.cpp b/utilities/TestClient/Program.cpp index b6d7333..55aaf5e 100644 --- a/utilities/TestClient/Program.cpp +++ b/utilities/TestClient/Program.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -67,6 +68,10 @@ void OnSimulationContinuedCallback(DsVeosCoSim_SimulationTime simulationTime) { connectConfig.serverName = serverName; connectConfig.remoteIpAddress = host; CheckResultWithMessage(g_coSimClient->Connect(connectConfig), "Could not connect."); + LogTrace(""); + + LogTrace("Step size: {}", g_coSimClient->GetStepSize()); + LogTrace(""); g_runTimeInfo.canControllers = g_coSimClient->GetCanControllers(); if (!g_runTimeInfo.canControllers.empty()) { diff --git a/utilities/TestServer/Program.cpp b/utilities/TestServer/Program.cpp index 04b249c..9e97a5a 100644 --- a/utilities/TestServer/Program.cpp +++ b/utilities/TestServer/Program.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -290,6 +291,7 @@ void UnloadSimulation() { LogInfo("Unloading ..."); StopSimulationThread(); + g_backgroundService.reset(); g_server.reset(); g_state = State::Unloaded;