From 5b86489aba72e1f8427cef6fefd544e803d453ca Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 10:28:00 +0200 Subject: [PATCH 1/9] Added resource monitoring and fixed FD leak. --- CMakeLists.txt | 4 +- src/mtconnect/configuration/agent_config.cpp | 41 +++++++++++++++--- src/mtconnect/configuration/agent_config.hpp | 7 ++- .../configuration/config_options.hpp | 1 + src/mtconnect/pipeline/deliver.cpp | 4 +- src/mtconnect/printer/json_printer.cpp | 2 +- src/mtconnect/printer/xml_printer.cpp | 2 +- src/mtconnect/sink/rest_sink/session_impl.hpp | 19 ++++++++ src/mtconnect/utilities.cpp | 39 +++++++++++++++++ src/mtconnect/utilities.hpp | 43 +++++++++++++++++++ 10 files changed, 148 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ff03e35e..07b02bd4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,8 +1,8 @@ # The version number. set(AGENT_VERSION_MAJOR 2) -set(AGENT_VERSION_MINOR 7) +set(AGENT_VERSION_MINOR 8) set(AGENT_VERSION_PATCH 0) -set(AGENT_VERSION_BUILD 13) +set(AGENT_VERSION_BUILD 1) set(AGENT_VERSION_RC "") # This minimum version is to support Visual Studio 2019 and C++ feature checking and FetchContent diff --git a/src/mtconnect/configuration/agent_config.cpp b/src/mtconnect/configuration/agent_config.cpp index 1daac31c..91808c63 100644 --- a/src/mtconnect/configuration/agent_config.cpp +++ b/src/mtconnect/configuration/agent_config.cpp @@ -104,7 +104,8 @@ BOOST_LOG_ATTRIBUTE_KEYWORD(utc_timestamp, "Timestamp", logr::attributes::utc_cl namespace mtconnect::configuration { AgentConfiguration::AgentConfiguration() - : m_context {make_unique()}, m_monitorTimer(m_context->get()) + : m_context {make_unique()}, m_monitorFilesTimer(m_context->get()), + m_monitorResourceTimer(m_context->get()) { NAMED_SCOPE("AgentConfiguration::AgentConfiguration"); using namespace source; @@ -370,8 +371,8 @@ namespace mtconnect::configuration { using std::placeholders::_1; - m_monitorTimer.expires_after(100ms); - m_monitorTimer.async_wait(boost::bind(&AgentConfiguration::monitorFiles, this, _1)); + m_monitorFilesTimer.expires_after(100ms); + m_monitorFilesTimer.async_wait(boost::bind(&AgentConfiguration::monitorFiles, this, _1)); } else { @@ -392,8 +393,26 @@ namespace mtconnect::configuration { using std::placeholders::_1; - m_monitorTimer.expires_after(m_monitorInterval); - m_monitorTimer.async_wait(boost::bind(&AgentConfiguration::monitorFiles, this, _1)); + m_monitorFilesTimer.expires_after(m_monitorInterval); + m_monitorFilesTimer.async_wait(boost::bind(&AgentConfiguration::monitorFiles, this, _1)); + } + + void AgentConfiguration::monitorResources(boost::system::error_code ec) + { + using namespace chrono; + using namespace chrono_literals; + + using std::placeholders::_1; + + auto report = m_fdMonitor.sample(); + LOG(info) << "Open file descriptors: Current: " << report.m_current + << ", high water: " << report.m_highWater + << ", slope: " << report.m_slope + << ", suspect: " << report.m_suspect; + + // m_current, m_highWater; double m_slope; bool m_suspect + m_monitorFilesTimer.expires_after(15s); + m_monitorFilesTimer.async_wait(boost::bind(&AgentConfiguration::monitorResources, this, _1)); } int AgentConfiguration::start() @@ -409,7 +428,13 @@ namespace mtconnect::configuration { }); boost::system::error_code ec; - AgentConfiguration::monitorFiles(ec); + monitorFiles(ec); + } + + if (m_monitorResources) + { + boost::system::error_code ec; + monitorResources(ec); } m_context->setThreadCount(m_workerThreadCount); @@ -422,7 +447,7 @@ namespace mtconnect::configuration { { LOG(info) << "Agent stopping"; m_beforeStopHooks.exec(*this); - m_monitorTimer.cancel(); + m_monitorFilesTimer.cancel(); m_restart = false; if (m_agent) m_agent->stop(); @@ -823,6 +848,7 @@ namespace mtconnect::configuration { GetOptions(config, options, {{configuration::PreserveUUID, true}, {configuration::DisableAgentDevice, false}, + {configuration::MonitorResources, false}, {configuration::WorkingDirectory, m_working.string()}, {configuration::DataPath, StringList()}, {configuration::AgentDeviceUUID, ""s}, @@ -875,6 +901,7 @@ namespace mtconnect::configuration { m_monitorFiles = *GetOption(options, configuration::MonitorConfigFiles); m_monitorInterval = *GetOption(options, configuration::MonitorInterval); m_monitorDelay = *GetOption(options, configuration::MinimumConfigReloadAge); + m_monitorResources = *GetOption(options, configuration::MonitorResources); addPathFront(m_configPaths, m_working); diff --git a/src/mtconnect/configuration/agent_config.hpp b/src/mtconnect/configuration/agent_config.hpp index fd43e8fb..7e3143bc 100644 --- a/src/mtconnect/configuration/agent_config.hpp +++ b/src/mtconnect/configuration/agent_config.hpp @@ -295,6 +295,7 @@ namespace mtconnect { void loadPlugins(const ptree &tree); bool loadPlugin(const std::string &name, const ptree &tree); void monitorFiles(boost::system::error_code ec); + void monitorResources(boost::system::error_code ec); void scheduleMonitorTimer(); protected: @@ -400,11 +401,13 @@ namespace mtconnect { std::list m_pluginPaths; // File monitoring - boost::asio::steady_timer m_monitorTimer; + boost::asio::steady_timer m_monitorFilesTimer; + boost::asio::steady_timer m_monitorResourceTimer; bool m_monitorFiles = false; std::chrono::seconds m_monitorInterval; std::chrono::seconds m_monitorDelay; bool m_restart = false; + bool m_monitorResources { false }; std::optional m_configTime; std::optional m_deviceTime; @@ -424,6 +427,8 @@ namespace mtconnect { std::unique_ptr m_python; #endif + FdMonitor m_fdMonitor; + HookManager m_afterAgentHooks; HookManager m_afterConfigHooks; HookManager m_beforeStartHooks; diff --git a/src/mtconnect/configuration/config_options.hpp b/src/mtconnect/configuration/config_options.hpp index 53160a33..4f739ccd 100644 --- a/src/mtconnect/configuration/config_options.hpp +++ b/src/mtconnect/configuration/config_options.hpp @@ -38,6 +38,7 @@ namespace mtconnect { DECLARE_CONFIGURATION(DataPath); DECLARE_CONFIGURATION(ConfigPath); DECLARE_CONFIGURATION(PluginPath); + DECLARE_CONFIGURATION(MonitorResources); ///@} /// @name Agent Configuration diff --git a/src/mtconnect/pipeline/deliver.cpp b/src/mtconnect/pipeline/deliver.cpp index 65e018fb..d4fbc931 100644 --- a/src/mtconnect/pipeline/deliver.cpp +++ b/src/mtconnect/pipeline/deliver.cpp @@ -98,8 +98,8 @@ namespace mtconnect { auto delta = count - m_last; double avg = delta + exp(-(dt.count() / 60.0)) * (m_lastAvg - delta); - LOG(info) << *m_dataItem << " - Average for last 1 minutes: " << (avg / dt.count()); - LOG(info) << *m_dataItem + LOG(debug) << *m_dataItem << " - Average for last 1 minutes: " << (avg / dt.count()); + LOG(debug) << *m_dataItem << " - Delta for last 10 seconds: " << (double(delta) / dt.count()); m_last = count; diff --git a/src/mtconnect/printer/json_printer.cpp b/src/mtconnect/printer/json_printer.cpp index c97c1802..3f8d5c75 100644 --- a/src/mtconnect/printer/json_printer.cpp +++ b/src/mtconnect/printer/json_printer.cpp @@ -64,7 +64,7 @@ namespace mtconnect::printer { const string &schemaVersion, const string modelChangeTime, bool validation, const std::optional &requestId) { - obj.AddPairs("version", version, "creationTime", getCurrentTime(GMT), "testIndicator", false, + obj.AddPairs("version", version, "creationTime", getCurrentTime(GMT_UV_SEC), "testIndicator", false, "instanceId", instanceId, "sender", hostname, "schemaVersion", schemaVersion); if (IntSchemaVersion(schemaVersion) >= SCHEMA_VERSION(1, 7)) diff --git a/src/mtconnect/printer/xml_printer.cpp b/src/mtconnect/printer/xml_printer.cpp index 58d6235f..dc44bcd7 100644 --- a/src/mtconnect/printer/xml_printer.cpp +++ b/src/mtconnect/printer/xml_printer.cpp @@ -538,7 +538,7 @@ namespace mtconnect::printer { // Create the header AutoElement header(writer, "Header"); - addAttribute(writer, "creationTime", getCurrentTime(GMT)); + addAttribute(writer, "creationTime", getCurrentTime(GMT_UV_SEC)); addAttribute(writer, "sender", m_senderName); addAttribute(writer, "instanceId", instanceId); diff --git a/src/mtconnect/sink/rest_sink/session_impl.hpp b/src/mtconnect/sink/rest_sink/session_impl.hpp index b7075229..7bfd6089 100644 --- a/src/mtconnect/sink/rest_sink/session_impl.hpp +++ b/src/mtconnect/sink/rest_sink/session_impl.hpp @@ -156,6 +156,24 @@ namespace mtconnect { { NAMED_SCOPE("HttpSession::close"); + if (m_closing) + return; + m_closing = true; + + // Release all references from observers. Streaming (interval) requests hold a + // shared_ptr back to this session via the AsyncObserver, and this session holds + // the observer's completion handler in m_complete, forming a reference cycle. + // Cancelling the observers resets that back-reference so the session (and its + // socket fd) can be destroyed. Without this the fd leaks on client disconnect. + for (auto &obs : m_observers) + { + auto optr = obs.lock(); + if (optr) + { + optr->cancel(); + } + } + m_request.reset(); boost::beast::error_code ec; m_stream.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); @@ -166,6 +184,7 @@ namespace mtconnect { protected: boost::beast::tcp_stream m_stream; + bool m_closing {false}; }; } // namespace sink::rest_sink } // namespace mtconnect diff --git a/src/mtconnect/utilities.cpp b/src/mtconnect/utilities.cpp index 0a0b78a0..4744d846 100644 --- a/src/mtconnect/utilities.cpp +++ b/src/mtconnect/utilities.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include "logging.hpp" @@ -47,6 +48,14 @@ #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ull #endif +#if defined(__linux__) +#include +#include +#else // macOS, *BSD +#include +#include +#endif + using namespace std; using namespace std::chrono; @@ -291,5 +300,35 @@ namespace mtconnect { return ast; } } // namespace url + + std::size_t FdMonitor::openFdCount() + { +#if defined(_WIN32) + // NOTE: counts ALL kernel handles (files, events, threads, mutexes...), + // not just file descriptors. There is no exact fd analogue. + DWORD n = 0; + if (!GetProcessHandleCount(GetCurrentProcess(), &n)) + return 0; + return static_cast(n); + +#elif defined(__linux__) + namespace fs = boost::filesystem; + boost::system::error_code ec; + fs::directory_iterator it("/proc/self/fd", ec), end; + if (ec) return 0; + // the iterator itself holds one fd open on the directory + auto n = static_cast(std::distance(it, end)); + return n ? n - 1 : 0; + +#else + // /proc may be absent; scan up to the soft limit. + long maxfd = sysconf(_SC_OPEN_MAX); + if (maxfd < 0) maxfd = 65536; + std::size_t n = 0; + for (int fd = 0; fd < maxfd; ++fd) + if (fcntl(fd, F_GETFD) != -1) ++n; + return n; +#endif + } } // namespace mtconnect diff --git a/src/mtconnect/utilities.hpp b/src/mtconnect/utilities.hpp index 4c09e919..4af5fa6a 100644 --- a/src/mtconnect/utilities.hpp +++ b/src/mtconnect/utilities.hpp @@ -40,6 +40,8 @@ #include #include #include +#include +#include #include "mtconnect/config.hpp" #include "mtconnect/logging.hpp" @@ -1021,4 +1023,45 @@ namespace mtconnect { } } // namespace url + + class FdMonitor { + public: + explicit FdMonitor(std::size_t window = 30) : m_window(window) {} + + // call on a timer (e.g. every 10–30s) + struct Report { std::size_t m_current, m_highWater; double m_slope; bool m_suspect; }; + + Report sample() { + std::size_t n = openFdCount(); + m_highWater = std::max(m_highWater, n); + + m_samples.push_back(n); + if (m_samples.size() > m_window) m_samples.pop_front(); + + double s = slope(); + // suspect if steadily rising AND at a new high across the whole window + bool suspect = m_samples.size() == m_window + && s > 0.5 // fds gained per sample + && m_samples.back() == m_highWater; + return { n, m_highWater, s, suspect }; + } + + private: + static std::size_t openFdCount(); + + double slope() const { // least-squares over the window + std::size_t m = m_samples.size(); + if (m < 2) return 0.0; + double sx=0, sy=0, sxy=0, sxx=0; + for (std::size_t i = 0; i < m; ++i) { + double x = double(i), y = double(m_samples[i]); + sx+=x; sy+=y; sxy+=x*y; sxx+=x*x; + } + double d = m*sxx - sx*sx; + return d == 0.0 ? 0.0 : (m*sxy - sx*sy) / d; + } + + std::size_t m_window, m_highWater = 0; + std::deque m_samples; + }; } // namespace mtconnect From f8bb8b0d73cae9ccfe6b10d0e09d0587a198e887 Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 10:38:42 +0200 Subject: [PATCH 2/9] Added memory monitoring as well --- src/mtconnect/configuration/agent_config.cpp | 33 ++++++--- src/mtconnect/configuration/agent_config.hpp | 6 +- src/mtconnect/utilities.cpp | 46 ++++++++++-- src/mtconnect/utilities.hpp | 73 ++++++++++++++++---- 4 files changed, 130 insertions(+), 28 deletions(-) diff --git a/src/mtconnect/configuration/agent_config.cpp b/src/mtconnect/configuration/agent_config.cpp index 91808c63..6585e96d 100644 --- a/src/mtconnect/configuration/agent_config.cpp +++ b/src/mtconnect/configuration/agent_config.cpp @@ -403,16 +403,28 @@ namespace mtconnect::configuration { using namespace chrono_literals; using std::placeholders::_1; - - auto report = m_fdMonitor.sample(); - LOG(info) << "Open file descriptors: Current: " << report.m_current - << ", high water: " << report.m_highWater - << ", slope: " << report.m_slope - << ", suspect: " << report.m_suspect; - - // m_current, m_highWater; double m_slope; bool m_suspect - m_monitorFilesTimer.expires_after(15s); - m_monitorFilesTimer.async_wait(boost::bind(&AgentConfiguration::monitorResources, this, _1)); + + if (ec == boost::asio::error::operation_aborted) + { + LOG(info) << "Monitor resources stopped"; + return; + } + + auto fd = m_fdMonitor.sample(); + LOG(info) << "Open file descriptors: Current: " << fd.m_current + << ", high water: " << fd.m_highWater + << ", slope: " << fd.m_slope + << ", suspect: " << fd.m_suspect; + + constexpr double MiB = 1024.0 * 1024.0; + auto mem = m_memoryMonitor.sample(); + LOG(info) << "Resident memory (MiB): Current: " << (mem.m_current / MiB) + << ", high water: " << (mem.m_highWater / MiB) + << ", slope (bytes/sample): " << mem.m_slope + << ", suspect: " << mem.m_suspect; + + m_monitorResourceTimer.expires_after(15s); + m_monitorResourceTimer.async_wait(boost::bind(&AgentConfiguration::monitorResources, this, _1)); } int AgentConfiguration::start() @@ -448,6 +460,7 @@ namespace mtconnect::configuration { LOG(info) << "Agent stopping"; m_beforeStopHooks.exec(*this); m_monitorFilesTimer.cancel(); + m_monitorResourceTimer.cancel(); m_restart = false; if (m_agent) m_agent->stop(); diff --git a/src/mtconnect/configuration/agent_config.hpp b/src/mtconnect/configuration/agent_config.hpp index 7e3143bc..97dc97ba 100644 --- a/src/mtconnect/configuration/agent_config.hpp +++ b/src/mtconnect/configuration/agent_config.hpp @@ -427,8 +427,10 @@ namespace mtconnect { std::unique_ptr m_python; #endif - FdMonitor m_fdMonitor; - + TrendMonitor m_fdMonitor {makeFdMonitor()}; + TrendMonitor m_memoryMonitor {makeMemoryMonitor()}; + + HookManager m_afterAgentHooks; HookManager m_afterConfigHooks; HookManager m_beforeStartHooks; diff --git a/src/mtconnect/utilities.cpp b/src/mtconnect/utilities.cpp index 4744d846..f784d276 100644 --- a/src/mtconnect/utilities.cpp +++ b/src/mtconnect/utilities.cpp @@ -44,14 +44,21 @@ #define _WINSOCKAPI_ #include #include +#include #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ull #endif #if defined(__linux__) #include +#include #include -#else // macOS, *BSD +#include +#elif defined(__APPLE__) +#include +#include +#include +#else // *BSD #include #include #endif @@ -301,7 +308,7 @@ namespace mtconnect { } } // namespace url - std::size_t FdMonitor::openFdCount() + std::size_t openFdCount() { #if defined(_WIN32) // NOTE: counts ALL kernel handles (files, events, threads, mutexes...), @@ -310,7 +317,7 @@ namespace mtconnect { if (!GetProcessHandleCount(GetCurrentProcess(), &n)) return 0; return static_cast(n); - + #elif defined(__linux__) namespace fs = boost::filesystem; boost::system::error_code ec; @@ -319,7 +326,7 @@ namespace mtconnect { // the iterator itself holds one fd open on the directory auto n = static_cast(std::distance(it, end)); return n ? n - 1 : 0; - + #else // /proc may be absent; scan up to the soft limit. long maxfd = sysconf(_SC_OPEN_MAX); @@ -331,4 +338,35 @@ namespace mtconnect { #endif } + std::size_t residentBytes() + { +#if defined(_WIN32) + // K32GetProcessMemoryInfo is exported from kernel32, so no psapi.lib link is needed. + PROCESS_MEMORY_COUNTERS pmc {}; + if (!K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) + return 0; + return static_cast(pmc.WorkingSetSize); + +#elif defined(__APPLE__) + mach_task_basic_info_data_t info {}; + mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, + reinterpret_cast(&info), &count) != KERN_SUCCESS) + return 0; + return static_cast(info.resident_size); + +#elif defined(__linux__) + // /proc/self/statm: total resident shared text lib data dt; field 2 = resident pages + std::ifstream f("/proc/self/statm"); + std::size_t total = 0, resident = 0; + if (!(f >> total >> resident)) return 0; + long pageSize = sysconf(_SC_PAGESIZE); + if (pageSize < 0) return 0; + return resident * static_cast(pageSize); + +#else + return 0; +#endif + } + } // namespace mtconnect diff --git a/src/mtconnect/utilities.hpp b/src/mtconnect/utilities.hpp index 4af5fa6a..7d795da7 100644 --- a/src/mtconnect/utilities.hpp +++ b/src/mtconnect/utilities.hpp @@ -42,6 +42,7 @@ #include #include #include +#include #include "mtconnect/config.hpp" #include "mtconnect/logging.hpp" @@ -1024,31 +1025,65 @@ namespace mtconnect { } // namespace url - class FdMonitor { + /// @brief Current number of open file descriptors (handles on Windows) for this process + std::size_t openFdCount(); + + /// @brief Current resident set size (physical memory) of this process in bytes + std::size_t residentBytes(); + + /// @brief Tracks a resource metric over a sliding window and flags suspected leaks. + /// + /// Samples a caller-supplied metric (e.g. open fds or resident memory) on a timer, + /// keeps a high-water mark, and computes a least-squares slope over the window. The + /// metric is flagged `suspect` when it has risen steadily across a full window and is + /// currently at a new high. The growth threshold combines an absolute floor with a + /// fraction of the window mean so the same class works for small counts (fds) and + /// large magnitudes (bytes). + class TrendMonitor + { public: - explicit FdMonitor(std::size_t window = 30) : m_window(window) {} - + /// @brief a source that returns the current value of the metric + using Sampler = std::function; + + /// @param sampler returns the current value of the metric + /// @param window number of samples to retain + /// @param absThreshold minimum slope (units/sample) to consider growth + /// @param relThreshold minimum slope as a fraction of the window mean to consider growth + explicit TrendMonitor(Sampler sampler, std::size_t window = 30, double absThreshold = 0.0, + double relThreshold = 0.0) + : m_sampler(std::move(sampler)), + m_window(window), + m_absThreshold(absThreshold), + m_relThreshold(relThreshold) + {} + // call on a timer (e.g. every 10–30s) struct Report { std::size_t m_current, m_highWater; double m_slope; bool m_suspect; }; - + Report sample() { - std::size_t n = openFdCount(); + std::size_t n = m_sampler(); m_highWater = std::max(m_highWater, n); - + m_samples.push_back(n); if (m_samples.size() > m_window) m_samples.pop_front(); - + double s = slope(); // suspect if steadily rising AND at a new high across the whole window + double threshold = std::max(m_absThreshold, m_relThreshold * mean()); bool suspect = m_samples.size() == m_window - && s > 0.5 // fds gained per sample + && s > threshold && m_samples.back() == m_highWater; return { n, m_highWater, s, suspect }; } - + private: - static std::size_t openFdCount(); - + double mean() const { + if (m_samples.empty()) return 0.0; + double sum = 0.0; + for (auto v : m_samples) sum += double(v); + return sum / double(m_samples.size()); + } + double slope() const { // least-squares over the window std::size_t m = m_samples.size(); if (m < 2) return 0.0; @@ -1060,8 +1095,22 @@ namespace mtconnect { double d = m*sxx - sx*sx; return d == 0.0 ? 0.0 : (m*sxy - sx*sy) / d; } - + + Sampler m_sampler; std::size_t m_window, m_highWater = 0; + double m_absThreshold, m_relThreshold; std::deque m_samples; }; + + /// @brief Monitor for open file descriptors. Growth of >0.5 fds/sample is suspect. + inline TrendMonitor makeFdMonitor(std::size_t window = 30) + { + return TrendMonitor(&openFdCount, window, 0.5, 0.0); + } + + /// @brief Monitor for resident memory. Growth of >1% of the window mean per sample is suspect. + inline TrendMonitor makeMemoryMonitor(std::size_t window = 30) + { + return TrendMonitor(&residentBytes, window, 0.0, 0.01); + } } // namespace mtconnect From b3c777136577b44498b85414e1ce45ca4b6134e5 Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 11:42:19 +0200 Subject: [PATCH 3/9] Added cmake requirement for VS 2026 to fix generator issues. Fixed windows build issue with the *NIX includes for utilities --- conan/profiles/vs32 | 5 +++++ conan/profiles/vs32debug | 7 +++++++ conan/profiles/vs32shared | 6 ++++++ conan/profiles/vs64 | 6 ++++++ conan/profiles/vs64debug | 6 ++++++ conan/profiles/vs64shared | 5 +++++ src/mtconnect/utilities.cpp | 9 +++++---- 7 files changed, 40 insertions(+), 4 deletions(-) diff --git a/conan/profiles/vs32 b/conan/profiles/vs32 index 3a5f8709..80588e5e 100644 --- a/conan/profiles/vs32 +++ b/conan/profiles/vs32 @@ -8,3 +8,8 @@ compiler.runtime=static compiler.runtime_type=Release build_type=Release +[platform_tool_requires] +cmake/4.3.1 + +[replace_tool_requires] +cmake/*: cmake/4.3.1 diff --git a/conan/profiles/vs32debug b/conan/profiles/vs32debug index c88c703e..89406213 100644 --- a/conan/profiles/vs32debug +++ b/conan/profiles/vs32debug @@ -7,3 +7,10 @@ arch=x86 compiler.runtime=static compiler.runtime_type=Debug build_type=Debug + + +[platform_tool_requires] +cmake/4.3.1 + +[replace_tool_requires] +cmake/*: cmake/4.3.1 diff --git a/conan/profiles/vs32shared b/conan/profiles/vs32shared index a06bc079..80c97deb 100644 --- a/conan/profiles/vs32shared +++ b/conan/profiles/vs32shared @@ -8,3 +8,9 @@ compiler.runtime=dynamic compiler.runtime_type=Release build_type=Release + +[platform_tool_requires] +cmake/4.3.1 + +[replace_tool_requires] +cmake/*: cmake/4.3.1 diff --git a/conan/profiles/vs64 b/conan/profiles/vs64 index 3e639b8c..1db3bdcc 100644 --- a/conan/profiles/vs64 +++ b/conan/profiles/vs64 @@ -7,3 +7,9 @@ arch=x86_64 compiler.runtime=static compiler.runtime_type=Release build_type=Release + +[platform_tool_requires] +cmake/4.3 + +[replace_tool_requires] +cmake/*: cmake/4.3 \ No newline at end of file diff --git a/conan/profiles/vs64debug b/conan/profiles/vs64debug index 9445c691..dcba5cbb 100644 --- a/conan/profiles/vs64debug +++ b/conan/profiles/vs64debug @@ -7,3 +7,9 @@ arch=x86_64 compiler.runtime=static compiler.runtime_type=Debug build_type=Debug + +[platform_tool_requires] +cmake/4.3 + +[replace_tool_requires] +cmake/*: cmake/4.3 \ No newline at end of file diff --git a/conan/profiles/vs64shared b/conan/profiles/vs64shared index 13548f25..553587fc 100644 --- a/conan/profiles/vs64shared +++ b/conan/profiles/vs64shared @@ -11,3 +11,8 @@ build_type=Release [options] shared=True +[platform_tool_requires] +cmake/4.3.1 + +[replace_tool_requires] +cmake/*: cmake/4.3.1 diff --git a/src/mtconnect/utilities.cpp b/src/mtconnect/utilities.cpp index f784d276..b54ec173 100644 --- a/src/mtconnect/utilities.cpp +++ b/src/mtconnect/utilities.cpp @@ -47,8 +47,8 @@ #include #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ull -#endif - +#else // _WINDOWS +// Resource management required includes by OS #if defined(__linux__) #include #include @@ -58,10 +58,11 @@ #include #include #include -#else // *BSD +#else // not __linux__ or __APPLE__ #include #include -#endif +#endif // __linux__ or __APPLE__ +#endif // _WINDOWS using namespace std; using namespace std::chrono; From 9ec5c2ab2da4ce050a3854264aa42cb2fad0968e Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 12:10:22 +0200 Subject: [PATCH 4/9] unistd is already included. removed build issue --- src/mtconnect/utilities.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/mtconnect/utilities.cpp b/src/mtconnect/utilities.cpp index b54ec173..3b729fa9 100644 --- a/src/mtconnect/utilities.cpp +++ b/src/mtconnect/utilities.cpp @@ -53,13 +53,10 @@ #include #include #include -#include #elif defined(__APPLE__) #include -#include #include #else // not __linux__ or __APPLE__ -#include #include #endif // __linux__ or __APPLE__ #endif // _WINDOWS From 3e5ef40e172ead27f3146286823292d378fda2da Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 12:13:07 +0200 Subject: [PATCH 5/9] Formatted with clang --- src/mtconnect/agent.cpp | 153 ++++++------- src/mtconnect/agent.hpp | 152 ++++++------- src/mtconnect/asset/asset.cpp | 4 +- src/mtconnect/asset/asset.hpp | 28 +-- src/mtconnect/asset/asset_buffer.hpp | 72 +++--- src/mtconnect/asset/asset_storage.hpp | 22 +- src/mtconnect/buffer/checkpoint.cpp | 34 +-- src/mtconnect/buffer/checkpoint.hpp | 40 ++-- src/mtconnect/buffer/circular_buffer.hpp | 26 +-- src/mtconnect/configuration/agent_config.cpp | 109 +++++---- src/mtconnect/configuration/agent_config.hpp | 97 ++++---- src/mtconnect/configuration/async_context.hpp | 28 +-- .../configuration/config_options.hpp | 2 +- src/mtconnect/configuration/hook_manager.hpp | 26 +-- src/mtconnect/configuration/parser.cpp | 42 ++-- src/mtconnect/configuration/parser.hpp | 4 +- src/mtconnect/configuration/service.cpp | 30 +-- src/mtconnect/configuration/service.hpp | 14 +- src/mtconnect/device_model/agent_device.cpp | 6 +- src/mtconnect/device_model/agent_device.hpp | 6 +- src/mtconnect/device_model/component.cpp | 18 +- src/mtconnect/device_model/component.hpp | 50 ++-- src/mtconnect/device_model/composition.cpp | 2 +- src/mtconnect/device_model/composition.hpp | 2 +- .../configuration/configuration.cpp | 2 +- .../configuration/coordinate_systems.cpp | 2 +- .../device_model/configuration/motion.cpp | 2 +- .../configuration/relationships.cpp | 2 +- .../configuration/sensor_configuration.cpp | 2 +- .../configuration/solid_model.cpp | 2 +- .../configuration/specifications.cpp | 2 +- .../device_model/data_item/data_item.cpp | 36 +-- .../device_model/data_item/data_item.hpp | 70 +++--- .../device_model/data_item/definition.hpp | 6 +- .../device_model/data_item/relationships.hpp | 8 +- .../data_item/unit_conversion.cpp | 10 +- .../data_item/unit_conversion.hpp | 20 +- src/mtconnect/device_model/device.cpp | 14 +- src/mtconnect/device_model/device.hpp | 40 ++-- src/mtconnect/device_model/reference.cpp | 2 +- src/mtconnect/device_model/reference.hpp | 6 +- src/mtconnect/entity/data_set.cpp | 56 ++--- src/mtconnect/entity/data_set.hpp | 42 ++-- src/mtconnect/entity/entity.cpp | 96 ++++---- src/mtconnect/entity/entity.hpp | 182 +++++++-------- src/mtconnect/entity/factory.cpp | 36 +-- src/mtconnect/entity/factory.hpp | 78 +++---- src/mtconnect/entity/json_parser.hpp | 2 +- src/mtconnect/entity/json_printer.hpp | 86 +++---- src/mtconnect/entity/qname.hpp | 20 +- src/mtconnect/entity/requirement.cpp | 92 ++++---- src/mtconnect/entity/requirement.hpp | 76 +++---- src/mtconnect/entity/xml_parser.cpp | 54 ++--- src/mtconnect/entity/xml_parser.hpp | 6 +- src/mtconnect/entity/xml_printer.cpp | 66 +++--- src/mtconnect/entity/xml_printer.hpp | 4 +- src/mtconnect/mqtt/mqtt_client.hpp | 18 +- src/mtconnect/mqtt/mqtt_client_impl.hpp | 32 +-- src/mtconnect/mqtt/mqtt_server.hpp | 8 +- src/mtconnect/mqtt/mqtt_server_impl.hpp | 42 ++-- src/mtconnect/observation/change_observer.cpp | 4 +- src/mtconnect/observation/change_observer.hpp | 38 ++-- src/mtconnect/observation/observation.cpp | 64 +++--- src/mtconnect/observation/observation.hpp | 38 ++-- src/mtconnect/parser/json_parser.cpp | 18 +- src/mtconnect/parser/json_parser.hpp | 10 +- src/mtconnect/parser/xml_parser.cpp | 44 ++-- src/mtconnect/parser/xml_parser.hpp | 14 +- src/mtconnect/pipeline/convert_sample.hpp | 4 +- src/mtconnect/pipeline/correct_timestamp.hpp | 6 +- src/mtconnect/pipeline/deliver.cpp | 18 +- src/mtconnect/pipeline/deliver.hpp | 50 ++-- src/mtconnect/pipeline/delta_filter.hpp | 10 +- src/mtconnect/pipeline/duplicate_filter.hpp | 4 +- src/mtconnect/pipeline/guard.hpp | 58 ++--- src/mtconnect/pipeline/json_mapper.cpp | 98 ++++---- src/mtconnect/pipeline/json_mapper.hpp | 4 +- src/mtconnect/pipeline/message_mapper.hpp | 12 +- .../pipeline/mtconnect_xml_transform.hpp | 16 +- src/mtconnect/pipeline/period_filter.hpp | 24 +- src/mtconnect/pipeline/pipeline.hpp | 56 ++--- src/mtconnect/pipeline/pipeline_context.hpp | 4 +- src/mtconnect/pipeline/pipeline_contract.hpp | 10 +- src/mtconnect/pipeline/response_document.cpp | 74 +++--- src/mtconnect/pipeline/response_document.hpp | 6 +- src/mtconnect/pipeline/shdr_token_mapper.cpp | 56 ++--- src/mtconnect/pipeline/shdr_token_mapper.hpp | 22 +- src/mtconnect/pipeline/shdr_tokenizer.hpp | 20 +- .../pipeline/timestamp_extractor.hpp | 28 +-- src/mtconnect/pipeline/topic_mapper.hpp | 14 +- src/mtconnect/pipeline/transform.hpp | 40 ++-- src/mtconnect/pipeline/upcase_value.hpp | 6 +- src/mtconnect/pipeline/validator.hpp | 12 +- src/mtconnect/printer/json_printer.cpp | 61 ++--- src/mtconnect/printer/json_printer.hpp | 24 +- src/mtconnect/printer/json_printer_helper.hpp | 44 ++-- src/mtconnect/printer/printer.hpp | 22 +- src/mtconnect/printer/xml_printer.cpp | 82 +++---- src/mtconnect/printer/xml_printer.hpp | 54 ++--- src/mtconnect/printer/xml_printer_helper.hpp | 32 +-- src/mtconnect/ruby/embedded.cpp | 18 +- src/mtconnect/ruby/embedded.hpp | 6 +- src/mtconnect/ruby/ruby_agent.hpp | 28 +-- src/mtconnect/ruby/ruby_entity.hpp | 168 +++++++------- src/mtconnect/ruby/ruby_observation.hpp | 30 +-- src/mtconnect/ruby/ruby_pipeline.hpp | 40 ++-- src/mtconnect/ruby/ruby_smart_ptr.hpp | 80 +++---- src/mtconnect/ruby/ruby_transform.hpp | 56 ++--- src/mtconnect/ruby/ruby_type.hpp | 10 +- src/mtconnect/ruby/ruby_vm.hpp | 26 +-- .../mqtt_entity_sink/mqtt_entity_sink.cpp | 2 +- .../mqtt_entity_sink/mqtt_entity_sink.hpp | 2 +- src/mtconnect/sink/mqtt_sink/mqtt_service.cpp | 38 ++-- src/mtconnect/sink/mqtt_sink/mqtt_service.hpp | 22 +- src/mtconnect/sink/rest_sink/cached_file.hpp | 12 +- src/mtconnect/sink/rest_sink/error.hpp | 78 +++---- src/mtconnect/sink/rest_sink/file_cache.cpp | 32 +-- src/mtconnect/sink/rest_sink/file_cache.hpp | 34 +-- src/mtconnect/sink/rest_sink/parameter.hpp | 16 +- src/mtconnect/sink/rest_sink/request.hpp | 8 +- src/mtconnect/sink/rest_sink/response.hpp | 4 +- src/mtconnect/sink/rest_sink/rest_service.cpp | 214 +++++++++--------- src/mtconnect/sink/rest_sink/rest_service.hpp | 169 +++++++------- src/mtconnect/sink/rest_sink/routing.hpp | 70 +++--- src/mtconnect/sink/rest_sink/server.cpp | 32 +-- src/mtconnect/sink/rest_sink/server.hpp | 40 ++-- src/mtconnect/sink/rest_sink/session.hpp | 22 +- src/mtconnect/sink/rest_sink/session_impl.cpp | 40 ++-- src/mtconnect/sink/rest_sink/session_impl.hpp | 28 +-- src/mtconnect/sink/rest_sink/tls_dector.hpp | 10 +- .../rest_sink/websocket_request_manager.hpp | 32 +-- .../sink/rest_sink/websocket_session.hpp | 50 ++-- src/mtconnect/sink/sink.cpp | 8 +- src/mtconnect/sink/sink.hpp | 44 ++-- src/mtconnect/source/adapter/adapter.hpp | 10 +- .../source/adapter/adapter_pipeline.cpp | 18 +- .../source/adapter/adapter_pipeline.hpp | 20 +- .../adapter/agent_adapter/agent_adapter.cpp | 10 +- .../adapter/agent_adapter/agent_adapter.hpp | 34 +-- .../adapter/agent_adapter/http_session.hpp | 8 +- .../adapter/agent_adapter/https_session.hpp | 10 +- .../source/adapter/agent_adapter/session.hpp | 20 +- .../adapter/agent_adapter/session_impl.hpp | 32 +-- .../source/adapter/mqtt/mqtt_adapter.cpp | 30 +-- .../source/adapter/mqtt/mqtt_adapter.hpp | 20 +- .../source/adapter/shdr/connector.cpp | 22 +- .../source/adapter/shdr/connector.hpp | 26 +-- .../source/adapter/shdr/shdr_adapter.cpp | 14 +- .../source/adapter/shdr/shdr_adapter.hpp | 30 +-- .../source/adapter/shdr/shdr_pipeline.cpp | 2 +- .../source/adapter/shdr/shdr_pipeline.hpp | 4 +- src/mtconnect/source/error_code.hpp | 4 +- src/mtconnect/source/loopback_source.cpp | 22 +- src/mtconnect/source/loopback_source.hpp | 24 +- src/mtconnect/source/source.cpp | 10 +- src/mtconnect/source/source.hpp | 38 ++-- src/mtconnect/utilities.cpp | 48 ++-- src/mtconnect/utilities.hpp | 191 +++++++++------- src/mtconnect/validation/observations.hpp | 2 +- test_package/adapter_test.cpp | 8 +- test_package/agent_adapter_test.cpp | 42 ++-- test_package/agent_asset_test.cpp | 34 +-- test_package/agent_device_test.cpp | 4 +- test_package/agent_test.cpp | 62 ++--- test_package/agent_test_helper.cpp | 52 ++--- test_package/agent_test_helper.hpp | 110 ++++----- test_package/asset_buffer_test.cpp | 6 +- test_package/asset_hash_test.cpp | 8 +- test_package/asset_test.cpp | 6 +- test_package/change_observer_test.cpp | 16 +- test_package/checkpoint_test.cpp | 4 +- test_package/circular_buffer_test.cpp | 4 +- test_package/component_parameters_test.cpp | 8 +- test_package/component_test.cpp | 2 +- test_package/composition_test.cpp | 8 +- test_package/config_parser_test.cpp | 2 +- test_package/config_test.cpp | 190 ++++++++-------- test_package/connector_test.cpp | 14 +- test_package/coordinate_system_test.cpp | 8 +- test_package/correct_timestamp_test.cpp | 16 +- test_package/cutting_tool_test.cpp | 18 +- test_package/data_item_mapping_test.cpp | 66 +++--- test_package/data_item_test.cpp | 2 +- test_package/data_set_test.cpp | 16 +- test_package/device_test.cpp | 4 +- test_package/duplicate_filter_test.cpp | 18 +- test_package/embedded_ruby_test.cpp | 38 ++-- test_package/entity_parser_test.cpp | 8 +- test_package/entity_printer_test.cpp | 2 +- test_package/entity_test.cpp | 8 +- test_package/file_asset_test.cpp | 6 +- test_package/file_cache_test.cpp | 8 +- test_package/fixture_test.cpp | 4 +- test_package/image_file_test.cpp | 8 +- test_package/json_device_parser_test.cpp | 4 +- test_package/json_helper.hpp | 6 +- test_package/json_mapping_test.cpp | 42 ++-- test_package/json_parser_test.cpp | 2 +- test_package/json_printer_asset_test.cpp | 6 +- test_package/json_printer_error_test.cpp | 2 +- test_package/json_printer_probe_test.cpp | 2 +- test_package/json_printer_stream_test.cpp | 12 +- test_package/json_printer_test.cpp | 2 +- test_package/kinematics_test.cpp | 10 +- test_package/message_mapping_test.cpp | 30 +-- test_package/mqtt_adapter_test.cpp | 12 +- test_package/mqtt_isolated_test.cpp | 16 +- test_package/mqtt_sink_test.cpp | 24 +- test_package/mtconnect_xml_transform_test.cpp | 14 +- test_package/observation_test.cpp | 24 +- test_package/observation_validation_test.cpp | 34 +-- test_package/pallet_test.cpp | 4 +- test_package/part_test.cpp | 22 +- test_package/period_filter_test.cpp | 36 +-- test_package/physical_asset_test.cpp | 4 +- test_package/pipeline_deliver_test.cpp | 8 +- test_package/pipeline_edit_test.cpp | 24 +- test_package/process_test.cpp | 22 +- test_package/qif_document_test.cpp | 14 +- test_package/qname_test.cpp | 2 +- test_package/raw_material_test.cpp | 6 +- test_package/references_test.cpp | 8 +- test_package/relationship_test.cpp | 6 +- test_package/response_document_test.cpp | 26 +-- test_package/routing_test.cpp | 8 +- test_package/sensor_configuration_test.cpp | 6 +- test_package/shdr_tokenizer_test.cpp | 14 +- test_package/solid_model_test.cpp | 8 +- test_package/specification_test.cpp | 20 +- test_package/table_test.cpp | 36 +-- test_package/target_test.cpp | 6 +- test_package/task_test.cpp | 18 +- test_package/test_utilities.hpp | 38 ++-- test_package/testadapter_service.hpp | 18 +- test_package/testsink_service.hpp | 16 +- test_package/timestamp_extractor_test.cpp | 2 +- test_package/topic_mapping_test.cpp | 32 +-- test_package/unit_conversion_test.cpp | 2 +- test_package/url_parser_test.cpp | 2 +- test_package/utilities_test.cpp | 4 +- test_package/xml_parser_test.cpp | 42 ++-- test_package/xml_printer_test.cpp | 34 +-- 242 files changed, 3536 insertions(+), 3512 deletions(-) diff --git a/src/mtconnect/agent.cpp b/src/mtconnect/agent.cpp index a3d85da7..2a1a4f68 100644 --- a/src/mtconnect/agent.cpp +++ b/src/mtconnect/agent.cpp @@ -81,8 +81,8 @@ namespace mtconnect { static const string g_available("AVAILABLE"); // Agent public methods - Agent::Agent(config::AsyncContext &context, const string &deviceXmlPath, - const ConfigOptions &options) + Agent::Agent(config::AsyncContext& context, const string& deviceXmlPath, + const ConfigOptions& options) : m_options(options), m_context(context), m_strand(m_context), @@ -126,21 +126,22 @@ namespace mtconnect { if (!m_schemaVersion) { - m_xmlParser->parseFile(m_deviceXmlPath, dynamic_cast(m_printers["xml"].get())); + m_xmlParser->parseFile(m_deviceXmlPath, + dynamic_cast(m_printers["xml"].get())); m_schemaVersion = m_xmlParser->getSchemaVersion(); } - + if (m_schemaVersion) { m_intSchemaVersion = IntSchemaVersion(*m_schemaVersion); - for (auto &[k, pr] : m_printers) + for (auto& [k, pr] : m_printers) pr->setSchemaVersion(*m_schemaVersion); } auto sender = GetOption(options, config::Sender); if (sender) { - for (auto &[k, pr] : m_printers) + for (auto& [k, pr] : m_printers) pr->setSenderName(*sender); } } @@ -162,7 +163,7 @@ namespace mtconnect { } m_intSchemaVersion = IntSchemaVersion(*m_schemaVersion); - for (auto &[k, pr] : m_printers) + for (auto& [k, pr] : m_printers) pr->setSchemaVersion(*m_schemaVersion); auto disableAgentDevice = GetOption(m_options, config::DisableAgentDevice); @@ -195,7 +196,7 @@ namespace mtconnect { IsOptionSet(m_options, mtconnect::configuration::Validation)) { m_validation = false; - for (auto &printer : m_printers) + for (auto& printer : m_printers) printer.second->setValidation(false); } @@ -212,7 +213,7 @@ namespace mtconnect { entity::Properties props {{"VALUE", uuid}}; if (m_intSchemaVersion >= SCHEMA_VERSION(2, 2)) { - const auto &hash = device->getProperty("hash"); + const auto& hash = device->getProperty("hash"); if (ValueType(hash.index()) != ValueType::EMPTY) props.insert_or_assign("hash", hash); } @@ -264,7 +265,7 @@ namespace mtconnect { m_afterStartHooks.exec(*this); } - catch (std::runtime_error &e) + catch (std::runtime_error& e) { LOG(fatal) << "Cannot start server: " << e.what(); throw FatalException(e.what()); @@ -333,7 +334,7 @@ namespace mtconnect { if (m_circularBuffer.addToBuffer(observation) != 0) { - for (auto &sink : m_sinks) + for (auto& sink : m_sinks) sink->publish(observation); } } @@ -374,7 +375,7 @@ namespace mtconnect { auto old = m_assetStorage->addAsset(asset); - for (auto &sink : m_sinks) + for (auto& sink : m_sinks) sink->publish(asset); if (device) @@ -405,7 +406,7 @@ namespace mtconnect { if (m_intSchemaVersion >= SCHEMA_VERSION(2, 2)) { - const auto &hash = asset->getProperty("hash"); + const auto& hash = asset->getProperty("hash"); if (ValueType(hash.index()) != ValueType::EMPTY) { props.insert_or_assign("hash", hash); @@ -419,13 +420,13 @@ namespace mtconnect { } } - bool Agent::reloadDevices(const std::string &deviceFile) + bool Agent::reloadDevices(const std::string& deviceFile) { try { // Load the configuration for the Agent auto devices = m_xmlParser->parseFile( - deviceFile, dynamic_cast(m_printers["xml"].get())); + deviceFile, dynamic_cast(m_printers["xml"].get())); if (m_xmlParser->getSchemaVersion() && IntSchemaVersion(*m_xmlParser->getSchemaVersion()) != m_intSchemaVersion) @@ -445,14 +446,14 @@ namespace mtconnect { return true; } - catch (runtime_error &e) + catch (runtime_error& e) { LOG(fatal) << "Error loading xml configuration: " + deviceFile; LOG(fatal) << "Error detail: " << e.what(); cerr << e.what() << endl; throw FatalException(e.what()); } - catch (exception &f) + catch (exception& f) { LOG(fatal) << "Error loading xml configuration: " + deviceFile; LOG(fatal) << "Error detail: " << f.what(); @@ -461,11 +462,11 @@ namespace mtconnect { } } - void Agent::loadDeviceXml(const string &deviceXml, const optional source) + void Agent::loadDeviceXml(const string& deviceXml, const optional source) { try { - auto printer = dynamic_cast(m_printers["xml"].get()); + auto printer = dynamic_cast(m_printers["xml"].get()); auto device = m_xmlParser->parseDevice(deviceXml, printer); if (device == nullptr) { @@ -476,13 +477,13 @@ namespace mtconnect { loadDevices({device}, source); } } - catch (runtime_error &e) + catch (runtime_error& e) { LOG(error) << "Error loading device: " << deviceXml; LOG(error) << "Error detail: " << e.what(); cerr << e.what() << endl; } - catch (exception &f) + catch (exception& f) { LOG(error) << "Error loading device: " << deviceXml; LOG(error) << "Error detail: " << f.what(); @@ -498,7 +499,7 @@ namespace mtconnect { return; } - auto callback = [=, this](config::AsyncContext &context) { + auto callback = [=, this](config::AsyncContext& context) { try { bool changed = false; @@ -532,7 +533,7 @@ namespace mtconnect { auto adapter = std::dynamic_pointer_cast(src); if (adapter) { - auto &options = adapter->getOptions(); + auto& options = adapter->getOptions(); auto dev = GetOption(options, config::Device); if (dev == oldName || dev == oldUuid) { @@ -546,11 +547,11 @@ namespace mtconnect { if (changed) loadCachedProbe(); } - catch (FatalException &e) + catch (FatalException& e) { throw e; } - catch (runtime_error &e) + catch (runtime_error& e) { for (auto device : devices) { @@ -559,7 +560,7 @@ namespace mtconnect { LOG(error) << "Error detail: " << e.what(); cerr << e.what() << endl; } - catch (exception &f) + catch (exception& f) { for (auto device : devices) { @@ -611,7 +612,7 @@ namespace mtconnect { if (version) versionDeviceXml(); - for (auto &sink : m_sinks) + for (auto& sink : m_sinks) sink->publish(device); return true; @@ -635,7 +636,7 @@ namespace mtconnect { // Remove the old data items set skip; - for (auto &di : oldDev->getDeviceDataItems()) + for (auto& di : oldDev->getDeviceDataItems()) { if (!di.expired()) { @@ -670,7 +671,7 @@ namespace mtconnect { entity::Properties props {{"VALUE", *uuid}}; if (m_intSchemaVersion >= SCHEMA_VERSION(2, 2)) { - const auto &hash = device->getProperty("hash"); + const auto& hash = device->getProperty("hash"); if (ValueType(hash.index()) != ValueType::EMPTY) props.insert_or_assign("hash", hash); } @@ -679,7 +680,7 @@ namespace mtconnect { m_loopback->receive(d, props); } - for (auto &sink : m_sinks) + for (auto& sink : m_sinks) sink->publish(device); return true; @@ -717,7 +718,7 @@ namespace mtconnect { { std::list list; copy_if(m_deviceIndex.begin(), m_deviceIndex.end(), back_inserter(list), - [](DevicePtr d) { return dynamic_cast(d.get()) == nullptr; }); + [](DevicePtr d) { return dynamic_cast(d.get()) == nullptr; }); auto probe = printer->printProbe(0, 0, 0, 0, 0, list, nullptr, true, true); ofstream devices(file.string()); @@ -733,13 +734,13 @@ namespace mtconnect { } } - bool Agent::removeAsset(DevicePtr device, const std::string &id, + bool Agent::removeAsset(DevicePtr device, const std::string& id, const std::optional time) { auto asset = m_assetStorage->removeAsset(id); if (asset) { - for (auto &sink : m_sinks) + for (auto& sink : m_sinks) sink->publish(asset); notifyAssetRemoved(device, asset); @@ -755,7 +756,7 @@ namespace mtconnect { bool Agent::removeAllAssets(const std::optional device, const std::optional type, - const std::optional time, asset::AssetList &list) + const std::optional time, asset::AssetList& list) { std::optional uuid; DevicePtr dev; @@ -769,7 +770,7 @@ namespace mtconnect { } auto count = m_assetStorage->removeAll(list, uuid, type, time); - for (auto &asset : list) + for (auto& asset : list) { notifyAssetRemoved(nullptr, asset); } @@ -787,14 +788,14 @@ namespace mtconnect { return count > 0; } - void Agent::notifyAssetRemoved(DevicePtr device, const asset::AssetPtr &asset) + void Agent::notifyAssetRemoved(DevicePtr device, const asset::AssetPtr& asset) { if (device || asset->getDeviceUuid()) { auto dev = device; if (!device) { - auto &idx = m_deviceIndex.get(); + auto& idx = m_deviceIndex.get(); auto it = idx.find(*asset->getDeviceUuid()); if (it != idx.end()) dev = *it; @@ -855,7 +856,7 @@ namespace mtconnect { dynamic_pointer_cast(AgentDevice::getFactory()->make("Agent", ps, errors)); if (!errors.empty()) { - for (auto &e : errors) + for (auto& e : errors) LOG(fatal) << "Error creating the agent device: " << e->what(); throw FatalException("Cannot create AgentDevice"); } @@ -866,7 +867,7 @@ namespace mtconnect { // Device management and Initialization // ---------------------------------------------- - std::list Agent::loadXMLDeviceFile(const std::string &configXmlPath) + std::list Agent::loadXMLDeviceFile(const std::string& configXmlPath) { NAMED_SCOPE("Agent::loadXMLDeviceFile"); @@ -874,7 +875,7 @@ namespace mtconnect { { // Load the configuration for the Agent auto devices = m_xmlParser->parseFile( - configXmlPath, dynamic_cast(m_printers["xml"].get())); + configXmlPath, dynamic_cast(m_printers["xml"].get())); if (!m_schemaVersion && m_xmlParser->getSchemaVersion() && !m_xmlParser->getSchemaVersion()->empty()) @@ -890,14 +891,14 @@ namespace mtconnect { return devices; } - catch (runtime_error &e) + catch (runtime_error& e) { LOG(fatal) << "Error loading xml configuration: " + configXmlPath; LOG(fatal) << "Error detail: " << e.what(); cerr << e.what() << endl; throw FatalException(e.what()); } - catch (exception &f) + catch (exception& f) { LOG(fatal) << "Error loading xml configuration: " + configXmlPath; LOG(fatal) << "Error detail: " << f.what(); @@ -1013,7 +1014,7 @@ namespace mtconnect { else { // Check for single valued constrained data items. - const string *value = &g_unavailable; + const string* value = &g_unavailable; if (d->isCondition()) value = &g_unavailable; else if (d->getConstantValue()) @@ -1032,7 +1033,7 @@ namespace mtconnect { // Check if device already exists string uuid = *device->getUuid(); - auto &idx = m_deviceIndex.get(); + auto& idx = m_deviceIndex.get(); auto old = idx.find(uuid); if (old != idx.end()) { @@ -1061,7 +1062,7 @@ namespace mtconnect { entity::Properties props {{"VALUE", uuid}}; if (m_intSchemaVersion >= SCHEMA_VERSION(2, 2)) { - const auto &hash = device->getProperty("hash"); + const auto& hash = device->getProperty("hash"); if (ValueType(hash.index()) != ValueType::EMPTY) props.insert_or_assign("hash", hash); } @@ -1075,11 +1076,11 @@ namespace mtconnect { if (m_intSchemaVersion >= SCHEMA_VERSION(2, 2)) device->addHash(); - for (auto &printer : m_printers) + for (auto& printer : m_printers) printer.second->setModelChangeTime(getCurrentTime(GMT_UV_SEC)); } - void Agent::deviceChanged(DevicePtr device, const std::string &uuid) + void Agent::deviceChanged(DevicePtr device, const std::string& uuid) { NAMED_SCOPE("Agent::deviceChanged"); @@ -1099,7 +1100,7 @@ namespace mtconnect { if (changed) { // Create a new device - auto xmlPrinter = dynamic_cast(m_printers["xml"].get()); + auto xmlPrinter = dynamic_cast(m_printers["xml"].get()); auto newDevice = m_xmlParser->parseDevice(xmlPrinter->printDevice(device), xmlPrinter); newDevice->setUuid(uuid); @@ -1118,7 +1119,7 @@ namespace mtconnect { device->updateReferences(idMap); // Update the data item map. - for (auto &id : idMap) + for (auto& id : idMap) { auto di = device->getDeviceDataItem(id.second); if (auto it = m_dataItemMap.find(id.first); it != m_dataItemMap.end()) @@ -1135,10 +1136,10 @@ namespace mtconnect { NAMED_SCOPE("Agent::loadCachedProbe"); // Reload the document for path resolution - auto xmlPrinter = dynamic_cast(m_printers["xml"].get()); + auto xmlPrinter = dynamic_cast(m_printers["xml"].get()); m_xmlParser->loadDocument(xmlPrinter->printProbe(0, 0, 0, 0, 0, getDevices())); - for (auto &printer : m_printers) + for (auto& printer : m_printers) printer.second->setModelChangeTime(getCurrentTime(GMT_UV_SEC)); } @@ -1146,12 +1147,12 @@ namespace mtconnect { // Helper Methods // ---------------------------------------------------- - DevicePtr Agent::getDeviceByName(const std::string &name) const + DevicePtr Agent::getDeviceByName(const std::string& name) const { if (name.empty()) return getDefaultDevice(); - auto &idx = m_deviceIndex.get(); + auto& idx = m_deviceIndex.get(); auto devPos = idx.find(name); if (devPos != idx.end()) return *devPos; @@ -1159,12 +1160,12 @@ namespace mtconnect { return nullptr; } - DevicePtr Agent::getDeviceByName(const std::string &name) + DevicePtr Agent::getDeviceByName(const std::string& name) { if (name.empty()) return getDefaultDevice(); - auto &idx = m_deviceIndex.get(); + auto& idx = m_deviceIndex.get(); auto devPos = idx.find(name); if (devPos != idx.end()) return *devPos; @@ -1172,7 +1173,7 @@ namespace mtconnect { return nullptr; } - DevicePtr Agent::findDeviceByUUIDorName(const std::string &idOrName) const + DevicePtr Agent::findDeviceByUUIDorName(const std::string& idOrName) const { if (idOrName.empty()) return getDefaultDevice(); @@ -1223,7 +1224,7 @@ namespace mtconnect { } void AgentPipelineContract::deliverConnectStatus(entity::EntityPtr entity, - const StringList &devices, bool autoAvailable) + const StringList& devices, bool autoAvailable) { auto value = entity->getValue(); if (value == "CONNECTING") @@ -1265,7 +1266,7 @@ namespace mtconnect { } } - void Agent::connecting(const std::string &adapter) + void Agent::connecting(const std::string& adapter) { if (m_agentDevice) { @@ -1276,7 +1277,7 @@ namespace mtconnect { } // Add values for related data items UNAVAILABLE - void Agent::disconnected(const std::string &adapter, const StringList &devices, + void Agent::disconnected(const std::string& adapter, const StringList& devices, bool autoAvailable) { LOG(debug) << "Disconnected from adapter, setting all values to UNAVAILABLE"; @@ -1288,7 +1289,7 @@ namespace mtconnect { m_loopback->receive(di, "CLOSED"); } - for (auto &name : devices) + for (auto& name : devices) { DevicePtr device = findDeviceByUUIDorName(name); if (device == nullptr) @@ -1309,7 +1310,7 @@ namespace mtconnect { if (ptr) { - const string *value = nullptr; + const string* value = nullptr; if (dataItem->getConstantValue()) value = &dataItem->getConstantValue().value(); else if (!ptr->isUnavailable()) @@ -1325,7 +1326,7 @@ namespace mtconnect { } } - void Agent::connected(const std::string &adapter, const StringList &devices, bool autoAvailable) + void Agent::connected(const std::string& adapter, const StringList& devices, bool autoAvailable) { if (m_agentDevice) { @@ -1337,7 +1338,7 @@ namespace mtconnect { if (!autoAvailable) return; - for (auto &name : devices) + for (auto& name : devices) { DevicePtr device = findDeviceByUUIDorName(name); if (device == nullptr) @@ -1357,7 +1358,7 @@ namespace mtconnect { } } - void Agent::sourceFailed(const std::string &identity) + void Agent::sourceFailed(const std::string& identity) { auto source = findSource(identity); if (source) @@ -1366,7 +1367,7 @@ namespace mtconnect { m_sources.remove(source); bool ext = false; - for (auto &s : m_sources) + for (auto& s : m_sources) { if (!s->isLoopback()) { @@ -1397,8 +1398,8 @@ namespace mtconnect { // Validation methods // ----------------------------------------------- - string Agent::devicesAndPath(const std::optional &path, const DevicePtr device, - const std::optional &deviceType) const + string Agent::devicesAndPath(const std::optional& path, const DevicePtr device, + const std::optional& deviceType) const { string dataPath; @@ -1441,7 +1442,7 @@ namespace mtconnect { void AgentPipelineContract::deliverAssetCommand(entity::EntityPtr command) { - const std::string &cmd = command->getValue(); + const std::string& cmd = command->getValue(); if (cmd == "RemoveAsset") { string id = command->get("assetId"); @@ -1464,7 +1465,7 @@ namespace mtconnect { } } - void Agent::updateAssetCounts(const DevicePtr &device, const std::optional type) + void Agent::updateAssetCounts(const DevicePtr& device, const std::optional type) { if (!device) return; @@ -1490,7 +1491,7 @@ namespace mtconnect { DataSet set; - for (auto &[t, count] : counts) + for (auto& [t, count] : counts) { if (count > 0) set.emplace(t, int64_t(count)); @@ -1503,8 +1504,8 @@ namespace mtconnect { } } - void Agent::receiveCommand(const std::string &deviceName, const std::string &command, - const std::string &value, const std::string &source) + void Agent::receiveCommand(const std::string& deviceName, const std::string& command, + const std::string& value, const std::string& source) { DevicePtr device {nullptr}; device = findDeviceByUUIDorName(deviceName); @@ -1514,15 +1515,15 @@ namespace mtconnect { LOG(warning) << source << ": Cannot find device for name " << deviceName; } - static std::unordered_map> + static std::unordered_map> deviceCommands { {"manufacturer", mem_fn(&Device::setManufacturer)}, {"station", mem_fn(&Device::setStation)}, {"serialnumber", mem_fn(&Device::setSerialNumber)}, {"description", mem_fn(&Device::setDescriptionValue)}, {"nativename", - [](DevicePtr device, const string &name) { device->setProperty("nativeName", name); }}, - {"calibration", [](DevicePtr device, const string &value) { + [](DevicePtr device, const string& name) { device->setProperty("nativeName", name); }}, + {"calibration", [](DevicePtr device, const string& value) { istringstream line(value); // Look for name|factor|offset triples @@ -1568,7 +1569,7 @@ namespace mtconnect { { if (!device->preserveUuid()) { - auto &idx = m_deviceIndex.get(); + auto& idx = m_deviceIndex.get(); auto it = idx.find(*device->getUuid()); if (it != idx.end()) { diff --git a/src/mtconnect/agent.hpp b/src/mtconnect/agent.hpp index 9f05dc72..024ce51b 100644 --- a/src/mtconnect/agent.hpp +++ b/src/mtconnect/agent.hpp @@ -91,43 +91,43 @@ namespace mtconnect { /// - VersionDeviceXml /// - JsonVersion /// - DisableAgentDevice - Agent(configuration::AsyncContext &context, const std::string &deviceXmlPath, - const ConfigOptions &options); + Agent(configuration::AsyncContext& context, const std::string& deviceXmlPath, + const ConfigOptions& options); /// Destructor for the Agent. /// > Note: Does not stop the agent. ~Agent(); /// @brief Hook callback type - using Hook = std::function; + using Hook = std::function; /// @brief Functions to run before the agent begins the initialization process. /// @return configuration::HookManager& - auto &beforeInitializeHooks() { return m_beforeInitializeHooks; } + auto& beforeInitializeHooks() { return m_beforeInitializeHooks; } /// @brief Function that run after all agent initialization is complete /// @return configuration::HookManager& - auto &afterInitializeHooks() { return m_afterInitializeHooks; } + auto& afterInitializeHooks() { return m_afterInitializeHooks; } /// @brief Hooks to run when before the agent starts all the soures and sinks /// @return configuration::HookManager& - auto &beforeStartHooks() { return m_beforeStartHooks; } + auto& beforeStartHooks() { return m_beforeStartHooks; } /// @brief Hooks to run when after the agent starts all the soures and sinks /// @return configuration::HookManager& - auto &afterStartHooks() { return m_afterStartHooks; } + auto& afterStartHooks() { return m_afterStartHooks; } /// @brief Hooks before the agent stops all the sources and sinks /// @return configuration::HookManager& - auto &beforeStopHooks() { return m_beforeStopHooks; } + auto& beforeStopHooks() { return m_beforeStopHooks; } /// @brief Hooks before the agent versions and write the device xml file /// @return configuration::HookManager& - auto &beforeDeviceXmlUpdateHooks() { return m_beforeDeviceXmlUpdateHooks; } + auto& beforeDeviceXmlUpdateHooks() { return m_beforeDeviceXmlUpdateHooks; } /// @brief Hooks after the agent versions and write the device xml file /// @return configuration::HookManager& - auto &afterDeviceXmlUpdateHooks() { return m_afterDeviceXmlUpdateHooks; } + auto& afterDeviceXmlUpdateHooks() { return m_afterDeviceXmlUpdateHooks; } /// @brief the agent given a pipeline context /// @param context: the pipeline context shared between all pipelines @@ -145,7 +145,7 @@ namespace mtconnect { /// @brief Get the boost asio io context /// @return boost::asio::io_context - auto &getContext() { return m_context; } + auto& getContext() { return m_context; } /// @brief Create a contract for pipelines to access agent information /// @return A contract between the pipeline and this agent @@ -159,15 +159,15 @@ namespace mtconnect { sink::SinkContractPtr makeSinkContract(); /// @brief Get a reference to the XML parser /// @return The XML parser - const auto &getXmlParser() const { return m_xmlParser; } + const auto& getXmlParser() const { return m_xmlParser; } /// @brief Get a reference to the circular buffer. Used by sinks to /// get latest and historical data. /// @return A reference to the circular buffer - auto &getCircularBuffer() { return m_circularBuffer; } + auto& getCircularBuffer() { return m_circularBuffer; } /// @brief Get a const reference to the circular buffer. Used by sinks to /// get latest and historical data. /// @return A const reference to the circular buffer - const auto &getCircularBuffer() const { return m_circularBuffer; } + const auto& getCircularBuffer() const { return m_circularBuffer; } /// @brief Adds an adapter to the agent /// @param[in] source: shared pointer to the source being added @@ -182,9 +182,9 @@ namespace mtconnect { /// @brief Find a source by name /// @param[in] name the identity to find /// @return A shared pointer to the source if found, otherwise nullptr - source::SourcePtr findSource(const std::string &name) const + source::SourcePtr findSource(const std::string& name) const { - for (auto &s : m_sources) + for (auto& s : m_sources) { if (s->getIdentity() == name || s->getName() == name) return s; @@ -194,9 +194,9 @@ namespace mtconnect { /// @brief Find a sink by name /// @param name the name to find /// @return A shared pointer to the sink if found, otherwise nullptr - sink::SinkPtr findSink(const std::string &name) const + sink::SinkPtr findSink(const std::string& name) const { - for (auto &s : m_sinks) + for (auto& s : m_sinks) if (s->getName() == name) return s; @@ -205,14 +205,14 @@ namespace mtconnect { /// @brief Get the list of all sources /// @return The list of all source in the agent - const auto &getSources() const { return m_sources; } + const auto& getSources() const { return m_sources; } /// @brief Get the list of all sinks /// @return The list of all sinks in the agent - const auto &getSinks() const { return m_sinks; } + const auto& getSinks() const { return m_sinks; } /// @brief Get the MTConnect schema version the agent is supporting /// @return The MTConnect schema version as a string - const auto &getSchemaVersion() const { return m_schemaVersion; } + const auto& getSchemaVersion() const { return m_schemaVersion; } /// @brief Get the validation state of the agent /// @returns the validation state of the agent @@ -225,15 +225,15 @@ namespace mtconnect { /// @brief Find a device by name /// @param[in] name The name of the device to find /// @return A shared pointer to the device - DevicePtr getDeviceByName(const std::string &name); + DevicePtr getDeviceByName(const std::string& name); /// @brief Find a device by name (Const Version) /// @param[in] name The name of the device to find /// @return A shared pointer to the device - DevicePtr getDeviceByName(const std::string &name) const; + DevicePtr getDeviceByName(const std::string& name) const; /// @brief Finds the device given either its UUID or its name /// @param[in] idOrName The uuid or name of the device /// @return A shared pointer to the device - DevicePtr findDeviceByUUIDorName(const std::string &idOrName) const; + DevicePtr findDeviceByUUIDorName(const std::string& idOrName) const; /// @brief Gets the list of devices /// @return The list of devices owned by the caller const auto getDevices() const @@ -267,7 +267,7 @@ namespace mtconnect { /// @brief Get a pointer to the asset storage object /// @return A pointer to the asset storage object - asset::AssetStorage *getAssetStorage() { return m_assetStorage.get(); } + asset::AssetStorage* getAssetStorage() { return m_assetStorage.get(); } /// @brief Add a device to the agent /// @param[in] device The device to add. @@ -277,11 +277,11 @@ namespace mtconnect { /// @param[in] device The modified device /// @param[in] oldUuid The old uuid /// @param[in] oldName The old name - void deviceChanged(DevicePtr device, const std::string &uuid); + void deviceChanged(DevicePtr device, const std::string& uuid); /// @brief Reload the devices from a device file after updates /// @param[in] deviceFile The device file to load /// @return true if successful - bool reloadDevices(const std::string &deviceFile); + bool reloadDevices(const std::string& deviceFile); /// @brief receive a single device from a source /// @param[in] deviceXml the device xml as a string @@ -292,7 +292,7 @@ namespace mtconnect { /// @brief receive and parse a single device from a source /// @param[in] deviceXml the device xml as a string /// @param[in] source the source loading the device - void loadDeviceXml(const std::string &deviceXml, + void loadDeviceXml(const std::string& deviceXml, const std::optional source = std::nullopt); /// @name Message when source has connected and disconnected @@ -300,19 +300,19 @@ namespace mtconnect { /// @brief Called when source begins trying to connect /// @param source The source identity - void connecting(const std::string &source); + void connecting(const std::string& source); /// @brief Called when source is disconnected /// @param[in] source The source identity /// @param[in] devices The list of devices associated with this source /// @param[in] autoAvailable `true` if the source should automatically set available to /// `UNAVAILABLE` - void disconnected(const std::string &source, const StringList &devices, bool autoAvailable); + void disconnected(const std::string& source, const StringList& devices, bool autoAvailable); /// @brief Called when source is connected /// @param source The source identity /// @param[in] devices The list of devices associated with this source /// @param[in] autoAvailable `true` if the source should automatically set available to /// `AVAILABLE` - void connected(const std::string &source, const StringList &devices, bool autoAvailable); + void connected(const std::string& source, const StringList& devices, bool autoAvailable); ///@} @@ -321,8 +321,8 @@ namespace mtconnect { /// @param[in] command The command being sent /// @param[in] value The value of the command /// @param[in] source The identity of the source - void receiveCommand(const std::string &device, const std::string &command, - const std::string &value, const std::string &source); + void receiveCommand(const std::string& device, const std::string& command, + const std::string& value, const std::string& source); /// @brief Method to get a data item for a device /// @param[in] deviceName The name or uuid of the device @@ -330,8 +330,8 @@ namespace mtconnect { /// @return Shared pointer to the data item if found /// @note Cover method for `findDeviceByUUIDorName()` and `DataItem::getDeviceDataItem()` from /// the device. - DataItemPtr getDataItemForDevice(const std::string &deviceName, - const std::string &dataItemName) const + DataItemPtr getDataItemForDevice(const std::string& deviceName, + const std::string& dataItemName) const { auto dev = findDeviceByUUIDorName(deviceName); return (dev) ? dev->getDeviceDataItem(dataItemName) : nullptr; @@ -340,7 +340,7 @@ namespace mtconnect { /// @brief Get a data item by its id. /// @param id Unique id of the data item /// @return Shared pointer to the data item if found - DataItemPtr getDataItemById(const std::string &id) const + DataItemPtr getDataItemById(const std::string& id) const { auto diPos = m_dataItemMap.find(id); if (diPos != m_dataItemMap.end()) @@ -367,7 +367,7 @@ namespace mtconnect { /// @param[in] id The asset id /// @param[in] time The timestamp the remove occurred at /// @return `true` if the asset was found and removed - bool removeAsset(DevicePtr device, const std::string &id, + bool removeAsset(DevicePtr device, const std::string& id, const std::optional time = std::nullopt); /// @brief Removes all assets for by device, type, or device and type /// @param[in] device Optional device name or uuid @@ -377,7 +377,7 @@ namespace mtconnect { /// @return `true` if any assets were found bool removeAllAssets(const std::optional device, const std::optional type, const std::optional time, - asset::AssetList &list); + asset::AssetList& list); /// @brief Send asset changed and added observation when an asset is removed. /// /// Also sets asset changed and added to `UNAVAILABLE` if the asset removed asset was the last @@ -385,13 +385,13 @@ namespace mtconnect { /// /// @param device The device related to the asset /// @param asset The asset - void notifyAssetRemoved(DevicePtr device, const asset::AssetPtr &asset); + void notifyAssetRemoved(DevicePtr device, const asset::AssetPtr& asset); ///@} /// @brief Method called by source when it cannot continue /// @param identity identity of the source - void sourceFailed(const std::string &identity); + void sourceFailed(const std::string& identity); /// @name For testing ///@{ @@ -405,7 +405,7 @@ namespace mtconnect { /// @param type The mime type /// @return pointer to the printer or nullptr if it does not exist /// @note Currently `xml` and `json` are supported. - printer::Printer *getPrinter(const std::string &type) const + printer::Printer* getPrinter(const std::string& type) const { auto printer = m_printers.find(type); if (printer != m_printers.end()) @@ -416,7 +416,7 @@ namespace mtconnect { /// @brief Get the map of available printers /// @return A const reference to the printer map - const auto &getPrinters() const { return m_printers; } + const auto& getPrinters() const { return m_printers; } /// @brief Prefixes the path with the device and rewrites the composed /// paths by repeating the prefix. The resulting path is valid @@ -436,8 +436,8 @@ namespace mtconnect { /// @param[in] device Optional device if one device is specified /// @param[in] deviceType optional Agent or Device selector /// @return The rewritten path properly prefixed - std::string devicesAndPath(const std::optional &path, const DevicePtr device, - const std::optional &deviceType = std::nullopt) const; + std::string devicesAndPath(const std::optional& path, const DevicePtr device, + const std::optional& deviceType = std::nullopt) const; /// @brief Creates unique ids for the device model and maps to the originals /// @@ -449,14 +449,14 @@ namespace mtconnect { /// @brief get agent options /// @returns constant reference to option map - const auto &getOptions() const { return m_options; } + const auto& getOptions() const { return m_options; } protected: friend class AgentPipelineContract; // Initialization methods void createAgentDevice(); - std::list loadXMLDeviceFile(const std::string &config); + std::list loadXMLDeviceFile(const std::string& config); void verifyDevice(DevicePtr device); void initializeDataItems(DevicePtr device, std::optional> skip = std::nullopt); @@ -464,18 +464,18 @@ namespace mtconnect { void versionDeviceXml(); // Asset count management - void updateAssetCounts(const DevicePtr &device, const std::optional type); + void updateAssetCounts(const DevicePtr& device, const std::optional type); - observation::ObservationPtr getLatest(const std::string &id) + observation::ObservationPtr getLatest(const std::string& id) { return m_circularBuffer.getLatest().getObservation(id); } - observation::ObservationPtr getLatest(const DataItemPtr &di) { return getLatest(di->getId()); } + observation::ObservationPtr getLatest(const DataItemPtr& di) { return getLatest(di->getId()); } protected: ConfigOptions m_options; - configuration::AsyncContext &m_context; + configuration::AsyncContext& m_context; boost::asio::io_context::strand m_strand; std::shared_ptr m_loopback; @@ -517,16 +517,16 @@ namespace mtconnect { struct ExtractDeviceUuid { using result_type = std::string; - const result_type &operator()(const DevicePtr &d) const { return *d->getUuid(); } - result_type operator()(const DevicePtr &d) { return *d->getUuid(); } + const result_type& operator()(const DevicePtr& d) const { return *d->getUuid(); } + result_type operator()(const DevicePtr& d) { return *d->getUuid(); } }; /// @brief Device name extractor for multi-index struct ExtractDeviceName { using result_type = std::string; - const result_type &operator()(const DevicePtr &d) const { return *d->getComponentName(); } - result_type operator()(DevicePtr &d) { return *d->getComponentName(); } + const result_type& operator()(const DevicePtr& d) const { return *d->getComponentName(); } + result_type operator()(DevicePtr& d) { return *d->getComponentName(); } }; /// @brief Devuce multi-index @@ -568,14 +568,14 @@ namespace mtconnect { class AGENT_LIB_API AgentPipelineContract : public pipeline::PipelineContract { public: - AgentPipelineContract(Agent *agent) : m_agent(agent) {} + AgentPipelineContract(Agent* agent) : m_agent(agent) {} ~AgentPipelineContract() = default; - DevicePtr findDevice(const std::string &device) override + DevicePtr findDevice(const std::string& device) override { return m_agent->findDeviceByUUIDorName(device); } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { DevicePtr dev = m_agent->findDeviceByUUIDorName(device); if (dev != nullptr) @@ -586,7 +586,7 @@ namespace mtconnect { } void eachDataItem(EachDataItem fun) override { - for (auto &di : m_agent->m_dataItemMap) + for (auto& di : m_agent->m_dataItemMap) { auto ldi = di.second.lock(); if (ldi) @@ -601,7 +601,7 @@ namespace mtconnect { } void deliverAsset(asset::AssetPtr asset) override { m_agent->receiveAsset(asset); } void deliverAssetCommand(entity::EntityPtr command) override; - void deliverConnectStatus(entity::EntityPtr, const StringList &devices, + void deliverConnectStatus(entity::EntityPtr, const StringList& devices, bool autoAvailable) override; void deliverCommand(entity::EntityPtr) override; void deliverDevice(DevicePtr device) override @@ -610,15 +610,15 @@ namespace mtconnect { } void deliverDevices(std::list devices) override { m_agent->loadDevices(devices); } - void sourceFailed(const std::string &identity) override { m_agent->sourceFailed(identity); } + void sourceFailed(const std::string& identity) override { m_agent->sourceFailed(identity); } - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return m_agent->getCircularBuffer().checkDuplicate(obs); } protected: - Agent *m_agent; + Agent* m_agent; }; inline std::unique_ptr Agent::makePipelineContract() @@ -630,47 +630,47 @@ namespace mtconnect { class AGENT_LIB_API AgentSinkContract : public sink::SinkContract { public: - AgentSinkContract(Agent *agent) : m_agent(agent) {} + AgentSinkContract(Agent* agent) : m_agent(agent) {} ~AgentSinkContract() = default; - printer::Printer *getPrinter(const std::string &aType) const override + printer::Printer* getPrinter(const std::string& aType) const override { return m_agent->getPrinter(aType); } // Get device from device map - DevicePtr getDeviceByName(const std::string &name) const override + DevicePtr getDeviceByName(const std::string& name) const override { return m_agent->getDeviceByName(name); } - DevicePtr findDeviceByUUIDorName(const std::string &idOrName) const override + DevicePtr findDeviceByUUIDorName(const std::string& idOrName) const override { return m_agent->findDeviceByUUIDorName(idOrName); } const std::list getDevices() const override { return m_agent->getDevices(); } DevicePtr getDefaultDevice() const override { return m_agent->getDefaultDevice(); } - DataItemPtr getDataItemById(const std::string &id) const override + DataItemPtr getDataItemById(const std::string& id) const override { return m_agent->getDataItemById(id); } void addSource(source::SourcePtr source) override { m_agent->addSource(source); } // Asset information - asset::AssetStorage *getAssetStorage() override { return m_agent->getAssetStorage(); } - const PrinterMap &getPrinters() const override { return m_agent->getPrinters(); } + asset::AssetStorage* getAssetStorage() override { return m_agent->getAssetStorage(); } + const PrinterMap& getPrinters() const override { return m_agent->getPrinters(); } - void getDataItemsForPath(const DevicePtr device, const std::optional &path, - FilterSet &filter, - const std::optional &deviceType) const override + void getDataItemsForPath(const DevicePtr device, const std::optional& path, + FilterSet& filter, + const std::optional& deviceType) const override { std::string dataPath = m_agent->devicesAndPath(path, device, deviceType); - const auto &parser = m_agent->getXmlParser(); + const auto& parser = m_agent->getXmlParser(); parser->getDataItems(filter, dataPath); } - buffer::CircularBuffer &getCircularBuffer() override { return m_agent->getCircularBuffer(); } + buffer::CircularBuffer& getCircularBuffer() override { return m_agent->getCircularBuffer(); } - configuration::HookManager &getHooks(HookType type) override + configuration::HookManager& getHooks(HookType type) override { using namespace sink; switch (type) @@ -713,7 +713,7 @@ namespace mtconnect { } protected: - Agent *m_agent; + Agent* m_agent; }; inline sink::SinkContractPtr Agent::makeSinkContract() diff --git a/src/mtconnect/asset/asset.cpp b/src/mtconnect/asset/asset.cpp index b2a7765a..cd7830c0 100644 --- a/src/mtconnect/asset/asset.cpp +++ b/src/mtconnect/asset/asset.cpp @@ -36,7 +36,7 @@ namespace mtconnect { Requirement("timestamp", ValueType::TIMESTAMP, false), Requirement("hash", false), Requirement("Configuration", ValueType::ENTITY, Configuration::getFactory(), false), Requirement("removed", ValueType::BOOL, false)}), - [](const std::string &name, Properties &props) -> EntityPtr { + [](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); @@ -51,7 +51,7 @@ namespace mtconnect { return asset; } - void Asset::registerAssetType(const std::string &type, FactoryPtr factory) + void Asset::registerAssetType(const std::string& type, FactoryPtr factory) { auto root = getRoot(); root->registerFactory(type, factory); diff --git a/src/mtconnect/asset/asset.hpp b/src/mtconnect/asset/asset.hpp index 537f7138..2797448d 100644 --- a/src/mtconnect/asset/asset.hpp +++ b/src/mtconnect/asset/asset.hpp @@ -45,7 +45,7 @@ namespace mtconnect { /// @brief Abstract Asset constructor /// @param name asset name, sometimes referred to as the asset type /// @param props asset properties - Asset(const std::string &name, const entity::Properties &props) + Asset(const std::string& name, const entity::Properties& props) : entity::Entity(name, props), m_removed(false) { auto removed = maybeGet("removed"); @@ -55,7 +55,7 @@ namespace mtconnect { /// @brief an assets identity is its `assetId` property /// @return the `assetId` - const entity::Value &getIdentity() const override { return getProperty("assetId"); } + const entity::Value& getIdentity() const override { return getProperty("assetId"); } /// @brief get the static asset factory /// @return shared pointer to the factory @@ -69,7 +69,7 @@ namespace mtconnect { /// Special handling of `removed`. If `true` sets the asset state to removed. /// @param key property `key` /// @param v property value - void setProperty(const std::string &key, const entity::Value &v) override + void setProperty(const std::string& key, const entity::Value& v) override { entity::Value r = v; if (key == "removed") @@ -84,23 +84,23 @@ namespace mtconnect { } /// @brief Set a property /// @param property the property - void setProperty(const entity::Property &property) { Entity::setProperty(property); } + void setProperty(const entity::Property& property) { Entity::setProperty(property); } /// @brief Cover method for `getName()` - const auto &getType() const { return getName(); } + const auto& getType() const { return getName(); } /// @brief gets the asset id /// /// Every asset must have an asset id. /// @return the assets identity /// @throws PropertyError if there is no assetId - const std::string &getAssetId() const + const std::string& getAssetId() const { if (m_assetId.empty()) { - const auto &v = getProperty("assetId"); + const auto& v = getProperty("assetId"); if (std::holds_alternative(v)) - *const_cast(&m_assetId) = std::get(v); + *const_cast(&m_assetId) = std::get(v); else throw entity::PropertyError("Asset has no assetId"); } @@ -108,7 +108,7 @@ namespace mtconnect { } /// @brief Set the asset id /// @param id the id - void setAssetId(const std::string &id) + void setAssetId(const std::string& id) { m_assetId = id; setProperty("assetId", id); @@ -120,7 +120,7 @@ namespace mtconnect { /// @return optional device uuid const std::optional getDeviceUuid() const { - const auto &v = getProperty("deviceUuid"); + const auto& v = getProperty("deviceUuid"); if (std::holds_alternative(v)) return std::get(v); else @@ -130,7 +130,7 @@ namespace mtconnect { /// @return optional timestamp if available const std::optional getTimestamp() const { - const auto &v = getProperty("timestamp"); + const auto& v = getProperty("timestamp"); if (std::holds_alternative(v)) return std::get(v); else @@ -146,12 +146,12 @@ namespace mtconnect { /// @brief register the factory for an asset type /// @param t the type or name of the asset /// @param factory the factory to create assets - static void registerAssetType(const std::string &t, entity::FactoryPtr factory); + static void registerAssetType(const std::string& t, entity::FactoryPtr factory); /// @brief compares two asset ids /// @param another other asset /// @return `true` if they have the same asset id - bool operator==(const Asset &another) const { return getAssetId() == another.getAssetId(); } + bool operator==(const Asset& another) const { return getAssetId() == another.getAssetId(); } protected: /// @brief The virtual method that covers `hash(boost::uuids::detail::sha1&, @@ -160,7 +160,7 @@ namespace mtconnect { /// Override to skip the `hash`, `timestamp`, and `removed` properties. /// /// @param[in,out] sha1 The boost sha1 accumulator - void hash(::boost::uuids::detail::sha1 &sha1) const override + void hash(::boost::uuids::detail::sha1& sha1) const override { static const ::boost::unordered_set skip {"hash", "timestamp", "removed"}; entity::Entity::hash(sha1, skip); diff --git a/src/mtconnect/asset/asset_buffer.hpp b/src/mtconnect/asset/asset_buffer.hpp index 6acb7ba5..7f5647d3 100644 --- a/src/mtconnect/asset/asset_buffer.hpp +++ b/src/mtconnect/asset/asset_buffer.hpp @@ -54,17 +54,17 @@ namespace mtconnect::asset { /// @brief Structure to store asset for boost multi index container struct AssetNode { - AssetNode(AssetPtr &asset) : m_asset(asset), m_identity(asset->getAssetId()) {} + AssetNode(AssetPtr& asset) : m_asset(asset), m_identity(asset->getAssetId()) {} ~AssetNode() = default; using element_type = AssetPtr; - const std::string &getAssetId() const { return m_identity; } - const std::string &getType() const { return m_asset->getType(); } - const std::string &getDeviceUuid() const + const std::string& getAssetId() const { return m_identity; } + const std::string& getType() const { return m_asset->getType(); } + const std::string& getDeviceUuid() const { static const std::string unknown {"UNKNOWN"}; - const auto &dev = m_asset->getProperty("deviceUuid"); + const auto& dev = m_asset->getProperty("deviceUuid"); if (std::holds_alternative(dev)) return std::get(dev); else @@ -72,7 +72,7 @@ namespace mtconnect::asset { } bool isRemoved() const { return m_asset->isRemoved(); } - bool operator<(const AssetNode &o) const { return m_identity < o.m_identity; } + bool operator<(const AssetNode& o) const { return m_identity < o.m_identity; } AssetPtr operator*() const { return m_asset; } @@ -144,7 +144,7 @@ namespace mtconnect::asset { if (!added.second) { old = added.first->m_asset; - m_index.modify(added.first, [&asset](AssetNode &n) { n.m_asset = asset; }); + m_index.modify(added.first, [&asset](AssetNode& n) { n.m_asset = asset; }); m_index.relocate(m_index.begin(), added.first); if (asset->isRemoved() && !old->isRemoved()) adjustCount(asset, 1); @@ -165,13 +165,13 @@ namespace mtconnect::asset { return old; } - AssetPtr removeAsset(const std::string &id, - const std::optional &time = std::nullopt) override + AssetPtr removeAsset(const std::string& id, + const std::optional& time = std::nullopt) override { AssetPtr asset {}; std::lock_guard lock(m_bufferLock); - auto &idx = m_index.get(); + auto& idx = m_index.get(); auto it = idx.find(id); if (it != idx.end()) { @@ -188,10 +188,10 @@ namespace mtconnect::asset { return asset; } - AssetPtr getAsset(const std::string &id) const override + AssetPtr getAsset(const std::string& id) const override { std::lock_guard lock(m_bufferLock); - const auto &idx = m_index.get(); + const auto& idx = m_index.get(); auto it = idx.find(id); if (it != idx.end()) return it->m_asset; @@ -199,7 +199,7 @@ namespace mtconnect::asset { return nullptr; } - virtual size_t getAssets(AssetList &list, size_t max, const bool active = true, + virtual size_t getAssets(AssetList& list, size_t max, const bool active = true, const std::optional device = std::nullopt, const std::optional type = std::nullopt) const override { @@ -219,11 +219,11 @@ namespace mtconnect::asset { } else { - auto &idx = m_index.get(); + auto& idx = m_index.get(); range = std::make_pair(idx.begin(), idx.end()); } - for (auto &a : range) + for (auto& a : range) { if (!active || !a.isRemoved()) list.push_back(a.m_asset); @@ -234,7 +234,7 @@ namespace mtconnect::asset { return list.size(); } - virtual size_t getAssets(AssetList &list, const std::list &ids) const override + virtual size_t getAssets(AssetList& list, const std::list& ids) const override { for (auto id : ids) { @@ -245,7 +245,7 @@ namespace mtconnect::asset { return list.size(); } - size_t getCountForDeviceAndType(const std::string &device, const std::string &type, + size_t getCountForDeviceAndType(const std::string& device, const std::string& type, bool active = true) const override { using namespace boost::adaptors; @@ -257,7 +257,7 @@ namespace mtconnect::asset { activePredicate(active)); } - size_t getCountForType(const std::string &type, bool active = true) const override + size_t getCountForType(const std::string& type, bool active = true) const override { using namespace boost::adaptors; @@ -266,7 +266,7 @@ namespace mtconnect::asset { return boost::count_if(m_index.get().equal_range(type), activePredicate(active)); } - size_t getCountForDevice(const std::string &device, bool active = true) const override + size_t getCountForDevice(const std::string& device, bool active = true) const override { std::lock_guard lock(m_bufferLock); @@ -278,12 +278,12 @@ namespace mtconnect::asset { { std::lock_guard lock(m_bufferLock); TypeCount res; - auto &idx = m_index.get(); + auto& idx = m_index.get(); auto it = idx.begin(); while (it != idx.end()) { int delta = 0; - auto &type = it->getType(); + auto& type = it->getType(); auto rng = idx.equal_range(type); if (active) { @@ -299,20 +299,20 @@ namespace mtconnect::asset { return res; } - TypeCount getCountsByTypeForDevice(const std::string &device, bool active = true) const override + TypeCount getCountsByTypeForDevice(const std::string& device, bool active = true) const override { std::lock_guard lock(m_bufferLock); TypeCount res; - auto &idx = m_index.get(); + auto& idx = m_index.get(); auto removes = m_deviceRemoveCount.find(device); - const auto *ridx {removes == m_deviceRemoveCount.end() ? nullptr : &removes->second}; + const auto* ridx {removes == m_deviceRemoveCount.end() ? nullptr : &removes->second}; auto range = idx.equal_range(std::make_tuple(device)); auto it = range.first; while (it != range.second) { int delta = 0; - auto &type = it->getType(); + auto& type = it->getType(); auto rng = idx.equal_range(std::make_tuple(device, type)); if (ridx != nullptr && active) { @@ -328,25 +328,25 @@ namespace mtconnect::asset { return res; } - size_t removeAll(AssetList &list, const std::optional device = std::nullopt, + size_t removeAll(AssetList& list, const std::optional device = std::nullopt, const std::optional type = std::nullopt, - const std::optional &time = std::nullopt) override + const std::optional& time = std::nullopt) override { std::lock_guard lock(m_bufferLock); getAssets(list, std::numeric_limits().max(), false, device, type); - for (auto &a : list) + for (auto& a : list) removeAsset(a->getAssetId(), time); return list.size(); } - int32_t getIndex(const std::string &id) const + int32_t getIndex(const std::string& id) const { - auto &idx = m_index.get(); + auto& idx = m_index.get(); auto it = idx.find(id); if (it != idx.end()) { - auto &fifo = m_index.get(); + auto& fifo = m_index.get(); auto pos = mic::project(m_index, it); return int32_t(std::distance(fifo.begin(), pos)); } @@ -357,8 +357,8 @@ namespace mtconnect::asset { protected: void adjustCount(AssetPtr asset, int delta) { - const auto &type = asset->getType(); - const auto &dev = asset->getDeviceUuid(); + const auto& type = asset->getType(); + const auto& dev = asset->getDeviceUuid(); bool found = false; if (dev) @@ -392,12 +392,12 @@ namespace mtconnect::asset { } } - std::function activePredicate(bool active) const + std::function activePredicate(bool active) const { if (active) - return [](const AssetNode &a) -> bool { return !a.isRemoved(); }; + return [](const AssetNode& a) -> bool { return !a.isRemoved(); }; else - return [](const AssetNode &a) -> bool { return true; }; + return [](const AssetNode& a) -> bool { return true; }; } protected: diff --git a/src/mtconnect/asset/asset_storage.hpp b/src/mtconnect/asset/asset_storage.hpp index 564c0012..529e6f9e 100644 --- a/src/mtconnect/asset/asset_storage.hpp +++ b/src/mtconnect/asset/asset_storage.hpp @@ -78,18 +78,18 @@ namespace mtconnect { /// @param[in] id the assetId /// @param[in] time the timestamp for the removal /// @return shared pointer to the removed asset if found - virtual AssetPtr removeAsset(const std::string &id, - const std::optional &time = std::nullopt) = 0; + virtual AssetPtr removeAsset(const std::string& id, + const std::optional& time = std::nullopt) = 0; /// @brief Remove assets by device and type /// @param[out] list list of assets removed /// @param[in] device optional device to filter assets /// @param[in] type optional type to filter assets /// @param[in] time optional timestamp, defaults to now /// @return the number of assets removed - virtual size_t removeAll(AssetList &list, + virtual size_t removeAll(AssetList& list, const std::optional device = std::nullopt, const std::optional type = std::nullopt, - const std::optional &time = std::nullopt) = 0; + const std::optional& time = std::nullopt) = 0; ///@} /// @name Retrival @@ -98,7 +98,7 @@ namespace mtconnect { /// @brief get an asset by its assetId /// @param[in] id the assetId /// @return shared point to the asset if found - virtual AssetPtr getAsset(const std::string &id) const = 0; + virtual AssetPtr getAsset(const std::string& id) const = 0; /// @brief get a list of assets with optional filters /// @param[out] list returned list of assets /// @param[in] max maximum number of assets to find @@ -106,14 +106,14 @@ namespace mtconnect { /// @param[in] device optional device uuid to select /// @param[in] type optional type to select /// @return the number of assets found - virtual size_t getAssets(AssetList &list, size_t max, const bool active = true, + virtual size_t getAssets(AssetList& list, size_t max, const bool active = true, const std::optional device = std::nullopt, const std::optional type = std::nullopt) const = 0; /// @brief get a list of assets given a list of asset ids /// @param[out] list list of assets /// @param[in] ids assetIds to find /// @return the number of assets found - virtual size_t getAssets(AssetList &list, const std::list &ids) const = 0; + virtual size_t getAssets(AssetList& list, const std::list& ids) const = 0; ///@} /// @name Count related methods @@ -124,24 +124,24 @@ namespace mtconnect { /// @param[in] type the type of asset /// @param[in] active `false` to skip removed assets /// @return the number of assets - virtual size_t getCountForDeviceAndType(const std::string &device, const std::string &type, + virtual size_t getCountForDeviceAndType(const std::string& device, const std::string& type, bool active = true) const = 0; /// @brief get count of a type of asset for all devices /// @param[in] type the type /// @param[in] active `false` to skip removed assets /// @return the number of assets - virtual size_t getCountForType(const std::string &type, bool active = true) const = 0; + virtual size_t getCountForType(const std::string& type, bool active = true) const = 0; /// @brief get count of all types of assets for a device /// @param[in] device the device uuid /// @param[in] active `false` to skip removed assets /// @return the number of assets - virtual size_t getCountForDevice(const std::string &device, bool active = true) const = 0; + virtual size_t getCountForDevice(const std::string& device, bool active = true) const = 0; /// @brief get the count by types for a device /// @param[in] device the device uuid /// @param[in] active `false` to skip removed assets /// @return a map of types and their counts - virtual TypeCount getCountsByTypeForDevice(const std::string &device, + virtual TypeCount getCountsByTypeForDevice(const std::string& device, bool active = true) const = 0; ///@} diff --git a/src/mtconnect/buffer/checkpoint.cpp b/src/mtconnect/buffer/checkpoint.cpp index 33f55f7f..8d2e011f 100644 --- a/src/mtconnect/buffer/checkpoint.cpp +++ b/src/mtconnect/buffer/checkpoint.cpp @@ -25,7 +25,7 @@ namespace mtconnect { using namespace observation; using namespace entity; namespace buffer { - Checkpoint::Checkpoint(const Checkpoint &checkpoint, const FilterSetOpt &filterSet) + Checkpoint::Checkpoint(const Checkpoint& checkpoint, const FilterSetOpt& filterSet) { FilterSetOpt filter; if (!filterSet && checkpoint.hasFilter()) @@ -40,10 +40,10 @@ namespace mtconnect { Checkpoint::~Checkpoint() { clear(); } - void Checkpoint::addObservation(ConditionPtr event, ObservationPtr &&old) + void Checkpoint::addObservation(ConditionPtr event, ObservationPtr&& old) { bool assign = true; - Condition *cond = dynamic_cast(old.get()); + Condition* cond = dynamic_cast(old.get()); if (cond->getLevel() != Condition::NORMAL && event->getLevel() != Condition::NORMAL && cond->getLevel() != Condition::UNAVAILABLE && event->getLevel() != Condition::UNAVAILABLE) { @@ -93,7 +93,7 @@ namespace mtconnect { old = event; } - void Checkpoint::addObservation(const DataSetEventPtr event, ObservationPtr &&old) + void Checkpoint::addObservation(const DataSetEventPtr event, ObservationPtr&& old) { if (!event->isUnavailable() && !old->isUnavailable() && !event->hasProperty("resetTriggered")) { @@ -101,9 +101,9 @@ namespace mtconnect { DataSet set = old->getValue(); // For data sets merge the maps together - for (auto &e : event->getValue()) + for (auto& e : event->getValue()) { - const auto &oe = set.find(e); + const auto& oe = set.find(e); if (oe != set.end()) set.erase(oe); if (!e.m_removed) @@ -130,7 +130,7 @@ namespace mtconnect { } auto item = obs->getDataItem(); - const auto &id = item->getId(); + const auto& id = item->getId(); auto old = m_observations.find(id); if (old != m_observations.end()) @@ -158,7 +158,7 @@ namespace mtconnect { } } - void Checkpoint::copy(const Checkpoint &checkpoint, const FilterSetOpt &filterSet) + void Checkpoint::copy(const Checkpoint& checkpoint, const FilterSetOpt& filterSet) { clear(); @@ -167,14 +167,14 @@ namespace mtconnect { m_filter = filterSet; } - for (const auto &event : checkpoint.m_observations) + for (const auto& event : checkpoint.m_observations) { if (!m_filter || m_filter->count(event.first) > 0) m_observations[event.first] = event.second; } } - static inline void addToList(ObservationList &list, ObservationPtr obs) + static inline void addToList(ObservationList& list, ObservationPtr obs) { if (obs->getDataItem()->isCondition()) { @@ -189,11 +189,11 @@ namespace mtconnect { } } - void Checkpoint::getObservations(ObservationList &list, const FilterSetOpt &filterSet) const + void Checkpoint::getObservations(ObservationList& list, const FilterSetOpt& filterSet) const { if (filterSet) { - for (const auto &id : *filterSet) + for (const auto& id : *filterSet) { auto obs = m_observations.find(id); if (obs != m_observations.end() && !obs->second->isOrphan()) @@ -204,7 +204,7 @@ namespace mtconnect { } else { - for (const auto &obs : m_observations) + for (const auto& obs : m_observations) { if (!obs.second->isOrphan()) { @@ -214,7 +214,7 @@ namespace mtconnect { } } - void Checkpoint::filter(const FilterSet &filterSet) + void Checkpoint::filter(const FilterSet& filterSet) { m_filter = filterSet; @@ -240,8 +240,8 @@ namespace mtconnect { } } - ObservationPtr Checkpoint::dataSetDifference(const ObservationPtr &obs, - const ConstObservationPtr &old) const + ObservationPtr Checkpoint::dataSetDifference(const ObservationPtr& obs, + const ConstObservationPtr& old) const { if (obs->isOrphan()) return nullptr; @@ -251,7 +251,7 @@ namespace mtconnect { if (!setEvent->getDataSet().empty() && !obs->hasProperty("resetTriggered")) { auto oldEvent = dynamic_pointer_cast(old); - auto &oldSet = oldEvent->getDataSet(); + auto& oldSet = oldEvent->getDataSet(); DataSet eventSet = setEvent->getDataSet(); bool changed = false; diff --git a/src/mtconnect/buffer/checkpoint.hpp b/src/mtconnect/buffer/checkpoint.hpp index c8653c29..1528f64a 100644 --- a/src/mtconnect/buffer/checkpoint.hpp +++ b/src/mtconnect/buffer/checkpoint.hpp @@ -39,7 +39,7 @@ namespace mtconnect::buffer { /// @brief Copy constructor for a checkpoint /// @param[in] checkpoint the previous checkpoint /// @param[in] filterSet an optional set of data item ids for filtering - Checkpoint(const Checkpoint &checkpoint, const FilterSetOpt &filterSet = std::nullopt); + Checkpoint(const Checkpoint& checkpoint, const FilterSetOpt& filterSet = std::nullopt); ~Checkpoint(); /// @brief Add an observation to the checkpoint @@ -51,25 +51,25 @@ namespace mtconnect::buffer { /// @param[in] old the previous value of the data set /// @return The observation or a copy if the data set changed observation::ObservationPtr dataSetDifference( - const observation::ObservationPtr &observation, - const observation::ConstObservationPtr &old) const; + const observation::ObservationPtr& observation, + const observation::ConstObservationPtr& old) const; /// @brief Checks if the observation is a duplicate with existing observations /// @param[in] obs the observation /// @return an observation, possibly changed if it is not a duplicate. `nullptr` if it is a /// duplicate.. - const observation::ObservationPtr checkDuplicate(const observation::ObservationPtr &obs) const + const observation::ObservationPtr checkDuplicate(const observation::ObservationPtr& obs) const { using namespace observation; using namespace std; auto di = obs->getDataItem(); - const auto &id = di->getId(); + const auto& id = di->getId(); auto old = m_observations.find(id); if (old != m_observations.end()) { - auto &oldObs = old->second; + auto& oldObs = old->second; // Filter out unavailable duplicates, only allow through changed // state. If both are unavailable, disregard. if (obs->isUnavailable() != oldObs->isUnavailable()) @@ -79,8 +79,8 @@ namespace mtconnect::buffer { if (di->isCondition()) { - auto *cond = dynamic_cast(obs.get()); - auto *oldCond = dynamic_cast(oldObs.get()); + auto* cond = dynamic_cast(obs.get()); + auto* oldCond = dynamic_cast(oldObs.get()); // Check for normal resetting all conditions. If there are // no active conditions, then this is a duplicate normal @@ -94,7 +94,7 @@ namespace mtconnect::buffer { // If there is already an active condition with this code, // then check if nothing has changed between activations. - if (const auto &e = oldCond->find(cond->getCode())) + if (const auto& e = oldCond->find(cond->getCode())) { if (cond->getLevel() != e->getLevel()) return obs; @@ -132,8 +132,8 @@ namespace mtconnect::buffer { } else { - auto &value = obs->getValue(); - auto &oldValue = oldObs->getValue(); + auto& value = obs->getValue(); + auto& oldValue = oldObs->getValue(); if (value == oldValue) return nullptr; @@ -148,20 +148,20 @@ namespace mtconnect::buffer { /// @brief copy another checkpoint to this checkpoint /// @param[in] checkpoint a checkpoint to copy /// @param[in] filterSet an optional filter set - void copy(Checkpoint const &checkpoint, const FilterSetOpt &filterSet = std::nullopt); + void copy(Checkpoint const& checkpoint, const FilterSetOpt& filterSet = std::nullopt); /// @brief clear the contents of this checkpoint void clear(); /// @brief Add a filter to the checkpoint - void filter(const FilterSet &filterSet); + void filter(const FilterSet& filterSet); /// @brief does this checkpoint have a filter? /// @return `true` if a checkpoint exists bool hasFilter() const { return bool(m_filter); } /// @brief get a map of data item id to observation shared pointers /// @return a map of ids to observations - const std::unordered_map &getObservations() const + const std::unordered_map& getObservations() const { return m_observations; } @@ -172,7 +172,7 @@ namespace mtconnect::buffer { /// changed. The new data item shared pointer will replace the old. /// /// @param[in] diMap the map of data ids to data item pointers - void updateDataItems(std::unordered_map &diMap) + void updateDataItems(std::unordered_map& diMap) { auto iter = m_observations.begin(); while (iter != m_observations.end()) @@ -193,13 +193,13 @@ namespace mtconnect::buffer { /// @brief Get a list of observations from the checkpoint /// @param[in,out] list the list to add the observations to /// @param[in] filter an optional filter for the observations - void getObservations(observation::ObservationList &list, - const FilterSetOpt &filter = std::nullopt) const; + void getObservations(observation::ObservationList& list, + const FilterSetOpt& filter = std::nullopt) const; /// @brief Get an observation for a data item id /// @param[in] id the data item id /// @return shared pointer to the observation if it exists - observation::ObservationPtr getObservation(const std::string &id) const + observation::ObservationPtr getObservation(const std::string& id) const { auto pos = m_observations.find(id); if (pos != m_observations.end()) @@ -208,9 +208,9 @@ namespace mtconnect::buffer { } protected: - void addObservation(observation::ConditionPtr event, observation::ObservationPtr &&old); + void addObservation(observation::ConditionPtr event, observation::ObservationPtr&& old); void addObservation(const observation::DataSetEventPtr event, - observation::ObservationPtr &&old); + observation::ObservationPtr&& old); protected: std::unordered_map m_observations; diff --git a/src/mtconnect/buffer/circular_buffer.hpp b/src/mtconnect/buffer/circular_buffer.hpp index 2763dfa9..d500b30f 100644 --- a/src/mtconnect/buffer/circular_buffer.hpp +++ b/src/mtconnect/buffer/circular_buffer.hpp @@ -82,9 +82,9 @@ namespace mtconnect::buffer { /// @brief update the data item references when device model changes /// @param diMap the map of data item ids to new data item entities - void updateDataItems(std::unordered_map &diMap) + void updateDataItems(std::unordered_map& diMap) { - for (auto &o : m_slidingBuffer) + for (auto& o : m_slidingBuffer) { if (o->isOrphan()) { @@ -97,7 +97,7 @@ namespace mtconnect::buffer { m_first.updateDataItems(diMap); m_latest.updateDataItems(diMap); - for (auto &cp : m_checkpoints) + for (auto& cp : m_checkpoints) { cp->updateDataItems(diMap); } @@ -121,7 +121,7 @@ namespace mtconnect::buffer { /// /// @param observation the observation /// @return the sequence number of the observation - SequenceNumber_t addToBuffer(observation::ObservationPtr &observation) + SequenceNumber_t addToBuffer(observation::ObservationPtr& observation) { if (observation->isOrphan()) return 0; @@ -172,17 +172,17 @@ namespace mtconnect::buffer { /// @brief Get the checkpoint at the end of the circular buffer /// @return reference to the checkpoint - const Checkpoint &getLatest() const { return m_latest; } + const Checkpoint& getLatest() const { return m_latest; } /// @brief Get the checkpoint at the beginning of the circular buffer /// @return reference to the checkpoint - const Checkpoint &getFirst() const { return m_first; } + const Checkpoint& getFirst() const { return m_first; } auto getCheckpointFreq() const { return m_checkpointFreq; } auto getCheckpointCount() const { return m_checkpointCount; } /// @brief Check if observation is a duplicate by validating against the latest checkpoint /// @param[in] obs the observation to check /// @return `true` if the observation is a duplicate - const observation::ObservationPtr checkDuplicate(const observation::ObservationPtr &obs) const + const observation::ObservationPtr checkDuplicate(const observation::ObservationPtr& obs) const { std::lock_guard lock(m_sequenceLock); return m_latest.checkDuplicate(obs); @@ -193,7 +193,7 @@ namespace mtconnect::buffer { /// @param filterSet the filter to apply to the new checkpoint /// @return a unique point to a new checkpoint std::unique_ptr getCheckpointAt(SequenceNumber_t at, - const FilterSetOpt &filterSet) const + const FilterSetOpt& filterSet) const { std::lock_guard lock(m_sequenceLock); @@ -250,9 +250,9 @@ namespace mtconnect::buffer { /// @param[out] endOfBuffer `true` if the last sequence is at the end of the buffer /// @return unique pointer to a list of shared observation pointers std::unique_ptr getObservations( - int count, const FilterSetOpt &filterSet, const std::optional start, - const std::optional to, SequenceNumber_t &end, SequenceNumber_t &firstSeq, - bool &endOfBuffer) const + int count, const FilterSetOpt& filterSet, const std::optional start, + const std::optional to, SequenceNumber_t& end, SequenceNumber_t& firstSeq, + bool& endOfBuffer) const { auto results = std::make_unique(); @@ -292,10 +292,10 @@ namespace mtconnect::buffer { for (int added = 0; added < limit && i < max && i >= min; i += inc) { // Filter out according to if it exists in the list - auto &event = m_slidingBuffer[i]; + auto& event = m_slidingBuffer[i]; if (!event->isOrphan()) { - const std::string &dataId = event->getDataItem()->getId(); + const std::string& dataId = event->getDataItem()->getId(); if (!filterSet || filterSet->count(dataId) > 0) { results->push_back(event); diff --git a/src/mtconnect/configuration/agent_config.cpp b/src/mtconnect/configuration/agent_config.cpp index 6585e96d..d12928bd 100644 --- a/src/mtconnect/configuration/agent_config.cpp +++ b/src/mtconnect/configuration/agent_config.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -53,7 +54,6 @@ #include #include #include -#include #include "mtconnect/agent.hpp" #include "mtconnect/configuration/config_options.hpp" @@ -79,7 +79,7 @@ #if defined(_WINDOWS) #if WINVER < 0x0600 #include "shlwapi.h" -#define stat(P, B) (PathFileExists((const char *)P) ? 0 : -1) +#define stat(P, B) (PathFileExists((const char*)P) ? 0 : -1) #endif #endif @@ -104,7 +104,8 @@ BOOST_LOG_ATTRIBUTE_KEYWORD(utc_timestamp, "Timestamp", logr::attributes::utc_cl namespace mtconnect::configuration { AgentConfiguration::AgentConfiguration() - : m_context {make_unique()}, m_monitorFilesTimer(m_context->get()), + : m_context {make_unique()}, + m_monitorFilesTimer(m_context->get()), m_monitorResourceTimer(m_context->get()) { NAMED_SCOPE("AgentConfiguration::AgentConfiguration"); @@ -156,7 +157,7 @@ namespace mtconnect::configuration { #endif } - void AgentConfiguration::initialize(const boost::program_options::variables_map &options) + void AgentConfiguration::initialize(const boost::program_options::variables_map& options) { NAMED_SCOPE("AgentConfiguration::initialize"); @@ -205,11 +206,11 @@ namespace mtconnect::configuration { logPaths(LOG_LEVEL(fatal), m_configPaths); cerr << "Agent failed to load: Cannot find configuration file: '" << configFile << ", evaluated paths: " << std::endl; - for (auto &p : m_configPaths) + for (auto& p : m_configPaths) cerr << " " << p << endl; usage(1); } - catch (std::exception &e) + catch (std::exception& e) { cerr << std::endl << "Agent failed to load: " << e.what() << " from " << m_configFile << std::endl; @@ -236,7 +237,7 @@ namespace mtconnect::configuration { #endif m_context.reset(); - for (auto &[channelName, logChannel] : m_logChannels) + for (auto& [channelName, logChannel] : m_logChannels) logChannel.m_logSink.reset(); m_logChannels.clear(); @@ -335,7 +336,7 @@ namespace mtconnect::configuration { m_agent->stop(); m_context->pause( - [this](AsyncContext &context) { + [this](AsyncContext& context) { m_agent.reset(); m_configTime.reset(); m_deviceTime.reset(); @@ -362,7 +363,7 @@ namespace mtconnect::configuration { LOG(warning) << "Monitor thread has detected change in devices files."; LOG(warning) << "... Reloading Devices File: " << m_devicesFile; - m_context->pause([this](AsyncContext &context) { + m_context->pause([this](AsyncContext& context) { if (!m_agent->reloadDevices(m_devicesFile)) { m_configTime.emplace(m_configTime->min()); @@ -372,7 +373,8 @@ namespace mtconnect::configuration { using std::placeholders::_1; m_monitorFilesTimer.expires_after(100ms); - m_monitorFilesTimer.async_wait(boost::bind(&AgentConfiguration::monitorFiles, this, _1)); + m_monitorFilesTimer.async_wait( + boost::bind(&AgentConfiguration::monitorFiles, this, _1)); } else { @@ -396,12 +398,12 @@ namespace mtconnect::configuration { m_monitorFilesTimer.expires_after(m_monitorInterval); m_monitorFilesTimer.async_wait(boost::bind(&AgentConfiguration::monitorFiles, this, _1)); } - + void AgentConfiguration::monitorResources(boost::system::error_code ec) { using namespace chrono; using namespace chrono_literals; - + using std::placeholders::_1; if (ec == boost::asio::error::operation_aborted) @@ -412,16 +414,14 @@ namespace mtconnect::configuration { auto fd = m_fdMonitor.sample(); LOG(info) << "Open file descriptors: Current: " << fd.m_current - << ", high water: " << fd.m_highWater - << ", slope: " << fd.m_slope + << ", high water: " << fd.m_highWater << ", slope: " << fd.m_slope << ", suspect: " << fd.m_suspect; constexpr double MiB = 1024.0 * 1024.0; auto mem = m_memoryMonitor.sample(); LOG(info) << "Resident memory (MiB): Current: " << (mem.m_current / MiB) << ", high water: " << (mem.m_highWater / MiB) - << ", slope (bytes/sample): " << mem.m_slope - << ", suspect: " << mem.m_suspect; + << ", slope (bytes/sample): " << mem.m_slope << ", suspect: " << mem.m_suspect; m_monitorResourceTimer.expires_after(15s); m_monitorResourceTimer.async_wait(boost::bind(&AgentConfiguration::monitorResources, this, _1)); @@ -434,7 +434,7 @@ namespace mtconnect::configuration { // Start the file monitor to check for changes to cfg or devices. LOG(debug) << "Waiting for monitor thread to exit to restart agent"; - m_agent->beforeDeviceXmlUpdateHooks().add([this](Agent &agent) { + m_agent->beforeDeviceXmlUpdateHooks().add([this](Agent& agent) { LOG(info) << "Reseting device file time because agent updated the device XML file"; m_deviceTime.reset(); }); @@ -472,11 +472,11 @@ namespace mtconnect::configuration { void AgentConfiguration::setLoggingLevel(const logr::trivial::severity_level level) { - for (auto &[channelName, logChannel] : m_logChannels) + for (auto& [channelName, logChannel] : m_logChannels) logChannel.m_logLevel = level; } - static logr::trivial::severity_level StringToLogLevel(const std::string &level) + static logr::trivial::severity_level StringToLogLevel(const std::string& level) { using namespace logr::trivial; string_view lev(level.c_str()); @@ -485,7 +485,7 @@ namespace mtconnect::configuration { struct compare { - bool operator()(const string_view &s1, const string_view &s2) const + bool operator()(const string_view& s1, const string_view& s2) const { return boost::ilexicographical_compare(s1, s2); } @@ -505,14 +505,14 @@ namespace mtconnect::configuration { return res->second; } - logr::trivial::severity_level AgentConfiguration::setLoggingLevel(const string &level) + logr::trivial::severity_level AgentConfiguration::setLoggingLevel(const string& level) { logr::trivial::severity_level l = StringToLogLevel(level); setLoggingLevel(l); return l; } - void AgentConfiguration::configureLogger(const ptree &config) + void AgentConfiguration::configureLogger(const ptree& config) { using namespace logr::trivial; namespace expr = logr::expressions; @@ -541,14 +541,14 @@ namespace mtconnect::configuration { } void AgentConfiguration::configureLoggerChannel( - const std::string &channelName, const ptree &config, + const std::string& channelName, const ptree& config, std::optional> formatter) { using namespace logr::trivial; namespace expr = logr::expressions; namespace kw = boost::log::keywords; - auto &logChannel = m_logChannels[channelName]; + auto& logChannel = m_logChannels[channelName]; if (logChannel.m_channelName == "") logChannel.m_channelName = channelName; @@ -585,7 +585,7 @@ namespace mtconnect::configuration { if (m_isDebug || (output && (*output == "cout" || *output == "cerr"))) { - ostream *out; + ostream* out; if (output && *output == "cerr") out = &std::cerr; else @@ -635,13 +635,13 @@ namespace mtconnect::configuration { } } - auto &maxLogArchiveSize = logChannel.m_maxLogArchiveSize; - auto &logRotationSize = logChannel.m_logRotationSize; - auto &rotationLogInterval = logChannel.m_rotationLogInterval; - auto &logArchivePattern = logChannel.m_logArchivePattern; - auto &logDirectory = logChannel.m_logDirectory; - auto &archiveLogDirectory = logChannel.m_archiveLogDirectory; - auto &logFileName = logChannel.m_logFileName; + auto& maxLogArchiveSize = logChannel.m_maxLogArchiveSize; + auto& logRotationSize = logChannel.m_logRotationSize; + auto& rotationLogInterval = logChannel.m_rotationLogInterval; + auto& logArchivePattern = logChannel.m_logArchivePattern; + auto& logDirectory = logChannel.m_logDirectory; + auto& archiveLogDirectory = logChannel.m_archiveLogDirectory; + auto& logFileName = logChannel.m_logFileName; logRotationSize = 2 * 1024 * 1024; // Default to 2MB for log rotation size maxLogArchiveSize = ConvertFileSize(options, "max_archive_size", maxLogArchiveSize); @@ -737,8 +737,8 @@ namespace mtconnect::configuration { logr::core::get()->add_sink(sink); } - static std::string ExpandValue(const std::map &values, - const std::string &s) + static std::string ExpandValue(const std::map& values, + const std::string& s) { static std::regex pat("\\$(([A-Za-z0-9_]+)|\\{([^}]+)\\})"); stringstream out; @@ -785,7 +785,7 @@ namespace mtconnect::configuration { } static void ExpandValues(std::map values, - boost::property_tree::ptree &node) + boost::property_tree::ptree& node) { if (auto value = node.get_value_optional(); value->find('$') != std::string::npos) { @@ -793,22 +793,22 @@ namespace mtconnect::configuration { node.put_value(expanded); } - for (auto &block : node) + for (auto& block : node) { ExpandValues(values, block.second); - const auto &value = block.second.get_value_optional(); + const auto& value = block.second.get_value_optional(); if (value && !value->empty()) values[block.first] = *value; } } - void AgentConfiguration::expandConfigVariables(boost::property_tree::ptree &config) + void AgentConfiguration::expandConfigVariables(boost::property_tree::ptree& config) { std::map values; ExpandValues(values, config); } - void AgentConfiguration::loadConfig(const std::string &text, FileFormat fmt) + void AgentConfiguration::loadConfig(const std::string& text, FileFormat fmt) { NAMED_SCOPE("AgentConfiguration::loadConfig"); @@ -837,12 +837,12 @@ namespace mtconnect::configuration { break; } } - catch (boost::property_tree::json_parser::json_parser_error &e) + catch (boost::property_tree::json_parser::json_parser_error& e) { cerr << "json file error: " << e.what() << " on line " << e.line() << endl; throw; } - catch (const std::exception &e) + catch (const std::exception& e) { cerr << "could not load config file: " << e.what() << endl; throw; @@ -1023,9 +1023,8 @@ namespace mtconnect::configuration { } else { - options[configuration::SchemaVersion] = std::format("{}.{}", std::to_string(AGENT_VERSION_MAJOR), - std::to_string(AGENT_VERSION_MINOR)); - + options[configuration::SchemaVersion] = std::format( + "{}.{}", std::to_string(AGENT_VERSION_MAJOR), std::to_string(AGENT_VERSION_MINOR)); } } loadSinks(config, options); @@ -1053,7 +1052,7 @@ namespace mtconnect::configuration { #endif } - void parseUrl(ConfigOptions &options) + void parseUrl(ConfigOptions& options) { using namespace mtconnect::url; auto url = *GetOption(options, configuration::Url); @@ -1080,7 +1079,7 @@ namespace mtconnect::configuration { } } - void AgentConfiguration::loadAdapters(const pt::ptree &config, const ConfigOptions &options) + void AgentConfiguration::loadAdapters(const pt::ptree& config, const ConfigOptions& options) { using namespace source::adapter; using namespace pipeline; @@ -1091,7 +1090,7 @@ namespace mtconnect::configuration { auto adapters = config.get_child_optional("Adapters"); if (adapters) { - for (const auto &block : *adapters) + for (const auto& block : *adapters) { ConfigOptions adapterOptions = options; @@ -1217,14 +1216,14 @@ namespace mtconnect::configuration { } #ifdef WITH_PYTHON - void AgentConfiguration::configurePython(const ptree &tree, ConfigOptions &options) + void AgentConfiguration::configurePython(const ptree& tree, ConfigOptions& options) { m_python = make_unique(m_agent.get(), options); } #endif #ifdef WITH_RUBY - void AgentConfiguration::configureRuby(const ptree &tree, ConfigOptions &options) + void AgentConfiguration::configureRuby(const ptree& tree, ConfigOptions& options) { ConfigOptions rubyOptions = options; @@ -1242,14 +1241,14 @@ namespace mtconnect::configuration { } #endif - void AgentConfiguration::loadSinks(const ptree &config, ConfigOptions &options) + void AgentConfiguration::loadSinks(const ptree& config, ConfigOptions& options) { NAMED_SCOPE("AgentConfiguration::loadSinks"); auto sinks = config.get_child_optional("Sinks"); if (sinks) { - for (const auto &sinkBlock : *sinks) + for (const auto& sinkBlock : *sinks) { auto qname = entity::QName(sinkBlock.first); auto [factory, name] = qname.getPair(); @@ -1303,17 +1302,17 @@ namespace mtconnect::configuration { } } - void AgentConfiguration::loadPlugins(const ptree &plugins) + void AgentConfiguration::loadPlugins(const ptree& plugins) { NAMED_SCOPE("AgentConfiguration::loadPlugins"); - for (const auto &plugin : plugins) + for (const auto& plugin : plugins) { loadPlugin(plugin.first, plugin.second); } } - bool AgentConfiguration::loadPlugin(const std::string &name, const ptree &plugin) + bool AgentConfiguration::loadPlugin(const std::string& name, const ptree& plugin) { NAMED_SCOPE("AgentConfiguration::loadPlugin"); @@ -1349,7 +1348,7 @@ namespace mtconnect::configuration { init(plugin, *this); return true; } - catch (exception &e) + catch (exception& e) { LOG(debug) << "Plugin " << name << " from " << path << " not found, Reason: " << e.what() << ", trying next path if available."; diff --git a/src/mtconnect/configuration/agent_config.hpp b/src/mtconnect/configuration/agent_config.hpp index 97dc97ba..26cfe901 100644 --- a/src/mtconnect/configuration/agent_config.hpp +++ b/src/mtconnect/configuration/agent_config.hpp @@ -78,7 +78,7 @@ namespace mtconnect { UNKNOWN }; - using InitializationFn = void(const boost::property_tree::ptree &, AgentConfiguration &); + using InitializationFn = void(const boost::property_tree::ptree&, AgentConfiguration&); using InitializationFunction = boost::function; using ptree = boost::property_tree::ptree; @@ -92,16 +92,16 @@ namespace mtconnect { /// @brief Get the callback manager after the agent is created /// @return the callback manager - auto &afterAgentHooks() { return m_afterAgentHooks; } + auto& afterAgentHooks() { return m_afterAgentHooks; } /// @brief Get the callback manager after the config has completed /// @return the callback manager - auto &afterConfigHooks() { return m_afterConfigHooks; } + auto& afterConfigHooks() { return m_afterConfigHooks; } /// @brief Get the callback manager after the agent is started /// @return the callback manager - auto &beforeStartHooks() { return m_beforeStartHooks; } + auto& beforeStartHooks() { return m_beforeStartHooks; } /// @brief Get the callback manager after the agent is stopped /// @return the callback manager - auto &beforeStopHooks() { return m_beforeStopHooks; } + auto& beforeStopHooks() { return m_beforeStopHooks; } ///@} /// @brief stops the agent. Used in daemons. @@ -111,34 +111,34 @@ namespace mtconnect { int start() override; /// @brief initializes the configuration of the agent from the command line parameters /// @param[in] options command line parameters - void initialize(const boost::program_options::variables_map &options) override; + void initialize(const boost::program_options::variables_map& options) override; /// @brief Configure the logger with the config node from the config file /// @param channelName the log channel name /// @param config the configuration node /// @param formatter optional custom message format void configureLoggerChannel( - const std::string &channelName, const ptree &config, + const std::string& channelName, const ptree& config, std::optional> formatter = std::nullopt); /// @brief Configure the agent logger with the config node from the config file /// @param config the configuration node - void configureLogger(const ptree &config); + void configureLogger(const ptree& config); /// @brief load a configuration text /// @param[in] text the configuration text loaded from a file /// @param[in] fmt the file format, can be MTCONNECT, JSON, or XML - void loadConfig(const std::string &text, FileFormat fmt = MTCONNECT); + void loadConfig(const std::string& text, FileFormat fmt = MTCONNECT); /// @brief assign the agent associated with this configuration /// @param[in] agent the agent the configuration will take ownership of - void setAgent(std::unique_ptr &agent) { m_agent = std::move(agent); } + void setAgent(std::unique_ptr& agent) { m_agent = std::move(agent); } /// @brief get the agent associated with the configuration - Agent *getAgent() const { return m_agent.get(); } + Agent* getAgent() const { return m_agent.get(); } /// @brief get the boost asio io context - auto &getContext() { return m_context->get(); } + auto& getContext() { return m_context->get(); } /// @brief get a pointer to the async io manager - auto &getAsyncContext() { return *m_context.get(); } + auto& getAsyncContext() { return *m_context.get(); } /// @brief sets the path for the working directory to the current path void updateWorkingDirectory() { m_working = std::filesystem::current_path(); } @@ -147,10 +147,10 @@ namespace mtconnect { ///@{ /// @brief get the factory for creating sinks /// @return the factory - auto &getSinkFactory() { return m_sinkFactory; } + auto& getSinkFactory() { return m_sinkFactory; } /// @brief get the factory for creating sources /// @return the factory - auto &getSourceFactory() { return m_sourceFactory; } + auto& getSourceFactory() { return m_sourceFactory; } ///@} /// @brief get the pipeline context for this configuration @@ -161,45 +161,45 @@ namespace mtconnect { ///@{ /// @brief gets the boost log sink /// @return boost log sink - const auto &getLoggerSink(const std::string &channelName = "agent") + const auto& getLoggerSink(const std::string& channelName = "agent") { return m_logChannels[channelName].m_logSink; } /// @brief gets the log directory /// @return log directory - const auto &getLogDirectory(const std::string &channelName = "agent") + const auto& getLogDirectory(const std::string& channelName = "agent") { return m_logChannels[channelName].m_logDirectory; } /// @brief get the logging file name /// @return log file name - const auto &getLogFileName(const std::string &channelName = "agent") + const auto& getLogFileName(const std::string& channelName = "agent") { return m_logChannels[channelName].m_logFileName; } /// @brief for log rolling, get the log archive pattern /// @return log archive pattern - const auto &getLogArchivePattern(const std::string &channelName = "agent") + const auto& getLogArchivePattern(const std::string& channelName = "agent") { return m_logChannels[channelName].m_logArchivePattern; } /// @brief gets the archive log directory /// @return log directory - const auto &getArchiveLogDirectory(const std::string &channelName = "agent") + const auto& getArchiveLogDirectory(const std::string& channelName = "agent") { return m_logChannels[channelName].m_archiveLogDirectory; } /// @brief Get the maximum size of all the log files /// @return the maximum size of all log files - auto getLogRotationSize(const std::string &channelName = "agent") + auto getLogRotationSize(const std::string& channelName = "agent") { return m_logChannels[channelName].m_logRotationSize; } /// @brief the maximum size of a log file when it triggers rolling over /// @return the maxumum site of a log file - auto getMaxLogArchiveSize(const std::string &channelName = "agent") + auto getMaxLogArchiveSize(const std::string& channelName = "agent") { return m_logChannels[channelName].m_maxLogArchiveSize; } @@ -211,13 +211,13 @@ namespace mtconnect { /// - `NEVER` /// /// @return the log file interval - auto getRotationLogInterval(const std::string &channelName = "agent") + auto getRotationLogInterval(const std::string& channelName = "agent") { return m_logChannels[channelName].m_rotationLogInterval; } /// @brief Get the current log level /// @return log level - auto getLogLevel(const std::string &channelName = "agent") + auto getLogLevel(const std::string& channelName = "agent") { return m_logChannels[channelName].m_logLevel; } @@ -228,14 +228,14 @@ namespace mtconnect { /// @brief Set the logging level as a string /// @param level the new logging level /// @return the logging level - boost::log::trivial::severity_level setLoggingLevel(const std::string &level); + boost::log::trivial::severity_level setLoggingLevel(const std::string& level); - std::optional findConfigFile(const std::string &file) + std::optional findConfigFile(const std::string& file) { return findFile(m_configPaths, file); } - std::optional findDataFile(const std::string &file) + std::optional findDataFile(const std::string& file) { return findFile(m_dataPaths, file); } @@ -246,11 +246,11 @@ namespace mtconnect { { auto contract = m_agent->makeSinkContract(); contract->m_findConfigFile = - [this](const std::string &n) -> std::optional { + [this](const std::string& n) -> std::optional { return findConfigFile(n); }; contract->m_findDataFile = - [this](const std::string &n) -> std::optional { + [this](const std::string& n) -> std::optional { return findDataFile(n); }; return contract; @@ -258,19 +258,19 @@ namespace mtconnect { /// @brief add a path to the config paths /// @param path the path to add - void addConfigPath(const std::filesystem::path &path) { addPathBack(m_configPaths, path); } + void addConfigPath(const std::filesystem::path& path) { addPathBack(m_configPaths, path); } /// @brief add a path to the data paths /// @param path the path to add - void addDataPath(const std::filesystem::path &path) { addPathBack(m_dataPaths, path); } + void addDataPath(const std::filesystem::path& path) { addPathBack(m_dataPaths, path); } /// @brief add a path to the plugin paths /// @param path the path to add - void addPluginPath(const std::filesystem::path &path) { addPathBack(m_pluginPaths, path); } + void addPluginPath(const std::filesystem::path& path) { addPathBack(m_pluginPaths, path); } ///@brief set the config path for testing ///@param path the path to set for the config file directory - void setConfigPath(const std::filesystem::path &path) { m_configPath = path; } + void setConfigPath(const std::filesystem::path& path) { m_configPath = path; } /// @brief Expand `$VAR` and `${VAR}` references in the config tree. /// @@ -278,31 +278,31 @@ namespace mtconnect { /// failing that, against environment variables. Unresolved references are left /// in place. Called by loadConfig() before any options are parsed. /// @param config the parsed configuration tree to expand in place - void expandConfigVariables(boost::property_tree::ptree &config); + void expandConfigVariables(boost::property_tree::ptree& config); protected: DevicePtr getDefaultDevice(); - void loadAdapters(const ptree &tree, const ConfigOptions &options); - void loadSinks(const ptree &sinks, ConfigOptions &options); + void loadAdapters(const ptree& tree, const ConfigOptions& options); + void loadSinks(const ptree& sinks, ConfigOptions& options); #ifdef WITH_PYTHON - void configurePython(const ptree &tree, ConfigOptions &options); + void configurePython(const ptree& tree, ConfigOptions& options); #endif #ifdef WITH_RUBY - void configureRuby(const ptree &tree, ConfigOptions &options); + void configureRuby(const ptree& tree, ConfigOptions& options); #endif - void loadPlugins(const ptree &tree); - bool loadPlugin(const std::string &name, const ptree &tree); + void loadPlugins(const ptree& tree); + bool loadPlugin(const std::string& name, const ptree& tree); void monitorFiles(boost::system::error_code ec); void monitorResources(boost::system::error_code ec); void scheduleMonitorTimer(); protected: - std::optional findFile(const std::list &paths, + std::optional findFile(const std::list& paths, const std::string file) { - for (const auto &path : paths) + for (const auto& path : paths) { auto tst = path / file; std::error_code ec; @@ -323,7 +323,7 @@ namespace mtconnect { return std::nullopt; } - void addPathBack(std::list &paths, std::filesystem::path path) + void addPathBack(std::list& paths, std::filesystem::path path) { std::error_code ec; auto con {std::filesystem::canonical(path, ec)}; @@ -336,7 +336,7 @@ namespace mtconnect { LOG(debug) << "Cannot find path: " << path << ", " << ec.message() << ", skipping..."; } - void addPathFront(std::list &paths, std::filesystem::path path) + void addPathFront(std::list& paths, std::filesystem::path path) { std::error_code ec; auto con {std::filesystem::canonical(path, ec)}; @@ -348,9 +348,9 @@ namespace mtconnect { } template - void logPaths(T lvl, const std::list &paths) + void logPaths(T lvl, const std::list& paths) { - for (const auto &p : paths) + for (const auto& p : paths) { BOOST_LOG_STREAM_WITH_PARAMS(::boost::log::trivial::logger::get(), (::boost::log::keywords::severity = lvl)) @@ -407,7 +407,7 @@ namespace mtconnect { std::chrono::seconds m_monitorInterval; std::chrono::seconds m_monitorDelay; bool m_restart = false; - bool m_monitorResources { false }; + bool m_monitorResources {false}; std::optional m_configTime; std::optional m_deviceTime; @@ -418,7 +418,7 @@ namespace mtconnect { int m_workerThreadCount {1}; // Reference to the global logger - boost::log::trivial::logger_type *m_logger {nullptr}; + boost::log::trivial::logger_type* m_logger {nullptr}; #ifdef WITH_RUBY std::unique_ptr m_ruby; @@ -430,7 +430,6 @@ namespace mtconnect { TrendMonitor m_fdMonitor {makeFdMonitor()}; TrendMonitor m_memoryMonitor {makeMemoryMonitor()}; - HookManager m_afterAgentHooks; HookManager m_afterConfigHooks; HookManager m_beforeStartHooks; diff --git a/src/mtconnect/configuration/async_context.hpp b/src/mtconnect/configuration/async_context.hpp index 71db55e3..986e9281 100644 --- a/src/mtconnect/configuration/async_context.hpp +++ b/src/mtconnect/configuration/async_context.hpp @@ -31,14 +31,14 @@ namespace mtconnect::configuration { class AGENT_LIB_API AsyncContext { public: - using SyncCallback = std::function; + using SyncCallback = std::function; using WorkGuard = boost::asio::executor_work_guard; /// @brief creates an asio context and a guard to prevent it from /// stopping AsyncContext() { m_guard.emplace(m_context.get_executor()); } /// @brief removes the copy constructor - AsyncContext(const AsyncContext &) = delete; + AsyncContext(const AsyncContext&) = delete; ~AsyncContext() {} /// @brief is the context running @@ -53,11 +53,11 @@ namespace mtconnect::configuration { void removeGuard() { m_guard.reset(); } /// @brief get the boost asio context reference - auto &get() { return m_context; } + auto& get() { return m_context; } /// @brief operator() returns a reference to the io context /// @return the io context - operator boost::asio::io_context &() { return m_context; } + operator boost::asio::io_context&() { return m_context; } /// @brief sets the number of theads for asio thread pool /// @param[in] threads number of threads @@ -82,13 +82,13 @@ namespace mtconnect::configuration { m_context.run(); } - catch (FatalException &e) + catch (FatalException& e) { LOG(fatal) << "Fatal exception occurred: " << e.what(); stop(false); m_exitCode = 1; } - catch (std::exception &e) + catch (std::exception& e) { LOG(fatal) << "Uncaught exception occurred: " << e.what(); stop(false); @@ -102,7 +102,7 @@ namespace mtconnect::configuration { } })); } - auto &first = m_workers.front(); + auto& first = m_workers.front(); while (m_running && !m_paused) { if (!first.try_join_for(boost::chrono::seconds(5)) && !m_running) @@ -112,7 +112,7 @@ namespace mtconnect::configuration { } } - for (auto &w : m_workers) + for (auto& w : m_workers) { w.join(); } @@ -134,13 +134,13 @@ namespace mtconnect::configuration { } while (m_running); } - catch (FatalException &e) + catch (FatalException& e) { LOG(fatal) << "Fatal exception occurred: " << e.what(); stop(false); m_exitCode = 1; } - catch (std::exception &e) + catch (std::exception& e) { LOG(fatal) << "Uncaught exception occurred: " << e.what(); stop(false); @@ -195,7 +195,7 @@ namespace mtconnect::configuration { /// @brief io_context::run_for template - auto run_for(const std::chrono::duration &rel_time) + auto run_for(const std::chrono::duration& rel_time) { return m_context.run_for(rel_time); } @@ -208,14 +208,14 @@ namespace mtconnect::configuration { /// @brief io_context::run_one_for template - auto run_one_for(const std::chrono::duration &rel_time) + auto run_one_for(const std::chrono::duration& rel_time) { return m_context.run_one_for(rel_time); } /// @brief io_context::run_one_until template - auto run_one_until(const std::chrono::time_point &abs_time) + auto run_one_until(const std::chrono::time_point& abs_time) { return m_context.run_one_for(abs_time); } @@ -229,7 +229,7 @@ namespace mtconnect::configuration { /// @} private: - void operator=(const AsyncContext &) {} + void operator=(const AsyncContext&) {} protected: boost::asio::io_context m_context; diff --git a/src/mtconnect/configuration/config_options.hpp b/src/mtconnect/configuration/config_options.hpp index 4f739ccd..e52f9ee6 100644 --- a/src/mtconnect/configuration/config_options.hpp +++ b/src/mtconnect/configuration/config_options.hpp @@ -30,7 +30,7 @@ namespace mtconnect { /// stringizes `name` /// /// @param name name of configuration parameter -#define DECLARE_CONFIGURATION(name) inline const char *name = #name; +#define DECLARE_CONFIGURATION(name) inline const char* name = #name; /// @name Global Configuration Options ///@{ diff --git a/src/mtconnect/configuration/hook_manager.hpp b/src/mtconnect/configuration/hook_manager.hpp index deb9a4e0..18249c4a 100644 --- a/src/mtconnect/configuration/hook_manager.hpp +++ b/src/mtconnect/configuration/hook_manager.hpp @@ -31,7 +31,7 @@ namespace mtconnect::configuration { class HookManager { public: - using Hook = std::function; + using Hook = std::function; using HookEntry = std::pair, Hook>; using HookList = std::list; @@ -41,16 +41,16 @@ namespace mtconnect::configuration { /// @brief Add a hook to the end of the list as a rvalue without a name /// @param[in] hook The callback - void add(Hook &hook) { m_hooks.emplace_back(std::make_pair(std::nullopt, hook)); } + void add(Hook& hook) { m_hooks.emplace_back(std::make_pair(std::nullopt, hook)); } /// @brief Add a hook to the end of the list as a lvalue without a name /// @param[in] hook The callback - void add(Hook &&hook) { m_hooks.emplace_back(std::make_pair(std::nullopt, std::move(hook))); } + void add(Hook&& hook) { m_hooks.emplace_back(std::make_pair(std::nullopt, std::move(hook))); } /// @brief Add a hook to the beginning of the list as a rvalue without a name /// @param[in] hook The callback - void addFirst(Hook &hook) { m_hooks.emplace_front(std::make_pair(std::nullopt, hook)); } + void addFirst(Hook& hook) { m_hooks.emplace_front(std::make_pair(std::nullopt, hook)); } /// @brief Add a hook to the beginning of the list as a lvalue without a name /// @param[in] hook The callback - void addFirst(Hook &&hook) + void addFirst(Hook&& hook) { m_hooks.emplace_front(std::make_pair(std::nullopt, std::move(hook))); } @@ -58,44 +58,44 @@ namespace mtconnect::configuration { /// @brief Add a hook to the end of the list as a rvalue /// @param[in] name The name of the callback /// @param[in] hook The callback - void add(std::string &name, Hook &hook) + void add(std::string& name, Hook& hook) { m_hooks.emplace_back(std::make_pair(std::nullopt, hook)); } /// @brief Add a hook to the end of the list as a rvalue /// @param[in] name The name of the callback /// @param[in] hook The callback - void add(std::string &name, Hook &&hook) + void add(std::string& name, Hook&& hook) { m_hooks.emplace_back(std::make_pair(std::nullopt, std::move(hook))); } /// @brief Add a hook to the beginning of the list as a rvalue /// @param[in] name The name of the callback /// @param[in] hook The callback - void addFirst(std::string &name, Hook &hook) + void addFirst(std::string& name, Hook& hook) { m_hooks.emplace_front(std::make_pair(std::nullopt, hook)); } /// @brief Add a hook to the beginning of the list as a lvalue /// @param[in] name The name of the callback /// @param[in] hook The callback - void addFirst(std::string &name, Hook &&hook) + void addFirst(std::string& name, Hook&& hook) { m_hooks.emplace_front(std::make_pair(std::nullopt, std::move(hook))); } /// @brief remove a named callback from the list - bool remove(const std::string &name) + bool remove(const std::string& name) { - auto v = m_hooks.remove_if([&name](const auto &v) { return v.first && *v.first == name; }); + auto v = m_hooks.remove_if([&name](const auto& v) { return v.first && *v.first == name; }); return v > 0; } /// @brief call each of the hooks in order with an object /// @param obj the object to pass to each callback - void exec(T &obj) const + void exec(T& obj) const { - for (const auto &h : m_hooks) + for (const auto& h : m_hooks) h.second(obj); } diff --git a/src/mtconnect/configuration/parser.cpp b/src/mtconnect/configuration/parser.cpp index bcf03f97..38f6d732 100644 --- a/src/mtconnect/configuration/parser.cpp +++ b/src/mtconnect/configuration/parser.cpp @@ -27,21 +27,21 @@ // #define BOOST_SPIRIT_DEBUG 1 #ifdef BOOST_SPIRIT_DEBUG namespace std { - static ostream &operator<<(ostream &s, const boost::property_tree::ptree &t); - static inline ostream &operator<<(ostream &s, - const pair &t) + static ostream& operator<<(ostream& s, const boost::property_tree::ptree& t); + static inline ostream& operator<<(ostream& s, + const pair& t) { s << "'" << t.first << "'" << t.second; return s; } - static inline ostream &operator<<(ostream &s, const pair &t) + static inline ostream& operator<<(ostream& s, const pair& t) { s << "Pair: '" << t.first << "', '" << t.second << "'"; return s; } - static ostream &operator<<(ostream &s, const boost::property_tree::ptree &t) + static ostream& operator<<(ostream& s, const boost::property_tree::ptree& t) { if (!t.data().empty()) { @@ -50,7 +50,7 @@ namespace std { if (!t.empty()) { s << " [Tree: "; - for (const auto &c : t) + for (const auto& c : t) s << c << ", "; s << "]"; } @@ -79,26 +79,26 @@ namespace mtconnect { namespace configuration { /// @brief Actions for the configuration parser in reductions namespace ConfigurationParserActions { - inline static void property(pair &t, const std::string &f, - const std::string &s) + inline static void property(pair& t, const std::string& f, + const std::string& s) { t = make_pair(f, trim(s)); } - inline static void tree(pair &t, const std::string &f, - const vector> &s) + inline static void tree(pair& t, const std::string& f, + const vector>& s) { t.first = f; - for (const auto &a : s) + for (const auto& a : s) { if (!a.first.empty()) t.second.push_back(a); } } - inline static void start(pt::ptree &t, const vector> &s) + inline static void start(pt::ptree& t, const vector>& s) { - for (const auto &a : s) + for (const auto& a : s) { if (!a.first.empty()) t.push_back(a); @@ -173,8 +173,8 @@ namespace mtconnect { qi::rule m_start; }; - static std::string ExpandValue(const std::map &values, - const std::string &s) + static std::string ExpandValue(const std::map& values, + const std::string& s) { static std::regex pat("\\$(([A-Za-z0-9_]+)|\\{([^}]+)\\})"); stringstream out; @@ -221,7 +221,7 @@ namespace mtconnect { } static void ExpandValues(std::map values, - boost::property_tree::ptree &node) + boost::property_tree::ptree& node) { if (auto value = node.get_value_optional(); value->find('$') != std::string::npos) @@ -230,22 +230,22 @@ namespace mtconnect { node.put_value(expanded); } - for (auto &block : node) + for (auto& block : node) { ExpandValues(values, block.second); - const auto &value = block.second.get_value_optional(); + const auto& value = block.second.get_value_optional(); if (value && !value->empty()) values[block.first] = *value; } } - static void ExpandVariables(boost::property_tree::ptree &config) + static void ExpandVariables(boost::property_tree::ptree& config) { std::map values; ExpandValues(values, config); } - pt::ptree Parser::parse(const std::string &text) + pt::ptree Parser::parse(const std::string& text) { pt::ptree tree; using boost::spirit::ascii::space; @@ -282,7 +282,7 @@ namespace mtconnect { return tree; } - pt::ptree Parser::parse(const std::filesystem::path &path) + pt::ptree Parser::parse(const std::filesystem::path& path) { std::ifstream t(path); std::stringstream buffer; diff --git a/src/mtconnect/configuration/parser.hpp b/src/mtconnect/configuration/parser.hpp index 0459ffdf..f0c6ba81 100644 --- a/src/mtconnect/configuration/parser.hpp +++ b/src/mtconnect/configuration/parser.hpp @@ -39,10 +39,10 @@ namespace mtconnect { { /// @brief Parse text string to a property tree (testing) /// @param[in] text text to be parsed - static boost::property_tree::ptree parse(const std::string &text); + static boost::property_tree::ptree parse(const std::string& text); /// @brief Parse file to a property tree /// @param[in] path file to be parsed - static boost::property_tree::ptree parse(const std::filesystem::path &path); + static boost::property_tree::ptree parse(const std::filesystem::path& path); }; } // namespace configuration } // namespace mtconnect diff --git a/src/mtconnect/configuration/service.cpp b/src/mtconnect/configuration/service.cpp index 4c318bcb..b8390158 100644 --- a/src/mtconnect/configuration/service.cpp +++ b/src/mtconnect/configuration/service.cpp @@ -73,8 +73,8 @@ namespace mtconnect { } boost::program_options::variables_map MTConnectService::parseOptions( - int argc, const char *argv[], boost::optional &command, - boost::optional &config) + int argc, const char* argv[], boost::optional& command, + boost::optional& config) { namespace po = boost::program_options; using namespace std; @@ -146,13 +146,13 @@ namespace mtconnect { HANDLE g_hSvcStopEvent = nullptr; VOID WINAPI SvcCtrlHandler(DWORD); - VOID WINAPI SvcMain(DWORD, LPTSTR *); + VOID WINAPI SvcMain(DWORD, LPTSTR*); VOID ReportSvcStatus(DWORD, DWORD, DWORD); - VOID SvcInit(DWORD, LPTSTR *); + VOID SvcInit(DWORD, LPTSTR*); VOID SvcReportEvent(LPSTR); - static MTConnectService *g_service = nullptr; + static MTConnectService* g_service = nullptr; static void agent_termination_handler() {} @@ -170,7 +170,7 @@ namespace mtconnect { } } - int MTConnectService::main(int argc, const char *argv[]) + int MTConnectService::main(int argc, const char* argv[]) { std::set_terminate(agent_termination_handler); PrintMTConnectAgentVersion(); @@ -235,13 +235,13 @@ namespace mtconnect { SvcReportEvent(LPSTR("StartServiceCtrlDispatcher")); } } - catch (std::exception &e) + catch (std::exception& e) { LOG(fatal) << "Agent top level exception: " << e.what(); std::cerr << "Agent top level exception: " << e.what() << std::endl; res = 1; } - catch (std::string &s) + catch (std::string& s) { LOG(fatal) << "Agent top level exception: " << s; std::cerr << "Agent top level exception: " << s << std::endl; @@ -367,7 +367,7 @@ namespace mtconnect { description.append(m_configFile.string()); } SERVICE_DESCRIPTIONA serviceDescription = {0}; - serviceDescription.lpDescription = const_cast(description.c_str()); + serviceDescription.lpDescription = const_cast(description.c_str()); ChangeServiceConfig2A(service, SERVICE_CONFIG_DESCRIPTION, &serviceDescription); CloseServiceHandle(service); @@ -417,7 +417,7 @@ namespace mtconnect { RegCloseKey(mtc); auto cfgFile = m_configFile.string(); - RegSetValueExA(agent, "ConfigurationFile", 0ul, REG_SZ, (const BYTE *)cfgFile.c_str(), + RegSetValueExA(agent, "ConfigurationFile", 0ul, REG_SZ, (const BYTE*)cfgFile.c_str(), cfgFile.length() + 1); RegCloseKey(agent); @@ -497,7 +497,7 @@ namespace mtconnect { // Return value: // None. // - VOID WINAPI SvcMain(DWORD dwArgc, LPSTR *lpszArgv) + VOID WINAPI SvcMain(DWORD dwArgc, LPSTR* lpszArgv) { // Register the handler function for the service g_service->setName(lpszArgv[0]); @@ -549,7 +549,7 @@ namespace mtconnect { // Return value: // None // - VOID SvcInit(DWORD dwArgc, LPTSTR *lpszArgv) + VOID SvcInit(DWORD dwArgc, LPTSTR* lpszArgv) { // Get the real arguments from the registry char key[1024] = {0}; @@ -566,7 +566,7 @@ namespace mtconnect { BYTE configFile[2048] = {}; DWORD len = sizeof(configFile) - 1ul, type(0ul); - res = RegQueryValueExA(agent, "ConfigurationFile", 0ul, &type, (BYTE *)configFile, &len); + res = RegQueryValueExA(agent, "ConfigurationFile", 0ul, &type, (BYTE*)configFile, &len); RegCloseKey(agent); agent = nullptr; if (res != ERROR_SUCCESS) @@ -579,7 +579,7 @@ namespace mtconnect { boost::optional command; boost::optional config; - const char *argp[3] = {"agent", "run", (const char *)configFile}; + const char* argp[3] = {"agent", "run", (const char*)configFile}; auto options = g_service->parseOptions(3, argp, command, config); g_service->initialize(options); @@ -806,7 +806,7 @@ namespace mtconnect { signal(SIGTERM, signal_handler); // catch kill signal } - int MTConnectService::main(int argc, const char *argv[]) + int MTConnectService::main(int argc, const char* argv[]) { PrintMTConnectAgentVersion(); diff --git a/src/mtconnect/configuration/service.hpp b/src/mtconnect/configuration/service.hpp index 117e72f6..8f1faa02 100644 --- a/src/mtconnect/configuration/service.hpp +++ b/src/mtconnect/configuration/service.hpp @@ -38,9 +38,9 @@ namespace mtconnect { /// @brief command line parser and entry point for agent /// @param[in] argc the count of arguments /// @param[in] argv the arguments - virtual int main(int argc, char const *argv[]); + virtual int main(int argc, char const* argv[]); /// @brief initialize the service with the parser command line options - virtual void initialize(const boost::program_options::variables_map &options) = 0; + virtual void initialize(const boost::program_options::variables_map& options) = 0; /// @brief stop the srvice virtual void stop() = 0; /// @brief start the service @@ -48,10 +48,10 @@ namespace mtconnect { /// @brief set the name of the service /// @param[in] name name of the service - void setName(std::string const &name) { m_name = name; } + void setName(std::string const& name) { m_name = name; } /// @brief get the name of the service /// @return service name - std::string const &name() const { return m_name; } + std::string const& name() const { return m_name; } /// @brief set the debugging state /// @param debug `true` if debugging void setDebug(bool debug) { m_isDebug = debug; } @@ -69,9 +69,9 @@ namespace mtconnect { /// @param command optonal command for testing /// @param config optional configration file for testing /// @return boost variable map - boost::program_options::variables_map parseOptions(int argc, const char *argv[], - boost::optional &command, - boost::optional &config); + boost::program_options::variables_map parseOptions(int argc, const char* argv[], + boost::optional& command, + boost::optional& config); protected: std::string m_name; diff --git a/src/mtconnect/device_model/agent_device.cpp b/src/mtconnect/device_model/agent_device.cpp index e242d47b..a5719fc3 100644 --- a/src/mtconnect/device_model/agent_device.cpp +++ b/src/mtconnect/device_model/agent_device.cpp @@ -36,7 +36,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Device::getFactory()); - factory->setFunction([](const std::string &name, Properties &ps) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& ps) -> EntityPtr { auto dev = make_shared("Agent"s, ps); dev->initialize(); return dev; @@ -54,7 +54,7 @@ namespace mtconnect { return factory; } - AgentDevice::AgentDevice(const std::string &name, entity::Properties &props) + AgentDevice::AgentDevice(const std::string& name, entity::Properties& props) : Device(name, props) { NAMED_SCOPE("agent_device"); @@ -62,7 +62,7 @@ namespace mtconnect { m_adapters = Component::make("Adapters", {{"id", "__adapters__"s}}, errors); if (!errors.empty()) { - for (auto &e : errors) + for (auto& e : errors) { LOG(fatal) << "Cannot create AgentDevice: " << e->what(); } diff --git a/src/mtconnect/device_model/agent_device.hpp b/src/mtconnect/device_model/agent_device.hpp index c27ccc9f..f4f316c2 100644 --- a/src/mtconnect/device_model/agent_device.hpp +++ b/src/mtconnect/device_model/agent_device.hpp @@ -39,7 +39,7 @@ namespace mtconnect { /// @brief Constructor that sets variables from an attribute map /// /// Should not be used directly, always create using the factory - AgentDevice(const std::string &name, entity::Properties &props); + AgentDevice(const std::string& name, entity::Properties& props); ~AgentDevice() override = default; static entity::FactoryPtr getFactory(); static entity::FactoryPtr getRoot(); @@ -60,13 +60,13 @@ namespace mtconnect { /// @brief get the connection status data item for an addapter /// @param adapter the adapter name /// @return shared pointer to the data item - DataItemPtr getConnectionStatus(const std::string &adapter) + DataItemPtr getConnectionStatus(const std::string& adapter) { return getDeviceDataItem(adapter + "_connection_status"); } /// @brief Get all the adapter components /// @return shared pointer to the adapters component - auto &getAdapters() { return m_adapters; } + auto& getAdapters() { return m_adapters; } protected: void addRequiredDataItems(); diff --git a/src/mtconnect/device_model/component.cpp b/src/mtconnect/device_model/component.cpp index c53fc19d..16d5cfee 100644 --- a/src/mtconnect/device_model/component.cpp +++ b/src/mtconnect/device_model/component.cpp @@ -36,7 +36,7 @@ namespace mtconnect { using namespace data_item; // Component public methods - Component::Component(const std::string &name, const entity::Properties &props) + Component::Component(const std::string& name, const entity::Properties& props) : Entity(name, props) { m_id = get("id"); @@ -49,7 +49,7 @@ namespace mtconnect { auto items = getList("DataItems"); if (items) { - for (auto &item : *items) + for (auto& item : *items) dynamic_pointer_cast(item)->setComponent(getptr()); } } @@ -59,7 +59,7 @@ namespace mtconnect { auto comps = getList("Compositions"); if (comps) { - for (auto &comp : *comps) + for (auto& comp : *comps) dynamic_pointer_cast(comp)->setComponent(getptr()); } } @@ -70,7 +70,7 @@ namespace mtconnect { auto items = getList("DataItems"); if (items) { - for (auto &item : *items) + for (auto& item : *items) { auto di = dynamic_pointer_cast(item); device->registerDataItem(di); @@ -81,7 +81,7 @@ namespace mtconnect { auto children = getChildren(); if (children) { - for (auto &child : *children) + for (auto& child : *children) { auto cp = dynamic_pointer_cast(child); cp->setParent(getptr()); @@ -114,7 +114,7 @@ namespace mtconnect { {"Compositions", ValueType::ENTITY_LIST, compositions, false}, {"References", ValueType::ENTITY_LIST, references, false}, {"Configuration", ValueType::ENTITY, configuration, false}}, - [](const std::string &name, Properties &props) -> EntityPtr { + [](const std::string& name, Properties& props) -> EntityPtr { auto ptr = make_shared(name, props); ptr->initialize(); return dynamic_pointer_cast(ptr); @@ -138,7 +138,7 @@ namespace mtconnect { auto references = getList("References"); if (references) { - for (auto &reference : *references) + for (auto& reference : *references) { dynamic_pointer_cast(reference)->resolve(device); } @@ -146,12 +146,12 @@ namespace mtconnect { auto children = getChildren(); if (children) { - for (const auto &child : *children) + for (const auto& child : *children) dynamic_pointer_cast(child)->resolveReferences(device); } } - void Component::addDataItem(DataItemPtr dataItem, entity::ErrorList &errors) + void Component::addDataItem(DataItemPtr dataItem, entity::ErrorList& errors) { if (addToList("DataItems", Component::getFactory(), dataItem, errors)) { diff --git a/src/mtconnect/device_model/component.hpp b/src/mtconnect/device_model/component.hpp index a396966d..069bdc3f 100644 --- a/src/mtconnect/device_model/component.hpp +++ b/src/mtconnect/device_model/component.hpp @@ -52,9 +52,9 @@ namespace mtconnect { /// @brief Create a component with a type and properties /// @param[in] name the name of the component (o type) /// @param[in] props properties of the component - Component(const std::string &name, const entity::Properties &props); - static ComponentPtr make(const std::string &name, const entity::Properties &props, - entity::ErrorList &errors) + Component(const std::string& name, const entity::Properties& props); + static ComponentPtr make(const std::string& name, const entity::Properties& props, + entity::ErrorList& errors) { entity::Properties ps(props); auto ptr = getFactory()->make(name, ps, errors); @@ -78,13 +78,13 @@ namespace mtconnect { /// @brief get the component id /// @return component id - const auto &getId() const { return m_id; } + const auto& getId() const { return m_id; } /// @brief get the name property of the component /// @return name if it exists - const auto &getComponentName() const { return m_componentName; } + const auto& getComponentName() const { return m_componentName; } /// @brief get the component uuid /// @return uuid if it exists - const auto &getUuid() const { return m_uuid; } + const auto& getUuid() const { return m_uuid; } /// @brief Get the topic name for the component /// @return topic name @@ -92,7 +92,7 @@ namespace mtconnect { { if (!m_topicName) { - auto *self = const_cast(this); + auto* self = const_cast(this); self->m_topicName.emplace(getName()); if (m_componentName) { @@ -120,7 +120,7 @@ namespace mtconnect { /// @brief set the manufacturer in the description /// @param value the manufacturer - void setManufacturer(const std::string &value) + void setManufacturer(const std::string& value) { auto desc = getDescription(); desc->setProperty("manufacturer", value); @@ -128,7 +128,7 @@ namespace mtconnect { /// @brief set the station in the description /// @param value the description - void setStation(const std::string &value) + void setStation(const std::string& value) { auto desc = getDescription(); desc->setProperty("station", value); @@ -136,7 +136,7 @@ namespace mtconnect { /// @brief set the serial number in the description /// @param value the serial number - void setSerialNumber(const std::string &value) + void setSerialNumber(const std::string& value) { auto desc = getDescription(); desc->setProperty("serialNumber", value); @@ -144,7 +144,7 @@ namespace mtconnect { /// @brief set the description value in the description /// @param value the description value - void setDescriptionValue(const std::string &value) + void setDescriptionValue(const std::string& value) { auto desc = getDescription(); desc->setValue(value); @@ -152,21 +152,21 @@ namespace mtconnect { /// @brief set the uuid /// @param uuid the uuid - void setUuid(const std::string &uuid) + void setUuid(const std::string& uuid) { m_uuid = uuid; setProperty("uuid", uuid); } /// @brief set the compoent name property, not the compoent type /// @param name name property - void setComponentName(const std::string &name) + void setComponentName(const std::string& name) { m_componentName = name; setProperty("name", name); } /// @brief set the compoent name property, not the compoent type /// @param name name property - void setComponentName(const std::optional &name) + void setComponentName(const std::optional& name) { m_componentName = name; if (name) @@ -185,7 +185,7 @@ namespace mtconnect { auto parent = m_parent.lock(); if (parent) { - const_cast(this)->m_device = parent->getDevice(); + const_cast(this)->m_device = parent->getDevice(); device = m_device.lock(); } } @@ -202,7 +202,7 @@ namespace mtconnect { /// @brief add a child to this component /// @param[in] child the child component /// @param[in,out] errors errors that occurred when adding the child - void addChild(ComponentPtr child, entity::ErrorList &errors) + void addChild(ComponentPtr child, entity::ErrorList& errors) { addToList("Components", Component::getFactory(), child, errors); child->setParent(getptr()); @@ -214,7 +214,7 @@ namespace mtconnect { /// @brief add a data item to the component /// @param[in] dataItem the data item /// @param[in,out] errors errors that occurred when adding the data item - virtual void addDataItem(DataItemPtr dataItem, entity::ErrorList &errors); + virtual void addDataItem(DataItemPtr dataItem, entity::ErrorList& errors); /// @brief get the list of data items /// @return the data item list auto getDataItems() const { return getList("DataItems"); } @@ -222,12 +222,12 @@ namespace mtconnect { /// @brief compares the ids of the component for sorting /// @param comp other component to compare against /// @return `true` if this id is less than the comp id - bool operator<(const Component &comp) const { return m_id < comp.getId(); } + bool operator<(const Component& comp) const { return m_id < comp.getId(); } /// @brief compares the ids for equality /// @param comp other component to compare against /// @return `true` if this id is equal than the comp id - bool operator==(const Component &comp) const { return m_id == comp.getId(); } + bool operator==(const Component& comp) const { return m_id == comp.getId(); } /// @brief connected references by looking them up in the device /// @param device the device to use as an index @@ -247,12 +247,12 @@ namespace mtconnect { /// @brief get the composition by its id /// @param id the composition id /// @return shared pointer to the composition - CompositionPtr getComposition(const std::string &id) const + CompositionPtr getComposition(const std::string& id) const { auto comps = getList("Compositions"); if (comps) { - for (auto &comp : *comps) + for (auto& comp : *comps) { const auto cid = comp->get("id"); if (cid == id) @@ -267,7 +267,7 @@ namespace mtconnect { /// /// Recurses to root and then appends getTopicName /// @param[in,out] pth the path list to append to - void path(std::list &pth) + void path(std::list& pth) { auto p = getParent(); if (p) @@ -276,8 +276,8 @@ namespace mtconnect { pth.push_back(getTopicName()); } - std::optional createUniqueId(std::unordered_map &idMap, - const boost::uuids::detail::sha1 &sha1) override + std::optional createUniqueId(std::unordered_map& idMap, + const boost::uuids::detail::sha1& sha1) override { auto newId = Entity::createUniqueId(idMap, sha1); m_id = *newId; @@ -303,7 +303,7 @@ namespace mtconnect { /// @brief Comparison lambda to sort components struct ComponentComp { - bool operator()(const Component *lhs, const Component *rhs) const { return *lhs < *rhs; } + bool operator()(const Component* lhs, const Component* rhs) const { return *lhs < *rhs; } }; } // namespace device_model } // namespace mtconnect diff --git a/src/mtconnect/device_model/composition.cpp b/src/mtconnect/device_model/composition.cpp index da284d8b..102aed25 100644 --- a/src/mtconnect/device_model/composition.cpp +++ b/src/mtconnect/device_model/composition.cpp @@ -41,7 +41,7 @@ namespace mtconnect { Requirement("type", true), Requirement("Description", ValueType::ENTITY, Description::getFactory(), false), Requirement("Configuration", ValueType::ENTITY, config, false)}, - [](const std::string &name, Properties &props) -> EntityPtr { + [](const std::string& name, Properties& props) -> EntityPtr { auto ptr = make_shared(name, props); return dynamic_pointer_cast(ptr); }); diff --git a/src/mtconnect/device_model/composition.hpp b/src/mtconnect/device_model/composition.hpp index 0542a3bf..dfa86c06 100644 --- a/src/mtconnect/device_model/composition.hpp +++ b/src/mtconnect/device_model/composition.hpp @@ -46,7 +46,7 @@ namespace mtconnect { if (name) topicName.append("[").append(*name).append("]"); - auto *self = const_cast(this); + auto* self = const_cast(this); self->m_topicName.emplace(topicName); } return *m_topicName; diff --git a/src/mtconnect/device_model/configuration/configuration.cpp b/src/mtconnect/device_model/configuration/configuration.cpp index 308b8b7e..8bc58d32 100644 --- a/src/mtconnect/device_model/configuration/configuration.cpp +++ b/src/mtconnect/device_model/configuration/configuration.cpp @@ -54,5 +54,5 @@ namespace mtconnect { return root; } } // namespace configuration - } // namespace device_model + } // namespace device_model } // namespace mtconnect diff --git a/src/mtconnect/device_model/configuration/coordinate_systems.cpp b/src/mtconnect/device_model/configuration/coordinate_systems.cpp index b1e3349a..c20b5e44 100644 --- a/src/mtconnect/device_model/configuration/coordinate_systems.cpp +++ b/src/mtconnect/device_model/configuration/coordinate_systems.cpp @@ -56,5 +56,5 @@ namespace mtconnect { return coordinateSystems; } } // namespace configuration - } // namespace device_model + } // namespace device_model } // namespace mtconnect diff --git a/src/mtconnect/device_model/configuration/motion.cpp b/src/mtconnect/device_model/configuration/motion.cpp index ef316fec..0de75ea8 100644 --- a/src/mtconnect/device_model/configuration/motion.cpp +++ b/src/mtconnect/device_model/configuration/motion.cpp @@ -50,5 +50,5 @@ namespace mtconnect { return motion; } } // namespace configuration - } // namespace device_model + } // namespace device_model } // namespace mtconnect diff --git a/src/mtconnect/device_model/configuration/relationships.cpp b/src/mtconnect/device_model/configuration/relationships.cpp index 0d1612c5..8fdb3608 100644 --- a/src/mtconnect/device_model/configuration/relationships.cpp +++ b/src/mtconnect/device_model/configuration/relationships.cpp @@ -65,5 +65,5 @@ namespace mtconnect { return relationships; } } // namespace configuration - } // namespace device_model + } // namespace device_model } // namespace mtconnect diff --git a/src/mtconnect/device_model/configuration/sensor_configuration.cpp b/src/mtconnect/device_model/configuration/sensor_configuration.cpp index dda0f0d9..ba946a9a 100644 --- a/src/mtconnect/device_model/configuration/sensor_configuration.cpp +++ b/src/mtconnect/device_model/configuration/sensor_configuration.cpp @@ -49,5 +49,5 @@ namespace mtconnect { return sensorConfiguration; } } // namespace configuration - } // namespace device_model + } // namespace device_model } // namespace mtconnect diff --git a/src/mtconnect/device_model/configuration/solid_model.cpp b/src/mtconnect/device_model/configuration/solid_model.cpp index f613a89a..a712dc87 100644 --- a/src/mtconnect/device_model/configuration/solid_model.cpp +++ b/src/mtconnect/device_model/configuration/solid_model.cpp @@ -57,5 +57,5 @@ namespace mtconnect { return solidModel; } } // namespace configuration - } // namespace device_model + } // namespace device_model } // namespace mtconnect diff --git a/src/mtconnect/device_model/configuration/specifications.cpp b/src/mtconnect/device_model/configuration/specifications.cpp index b77acfd8..2e674b57 100644 --- a/src/mtconnect/device_model/configuration/specifications.cpp +++ b/src/mtconnect/device_model/configuration/specifications.cpp @@ -89,5 +89,5 @@ namespace mtconnect { return specifications; } } // namespace configuration - } // namespace device_model + } // namespace device_model } // namespace mtconnect diff --git a/src/mtconnect/device_model/data_item/data_item.cpp b/src/mtconnect/device_model/data_item/data_item.cpp index 32be30fd..fe23dbb8 100644 --- a/src/mtconnect/device_model/data_item/data_item.cpp +++ b/src/mtconnect/device_model/data_item/data_item.cpp @@ -72,7 +72,7 @@ namespace mtconnect { {"Relationships", ValueType::ENTITY_LIST, relationships, false}, {"InitialValue", ValueType::STRING, false}, {"ResetTrigger", false}}); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { auto ptr = make_shared(name, props); return dynamic_pointer_cast(ptr); }); @@ -99,13 +99,13 @@ namespace mtconnect { } // DataItem public methods - DataItem::DataItem(const string &name, const Properties &props) : Entity(name, props) + DataItem::DataItem(const string& name, const Properties& props) : Entity(name, props) { NAMED_SCOPE("data_item"); - static const char *samples = "Samples"; - static const char *events = "Events"; - static const char *condition = "Condition"; + static const char* samples = "Samples"; + static const char* events = "Events"; + static const char* condition = "Condition"; m_id = get("id"); m_name = maybeGet("name"); @@ -127,7 +127,7 @@ namespace mtconnect { if (rep) m_representation = reps.find(*rep)->second; - auto &category = get("category"); + auto& category = get("category"); auto units = maybeGet("units"); if (units && units->ends_with("3D")) @@ -184,14 +184,14 @@ namespace mtconnect { if (isCondition()) m_observatonProperties.insert_or_assign("type", get("type")); - if (const auto &cons = getList("Constraints"); cons && cons->size() == 1) + if (const auto& cons = getList("Constraints"); cons && cons->size() == 1) { - auto &con = cons->front(); + auto& con = cons->front(); if (con->getName() == "Value") m_constantValue = con->getValue(); // Check for legacy filters - for (auto &c : *cons) + for (auto& c : *cons) { if (c->getName() == "Filter") { @@ -204,21 +204,21 @@ namespace mtconnect { } } - if (const auto &init = maybeGet("InitialValue"); init) + if (const auto& init = maybeGet("InitialValue"); init) { m_initialValue = *init; } - if (const auto &init = maybeGet("InitialValue"); init) + if (const auto& init = maybeGet("InitialValue"); init) { m_initialValue = *init; } - if (const auto &filters = getList("Filters")) + if (const auto& filters = getList("Filters")) { - for (auto &filter : *filters) + for (auto& filter : *filters) { - const auto &type = filter->get("type"); + const auto& type = filter->get("type"); if (type == "MINIMUM_DELTA") m_minimumDelta = filter->getValue(); else if (type == "PERIOD") @@ -261,14 +261,14 @@ namespace mtconnect { } } - bool DataItem::hasName(const string &name) const + bool DataItem::hasName(const string& name) const { return m_id == name || (m_name && *m_name == name) || (m_source && *m_source == name) || (m_originalId && *m_originalId == name); } // Sort by: Device, Component, Category, DataItem - bool DataItem::operator<(const DataItem &another) const + bool DataItem::operator<(const DataItem& another) const { auto component = m_component.lock(); if (component == nullptr) @@ -300,7 +300,7 @@ namespace mtconnect { return false; } - void DataItem::setConstantValue(const std::string &value) + void DataItem::setConstantValue(const std::string& value) { ErrorList errors; Properties url {{"VALUE", value}}; @@ -308,7 +308,7 @@ namespace mtconnect { if (!errors.empty()) { LOG(error) << "Cannot set constant value for data item " << m_id << " to " << value; - for (auto &e : errors) + for (auto& e : errors) LOG(error) << e->what(); } else diff --git a/src/mtconnect/device_model/data_item/data_item.hpp b/src/mtconnect/device_model/data_item/data_item.hpp index 03216c53..c656ac02 100644 --- a/src/mtconnect/device_model/data_item/data_item.hpp +++ b/src/mtconnect/device_model/data_item/data_item.hpp @@ -83,7 +83,7 @@ namespace mtconnect { /// @brief constructor for a data item. name is always `DataItem`. /// /// @note Do not use this method directly. Use the `make()` method. - DataItem(const std::string &name, const entity::Properties &props); + DataItem(const std::string& name, const entity::Properties& props); static entity::FactoryPtr getFactory(); static entity::FactoryPtr getRoot(); @@ -91,8 +91,8 @@ namespace mtconnect { /// @param[in] props data item properties /// @param[in,out] errors list of errors creating the data item /// @return shared pointer to DataItem - static std::shared_ptr make(const entity::Properties &props, - entity::ErrorList &errors) + static std::shared_ptr make(const entity::Properties& props, + entity::ErrorList& errors) { entity::Properties ps(props); auto ptr = getFactory()->create("DataItem", ps, errors); @@ -106,60 +106,60 @@ namespace mtconnect { ///@{ /// @brief get the data item id - const auto &getId() const { return m_id; } + const auto& getId() const { return m_id; } /// @brief get the data item name - const auto &getName() const { return m_name; } + const auto& getName() const { return m_name; } /// @brief get the data item source - const auto &getSource() const { return get("Source"); } + const auto& getSource() const { return get("Source"); } /// @brief get the name or the id of the data item /// @return the preferred name - const auto &getPreferredName() const { return m_preferredName; } - const auto &getMinimumDelta() const { return m_minimumDelta; } - const auto &getMinimumPeriod() const { return m_minimumPeriod; } + const auto& getPreferredName() const { return m_preferredName; } + const auto& getMinimumDelta() const { return m_minimumDelta; } + const auto& getMinimumPeriod() const { return m_minimumPeriod; } /// @brief get a key related to the data item for creating observations /// @return a key - const auto &getKey() const { return m_key; } + const auto& getKey() const { return m_key; } /// @brief Return the type property /// @return the type property - const auto &getType() { return get("type"); } + const auto& getType() { return get("type"); } /// @brief Return the sub-type property /// @return The sub-type - const auto &getSubType() { return get("subType"); } + const auto& getSubType() { return get("subType"); } /// @brief get the pascalized name for the data item when represented as a observation /// @return observation name - const auto &getObservationName() const { return m_observationName; } + const auto& getObservationName() const { return m_observationName; } /// @brief get the properties to build an observation /// @return observation properties - const auto &getObservationProperties() const { return m_observatonProperties; } + const auto& getObservationProperties() const { return m_observatonProperties; } /// @brief get the topic with the path /// @return data item topic - const auto &getTopic() const { return m_topic; } + const auto& getTopic() const { return m_topic; } /// @brief get the topic name leaf node for this data item /// @return the topic name - const auto &getTopicName() const { return m_topicName; } + const auto& getTopicName() const { return m_topicName; } /// @brief get the initial value if one is set /// @return optional initial value - const auto &getInitialValue() const { return m_initialValue; } + const auto& getInitialValue() const { return m_initialValue; } Category getCategory() const { return m_category; } Representation getRepresentation() const { return m_representation; } SpecialClass getSpecialClass() const { return m_specialClass; } - const auto &getConstantValue() const { return m_constantValue; } + const auto& getConstantValue() const { return m_constantValue; } ///@} /// @brief make this data item a constant /// @param[in] value constant value - void setConstantValue(const std::string &value); + void setConstantValue(const std::string& value); /// @name boolean methods to interigate the data item ///@{ - bool hasName(const std::string &name) const; + bool hasName(const std::string& name) const; bool isSample() const { return m_category == SAMPLE; } bool isEvent() const { return m_category == EVENT; } bool isCondition() const { return m_category == CONDITION; } @@ -188,8 +188,8 @@ namespace mtconnect { void makeTopic(); // Value converter - const auto &getConverter() const { return m_converter; } - void setConverter(const UnitConversion &conv) + const auto& getConverter() const { return m_converter; } + void setConverter(const UnitConversion& conv) { m_converter = std::make_unique(conv); } @@ -214,23 +214,23 @@ namespace mtconnect { /// @brief get the preferred name /// @return the preferred name - const std::string &getSourceOrName() const { return m_preferredName; } + const std::string& getSourceOrName() const { return m_preferredName; } /// @brief get the source /// @return source if available - const std::optional &getDataSource() const { return m_dataSource; } + const std::optional& getDataSource() const { return m_dataSource; } /// @brief set the data source /// @param[in] source the source - void setDataSource(const std::string &source) { m_dataSource = source; } + void setDataSource(const std::string& source) { m_dataSource = source; } /// @brief set the topic for the data item /// @param[in] topic the topic - void setTopic(const std::string &topic) { m_topic = topic; } + void setTopic(const std::string& topic) { m_topic = topic; } - bool operator<(const DataItem &another) const; - bool operator==(const DataItem &another) const { return m_id == another.m_id; } + bool operator<(const DataItem& another) const; + bool operator==(const DataItem& another) const { return m_id == another.m_id; } /// @brief Return the category as a char * - const char *getCategoryText() const { return m_categoryText; } + const char* getCategoryText() const { return m_categoryText; } /// @brief create unique ids recursively /// @@ -241,8 +241,8 @@ namespace mtconnect { /// @param[in] sha the root sha1 /// @returns optional string value of the new id std::optional createUniqueId( - std::unordered_map &idMap, - const boost::uuids::detail::sha1 &sha1) override + std::unordered_map& idMap, + const boost::uuids::detail::sha1& sha1) override { m_originalId.emplace(m_id); auto pref = m_id == m_preferredName; @@ -255,7 +255,7 @@ namespace mtconnect { /// @brief Get a reference to the optional original id /// @returns optional original id - const auto &getOriginalId() const { return m_originalId; } + const auto& getOriginalId() const { return m_originalId; } /// @brief Update all id references associated with this data item /// @@ -271,7 +271,7 @@ namespace mtconnect { } protected: - double simpleFactor(const std::string &units); + double simpleFactor(const std::string& units); std::map buildAttributes() const; friend struct device_model::UpdateDataItemId; @@ -295,7 +295,7 @@ namespace mtconnect { // Category of data item Category m_category; - const char *m_categoryText; + const char* m_categoryText; // Type for observation entity::QName m_observationName; @@ -322,7 +322,7 @@ namespace mtconnect { using DataItemPtr = std::shared_ptr; } // namespace data_item - } // namespace device_model + } // namespace device_model using DataItemPtr = std::shared_ptr; using WeakDataItemPtr = std::weak_ptr; diff --git a/src/mtconnect/device_model/data_item/definition.hpp b/src/mtconnect/device_model/data_item/definition.hpp index 1779632b..b16b2009 100644 --- a/src/mtconnect/device_model/data_item/definition.hpp +++ b/src/mtconnect/device_model/data_item/definition.hpp @@ -32,7 +32,7 @@ namespace mtconnect::device_model::data_item { { public: using entity::Entity::Entity; - const entity::Value &getIdentity() const override + const entity::Value& getIdentity() const override { auto it = m_properties.find("key"); if (it == m_properties.end()) @@ -58,7 +58,7 @@ namespace mtconnect::device_model::data_item { auto cells = make_shared( Requirements {{"CellDefinition", ValueType::ENTITY, cell, 1, Requirement::Infinite}}); - cells->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + cells->setFunction([](const std::string& name, Properties& props) -> EntityPtr { auto ptr = make_shared(name, props); return dynamic_pointer_cast(ptr); }); @@ -72,7 +72,7 @@ namespace mtconnect::device_model::data_item { {"units", false}, {"CellDefinitions", ValueType::ENTITY_LIST, cells, false}}); entry->setOrder({"Description", "CellDefinitions"}); - entry->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + entry->setFunction([](const std::string& name, Properties& props) -> EntityPtr { auto ptr = make_shared(name, props); return dynamic_pointer_cast(ptr); }); diff --git a/src/mtconnect/device_model/data_item/relationships.hpp b/src/mtconnect/device_model/data_item/relationships.hpp index fb2af920..1e257abd 100644 --- a/src/mtconnect/device_model/data_item/relationships.hpp +++ b/src/mtconnect/device_model/data_item/relationships.hpp @@ -32,7 +32,7 @@ namespace mtconnect::device_model::data_item { using entity::Entity::Entity; ~Relationship() override = default; - const entity::Value &getIdentity() const override { return getProperty("idRef"); } + const entity::Value& getIdentity() const override { return getProperty("idRef"); } static entity::FactoryPtr getDataItemFactory() { @@ -47,7 +47,7 @@ namespace mtconnect::device_model::data_item { true}, {"name", false}, {"idRef", true}}); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return std::make_shared(name, props); }); } @@ -64,7 +64,7 @@ namespace mtconnect::device_model::data_item { { factory = make_shared(Requirements { {"type", ControlledVocab {"LIMIT"}, true}, {"name", false}, {"idRef", true}}); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return std::make_shared(name, props); }); } @@ -96,7 +96,7 @@ namespace mtconnect::device_model::data_item { {"SpecificationRelationship", ValueType::ENTITY, spec, 0, Requirement::Infinite}, {"DataItemRelationship", ValueType::ENTITY, di, 0, Requirement::Infinite}}); relationships->setMinListSize(1); - relationships->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + relationships->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return std::make_shared(name, props); }); } diff --git a/src/mtconnect/device_model/data_item/unit_conversion.cpp b/src/mtconnect/device_model/data_item/unit_conversion.cpp index a4447e31..1257c1e1 100644 --- a/src/mtconnect/device_model/data_item/unit_conversion.cpp +++ b/src/mtconnect/device_model/data_item/unit_conversion.cpp @@ -91,7 +91,7 @@ namespace mtconnect::device_model::data_item { /// @brief Handle KILO and CUBIC prefixes to provide the correct scaling /// @param[in] unit the incoming unit /// @return the {scale,power} as a pair. - static pair scaleAndPower(string_view &unit) + static pair scaleAndPower(string_view& unit) { double power = 1.0, scale = 1.0; @@ -131,8 +131,8 @@ namespace mtconnect::device_model::data_item { /// @param[in] from units from /// @param[in] to units to /// @return A units conversion object - std::unique_ptr UnitConversion::make(const std::string &from, - const std::string &to) + std::unique_ptr UnitConversion::make(const std::string& from, + const std::string& to) { if (from == to) return nullptr; @@ -140,7 +140,7 @@ namespace mtconnect::device_model::data_item { string key(from); key = key.append("-").append(to); - const auto &conversion = m_conversions.find(string(key)); + const auto& conversion = m_conversions.find(string(key)); if (conversion != m_conversions.end()) return make_unique(conversion->second); @@ -185,7 +185,7 @@ namespace mtconnect::device_model::data_item { key = *si; key = key.append("-").append(*ti); - const auto &conversion = m_conversions.find(string(key)); + const auto& conversion = m_conversions.find(string(key)); // Check for no support units and not power or factor scaling. if (conversion == m_conversions.end() && factor == 1.0) diff --git a/src/mtconnect/device_model/data_item/unit_conversion.hpp b/src/mtconnect/device_model/data_item/unit_conversion.hpp index 5baf6e4b..de68377c 100644 --- a/src/mtconnect/device_model/data_item/unit_conversion.hpp +++ b/src/mtconnect/device_model/data_item/unit_conversion.hpp @@ -34,7 +34,7 @@ namespace mtconnect::device_model::data_item { /// @param[in] factor /// @param[in] offset UnitConversion(double factor = 1.0, double offset = 0.0) : m_factor(factor), m_offset(offset) {} - UnitConversion(const UnitConversion &) = default; + UnitConversion(const UnitConversion&) = default; ~UnitConversion() = default; /// @brief convert a value @@ -45,7 +45,7 @@ namespace mtconnect::device_model::data_item { /// @brief convert a vector of values /// @param[in] value the vector of double /// @return converted vector of doubles - entity::Vector convert(const entity::Vector &value) const + entity::Vector convert(const entity::Vector& value) const { entity::Vector res(value.size()); for (size_t i = 0; i < value.size(); i++) @@ -56,7 +56,7 @@ namespace mtconnect::device_model::data_item { /// @brief convert a vector of values in place /// @param[in,out] value the vector of double - void convert(entity::Vector &value) const + void convert(entity::Vector& value) const { for (size_t i = 0; i < value.size(); i++) value[i] = convert(value[i]); @@ -64,11 +64,11 @@ namespace mtconnect::device_model::data_item { /// @brief Convert a entity variant Value if it holds a double or a vector of doubles /// @param[in] value a Value variant /// @return the converted value - entity::Value convertValue(const entity::Value &value) + entity::Value convertValue(const entity::Value& value) { - if (const auto &v = std::get_if(&value)) + if (const auto& v = std::get_if(&value)) return {convert(*v)}; - else if (const auto &a = std::get_if(&value)) + else if (const auto& a = std::get_if(&value)) return {convert(*a)}; else return nullptr; @@ -76,11 +76,11 @@ namespace mtconnect::device_model::data_item { /// @brief Convert a entity variant Value if it holds a double or a vector of doubles in place /// @param[in,out] value a Value variant - void convertValue(entity::Value &value) + void convertValue(entity::Value& value) { - if (const auto &v = std::get_if(&value)) + if (const auto& v = std::get_if(&value)) value = convert(*v); - else if (const auto &a = std::get_if(&value)) + else if (const auto& a = std::get_if(&value)) convert(*a); } /// @brief add a scaling factor to the conversion @@ -90,7 +90,7 @@ namespace mtconnect::device_model::data_item { /// @param[in] from units from /// @param[in] to units to /// @return A units conversion object - static std::unique_ptr make(const std::string &from, const std::string &to); + static std::unique_ptr make(const std::string& from, const std::string& to); /// @brief get the factor /// @return the scaling factor diff --git a/src/mtconnect/device_model/device.cpp b/src/mtconnect/device_model/device.cpp index befcdf36..63c5e2c1 100644 --- a/src/mtconnect/device_model/device.cpp +++ b/src/mtconnect/device_model/device.cpp @@ -38,7 +38,7 @@ namespace mtconnect { factory->getRequirement("uuid")->setMultiplicity(1, 1); factory->addRequirements( {{"iso841Class", false}, {"mtconnectVersion", false}, {"hash", false}}); - factory->setFunction([](const std::string &name, Properties &ps) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& ps) -> EntityPtr { auto device = make_shared("Device"s, ps); device->initialize(); return device; @@ -103,13 +103,13 @@ namespace mtconnect { } } - Device::Device(const std::string &name, entity::Properties &props) : Component(name, props) + Device::Device(const std::string& name, entity::Properties& props) : Component(name, props) { NAMED_SCOPE("device"); auto items = getList("DataItems"); if (items) { - for (auto &item : *items) + for (auto& item : *items) { auto di = dynamic_pointer_cast(item); cachePointers(di); @@ -117,7 +117,7 @@ namespace mtconnect { } } - void Device::setOptions(const ConfigOptions &options) + void Device::setOptions(const ConfigOptions& options) { if (auto opt = GetOption(options, PreserveUUID)) m_preserveUuid = *opt; @@ -134,7 +134,7 @@ namespace mtconnect { } } - void Device::addDataItem(DataItemPtr dataItem, entity::ErrorList &errors) + void Device::addDataItem(DataItemPtr dataItem, entity::ErrorList& errors) { Component::addDataItem(dataItem, errors); cachePointers(dataItem); @@ -154,7 +154,7 @@ namespace mtconnect { m_assetCount = dataItem; } - DataItemPtr Device::getDeviceDataItem(const std::string &name) const + DataItemPtr Device::getDeviceDataItem(const std::string& name) const { if (auto it = m_dataItems.get().find(name); it != m_dataItems.get().end()) return it->lock(); @@ -172,7 +172,7 @@ namespace mtconnect { return nullptr; } - void Device::createUniqueIds(std::unordered_map &idMap) + void Device::createUniqueIds(std::unordered_map& idMap) { boost::uuids::detail::sha1 sha; sha.process_bytes(m_uuid->data(), m_uuid->size()); diff --git a/src/mtconnect/device_model/device.hpp b/src/mtconnect/device_model/device.hpp index 5b1281c5..64acb896 100644 --- a/src/mtconnect/device_model/device.hpp +++ b/src/mtconnect/device_model/device.hpp @@ -67,7 +67,7 @@ namespace mtconnect { struct ExtractId { using result_type = std::string; - const result_type &operator()(const WeakDataItemPtr d) const { return d.lock()->getId(); } + const result_type& operator()(const WeakDataItemPtr d) const { return d.lock()->getId(); } }; /// @brief multi-index data item id extractor /// @@ -76,7 +76,7 @@ namespace mtconnect { struct ExtractOriginalId { using result_type = std::string; - const result_type operator()(const WeakDataItemPtr &d) const + const result_type operator()(const WeakDataItemPtr& d) const { const static result_type none {}; if (d.expired()) @@ -98,7 +98,7 @@ namespace mtconnect { struct ExtractName { using result_type = std::string; - const result_type operator()(const WeakDataItemPtr &d) const + const result_type operator()(const WeakDataItemPtr& d) const { const static result_type none {}; if (d.expired()) @@ -120,7 +120,7 @@ namespace mtconnect { struct ExtractSource { using result_type = std::string; - const result_type &operator()(const WeakDataItemPtr &d) const + const result_type& operator()(const WeakDataItemPtr& d) const { const static result_type none {}; if (d.expired()) @@ -139,7 +139,7 @@ namespace mtconnect { struct ExtractType { using result_type = std::string; - const result_type &operator()(const WeakDataItemPtr &d) const + const result_type& operator()(const WeakDataItemPtr& d) const { const static result_type none {}; if (d.expired()) @@ -164,7 +164,7 @@ namespace mtconnect { struct ExtractComponentId { using result_type = std::string; - const result_type &operator()(const std::weak_ptr &c) const + const result_type& operator()(const std::weak_ptr& c) const { return c.lock()->getId(); } @@ -172,7 +172,7 @@ namespace mtconnect { struct ExtractComponentType { using result_type = std::string; - const result_type &operator()(const std::weak_ptr &c) const + const result_type& operator()(const std::weak_ptr& c) const { return c.lock()->getName(); } @@ -180,7 +180,7 @@ namespace mtconnect { struct ExtractComponentName { using result_type = std::string; - const result_type operator()(const std::weak_ptr &c) const + const result_type operator()(const std::weak_ptr& c) const { auto comp = c.lock(); if (comp->hasProperty("name")) @@ -199,7 +199,7 @@ namespace mtconnect { /// @brief Constructor that sets variables from an attribute map /// @param[in] name the name of the device /// @param[in] props the device properties - Device(const std::string &name, entity::Properties &props); + Device(const std::string& name, entity::Properties& props); ~Device() override = default; /// @brief get a shared pointer to the device @@ -222,7 +222,7 @@ namespace mtconnect { /// @brief set any configuration options related to this device /// @param[in] options the options /// - `PreserveUUID` can be set to lock the uuid of this device - void setOptions(const ConfigOptions &options); + void setOptions(const ConfigOptions& options); /// @brief Add a data item to the device /// @param[in] dataItem shared pointer to the data item @@ -236,15 +236,15 @@ namespace mtconnect { /// 4. source /// @param[in] name the source, name, or id of the data item /// @return shared pointer to the data item if found - DataItemPtr getDeviceDataItem(const std::string &name) const; + DataItemPtr getDeviceDataItem(const std::string& name) const; /// @brief associate an adapter with the device /// @param[in] anAdapter an adapter - void addAdapter(source::adapter::Adapter *anAdapter) { m_adapters.emplace_back(anAdapter); } + void addAdapter(source::adapter::Adapter* anAdapter) { m_adapters.emplace_back(anAdapter); } /// @brief get a component by id /// @param[in] aId the component id /// @return shared pointer to the component if found - ComponentPtr getComponentById(const std::string &aId) const + ComponentPtr getComponentById(const std::string& aId) const { auto comp = m_componentIndex.get().find(aId); if (comp != m_componentIndex.get().end()) @@ -255,7 +255,7 @@ namespace mtconnect { /// @brief get a component by name /// @param[in] name the component name /// @return shared pointer to the component if found - ComponentPtr getComponentByName(const std::string &name) const + ComponentPtr getComponentByName(const std::string& name) const { auto comp = m_componentIndex.get().find(name); if (comp != m_componentIndex.get().end()) @@ -266,7 +266,7 @@ namespace mtconnect { /// @brief get a component by name /// @param[in] name the component name /// @return shared pointer to the component if found - std::list getComponentByType(const std::string &type) const + std::list getComponentByType(const std::string& type) const { std::list res; auto [first, last] = m_componentIndex.get().equal_range(type); @@ -296,15 +296,15 @@ namespace mtconnect { /// @brief get the data item index by id /// @return data item index by id - const auto &getDeviceDataItems() const { return m_dataItems.get(); } + const auto& getDeviceDataItems() const { return m_dataItems.get(); } /// @brief get the multi-index for data items /// @return data item multi-index - const auto &getDataItemIndex() const { return m_dataItems; } + const auto& getDataItemIndex() const { return m_dataItems; } /// @brief /// @param[in] dataItem /// @param[in,out] errors - void addDataItem(DataItemPtr dataItem, entity::ErrorList &errors) override; + void addDataItem(DataItemPtr dataItem, entity::ErrorList& errors) override; /// @brief get the version of this device /// @return mtconnet version @@ -341,7 +341,7 @@ namespace mtconnect { /// /// Converts the id attribute to a unique value and caches the original value /// in case it is required later - void createUniqueIds(std::unordered_map &idMap); + void createUniqueIds(std::unordered_map& idMap); protected: void cachePointers(DataItemPtr dataItem); @@ -357,7 +357,7 @@ namespace mtconnect { DataItemIndex m_dataItems; ComponentIndex m_componentIndex; - std::vector m_adapters; + std::vector m_adapters; }; using DevicePtr = std::shared_ptr; diff --git a/src/mtconnect/device_model/reference.cpp b/src/mtconnect/device_model/reference.cpp index 3897f994..e2ec8fb5 100644 --- a/src/mtconnect/device_model/reference.cpp +++ b/src/mtconnect/device_model/reference.cpp @@ -40,7 +40,7 @@ namespace mtconnect { { auto reference = make_shared(Requirements {{"idRef", true}, {"name", false}}, - [](const std::string &name, Properties &ps) -> EntityPtr { + [](const std::string& name, Properties& ps) -> EntityPtr { auto r = make_shared(name, ps); if (name == "ComponentRef") r->m_type = COMPONENT; diff --git a/src/mtconnect/device_model/reference.hpp b/src/mtconnect/device_model/reference.hpp index 5d91638a..97b09412 100644 --- a/src/mtconnect/device_model/reference.hpp +++ b/src/mtconnect/device_model/reference.hpp @@ -53,7 +53,7 @@ namespace mtconnect { /// @brief The Entity id this component is related to /// @return the `idRef` property - const entity::Value &getIdentity() const override { return getProperty("idRef"); } + const entity::Value& getIdentity() const override { return getProperty("idRef"); } static entity::FactoryPtr getFactory(); static entity::FactoryPtr getRoot(); @@ -64,10 +64,10 @@ namespace mtconnect { /// @brief get component for a component reference /// @return shared pointer to the component - auto &getComponent() const { return m_component; } + auto& getComponent() const { return m_component; } /// @brief get data item for a data item reference /// @return shared pointer to the data item - auto &getDataItem() const { return m_dataItem; } + auto& getDataItem() const { return m_dataItem; } /// @brief get the reference type /// @return data item or component relationship type auto getReferenceType() const { return m_type; } diff --git a/src/mtconnect/entity/data_set.cpp b/src/mtconnect/entity/data_set.cpp index 3d215b69..bdafddab 100644 --- a/src/mtconnect/entity/data_set.cpp +++ b/src/mtconnect/entity/data_set.cpp @@ -39,18 +39,18 @@ namespace l = boost::lambda; #ifdef BOOST_SPIRIT_DEBUG namespace std { - static inline ostream &operator<<(ostream &s, const mtconnect::observation::DataSetEntry &t); + static inline ostream& operator<<(ostream& s, const mtconnect::observation::DataSetEntry& t); - static inline ostream &operator<<(ostream &s, const mtconnect::observation::DataSetValue &t) + static inline ostream& operator<<(ostream& s, const mtconnect::observation::DataSetValue& t) { using namespace mtconnect::observation; - visit(mtconnect::overloaded {[&s](const monostate &) { s << "NULL"; }, - [&s](const std::string &st) { s << "string(" << st << ")"; }, - [&s](const int64_t &i) { s << "int(" << i << ")"; }, - [&s](const double &d) { s << "double(" << d << ")"; }, - [&s](const TableRow &arg) { + visit(mtconnect::overloaded {[&s](const monostate&) { s << "NULL"; }, + [&s](const std::string& st) { s << "string(" << st << ")"; }, + [&s](const int64_t& i) { s << "int(" << i << ")"; }, + [&s](const double& d) { s << "double(" << d << ")"; }, + [&s](const TableRow& arg) { s << "{"; - for (const auto &v : arg) + for (const auto& v : arg) { s << v << ", "; } @@ -60,13 +60,13 @@ namespace std { return s; } - static inline ostream &operator<<(ostream &s, const mtconnect::observation::DataSetEntry &t) + static inline ostream& operator<<(ostream& s, const mtconnect::observation::DataSetEntry& t) { s << t.m_key << "=" << t.m_value << (t.m_removed ? ":removed" : ""); return s; } - static inline ostream &operator<<(ostream &s, const mtconnect::observation::TableCell &t) + static inline ostream& operator<<(ostream& s, const mtconnect::observation::TableCell& t) { s << t.m_key << "=" << t.m_value; return s; @@ -80,24 +80,24 @@ using namespace std; namespace mtconnect::entity { /// @brief Functions called when parsing data sets namespace DataSetParserActions { - inline static void add_entry_f(DataSet &ds, const DataSetEntry &entry) { ds.emplace(entry); } + inline static void add_entry_f(DataSet& ds, const DataSetEntry& entry) { ds.emplace(entry); } struct TableCellConverter { - TableCellConverter(TableCellValue &value) : m_value(value) {} + TableCellConverter(TableCellValue& value) : m_value(value) {} - void operator()(const TableRow &row) { LOG(error) << "Table row cannot recurse"; } + void operator()(const TableRow& row) { LOG(error) << "Table row cannot recurse"; } template - void operator()(const T &v) + void operator()(const T& v) { m_value.emplace(v); } - TableCellValue &m_value; + TableCellValue& m_value; }; - inline static void add_cell_f(TableRow &row, const DataSetEntry &entry) + inline static void add_cell_f(TableRow& row, const DataSetEntry& entry) { TableCell cell(entry.m_key); cell.m_removed = entry.m_removed; @@ -105,8 +105,8 @@ namespace mtconnect::entity { row.emplace(cell); } - inline static void make_entry_f(DataSetEntry &entry, const string &key, - const boost::optional &v) + inline static void make_entry_f(DataSetEntry& entry, const string& key, + const boost::optional& v) { entry.m_key = key; if (v && !holds_alternative(*v)) @@ -114,8 +114,8 @@ namespace mtconnect::entity { else entry.m_removed = true; } - inline static void make_entry_f(DataSetEntry &entry, const string &key, - const boost::optional &v) + inline static void make_entry_f(DataSetEntry& entry, const string& key, + const boost::optional& v) { entry.m_key = key; if (v) @@ -136,14 +136,14 @@ namespace mtconnect::entity { { protected: template - void logError(P ¶ms, O &obj, R &result) + void logError(P& params, O& obj, R& result) { using namespace boost::fusion; - auto &start = at_c<0>(params); - auto &end = at_c<1>(params); + auto& start = at_c<0>(params); + auto& end = at_c<1>(params); // auto &what = at_c<2>(params); - auto &expected = at_c<3>(params); + auto& expected = at_c<3>(params); std::string text(start, end); @@ -222,11 +222,11 @@ namespace mtconnect::entity { using namespace boost::fusion; on_error(m_entry, - [&](auto ¶ms, auto &obj, auto &result) { logError(params, obj, result); }); + [&](auto& params, auto& obj, auto& result) { logError(params, obj, result); }); on_error(m_tableEntry, - [&](auto ¶ms, auto &obj, auto &result) { logError(params, obj, result); }); + [&](auto& params, auto& obj, auto& result) { logError(params, obj, result); }); on_error(m_start, - [&](auto ¶ms, auto &obj, auto &result) { logError(params, obj, result); }); + [&](auto& params, auto& obj, auto& result) { logError(params, obj, result); }); } protected: @@ -247,7 +247,7 @@ namespace mtconnect::entity { qi::rule m_tableEntry; }; - bool DataSet::parse(const std::string &text, bool table) + bool DataSet::parse(const std::string& text, bool table) { using boost::spirit::ascii::space; diff --git a/src/mtconnect/entity/data_set.hpp b/src/mtconnect/entity/data_set.hpp index 42d1dd6e..01e77812 100644 --- a/src/mtconnect/entity/data_set.hpp +++ b/src/mtconnect/entity/data_set.hpp @@ -44,7 +44,7 @@ namespace mtconnect::entity { /// do not have a simple `==` method. The method first makes sure the types are the same and /// then compares using `==`. template - inline bool SameValue(const T1 &v1, const T2 &v2) + inline bool SameValue(const T1& v1, const T2& v2) { return std::holds_alternative(v1) && std::get(v1) == v2; } @@ -58,7 +58,7 @@ namespace mtconnect::entity { /// @param key the key /// @param value the value as a string /// @param removed `true` if the key has been removed - Entry(const std::string &key, std::string &value, bool removed = false) + Entry(const std::string& key, std::string& value, bool removed = false) : m_key(key), m_value(std::move(value)), m_removed(removed) {} @@ -66,7 +66,7 @@ namespace mtconnect::entity { /// @param key the key /// @param value the value as a string /// @param removed `true` if the key has been removed - Entry(std::string &&key, std::string &value, bool removed = false) + Entry(std::string&& key, std::string& value, bool removed = false) : m_key(std::move(key)), m_value(std::move(value)), m_removed(removed) {} @@ -74,7 +74,7 @@ namespace mtconnect::entity { /// @param key the key /// @param value the value as a DataSet /// @param removed `true` if the key has been removed - Entry(const std::string &key, Entry &value, bool removed = false) + Entry(const std::string& key, Entry& value, bool removed = false) : m_key(key), m_value(std::move(value)), m_removed(removed) {} @@ -82,17 +82,17 @@ namespace mtconnect::entity { /// @param key the key /// @param value the a data set variant /// @param removed `true` if the key has been removed - Entry(const std::string &key, T value, bool removed = false) + Entry(const std::string& key, T value, bool removed = false) : m_key(key), m_value(std::forward(value)), m_removed(removed) {} /// @brief Create a data set entry with just a key (used for search) /// @param key - Entry(const std::string &key) : m_key(key), m_removed(false) {} - Entry(const Entry &other) = default; + Entry(const std::string& key) : m_key(key), m_removed(false) {} + Entry(const Entry& other) = default; Entry() : m_removed(false) {} /// @brief copy a data set entry from another - Entry &operator=(const Entry &other) + Entry& operator=(const Entry& other) { m_key = other.m_key; m_value = other.m_value; @@ -101,9 +101,9 @@ namespace mtconnect::entity { } /// @brief only compares keys for equality - bool operator==(const Entry &other) const { return m_key == other.m_key; } + bool operator==(const Entry& other) const { return m_key == other.m_key; } /// @brief only compares keys for less than - bool operator<(const Entry &other) const { return m_key < other.m_key; } + bool operator<(const Entry& other) const { return m_key < other.m_key; } /// @brief Compares the values of the entiry /// @param other the other value to compare against `m_value` @@ -111,15 +111,15 @@ namespace mtconnect::entity { /// /// Compares using the `SameValue` free function in the `data_set` namespace. It must be /// overloaded for any special types required by the variant type T. - bool sameValue(const Entry &other) const + bool sameValue(const Entry& other) const { - const auto &ov = other.m_value; - return std::visit([&ov](const auto &v) { return SameValue(ov, v); }, m_value); + const auto& ov = other.m_value; + return std::visit([&ov](const auto& v) { return SameValue(ov, v); }, m_value); } /// @brief compare a data entry ewith another /// @param other the other entry to compare - bool same(const Entry &other) const + bool same(const Entry& other) const { return m_key == other.m_key && m_removed == other.m_removed && sameValue(other); } @@ -143,7 +143,7 @@ namespace mtconnect::entity { /// @param key the key /// @return the typed value of the entry template - const T &get(const std::string &key) const + const T& get(const std::string& key) const { auto v = base::find(ET(key)); if (v == this->end()) @@ -157,7 +157,7 @@ namespace mtconnect::entity { /// @param key the key /// @return optional typed value of the entry template - const std::optional maybeGet(const std::string &key) const + const std::optional maybeGet(const std::string& key) const { auto v = base::find(ET(key)); if (v == this->end()) @@ -192,19 +192,19 @@ namespace mtconnect::entity { /// @param v1 The value of the other variant /// @param row The row we're comparing template - inline bool SameValue(const T1 &v1, const TableRow &row) + inline bool SameValue(const T1& v1, const TableRow& row) { if (!std::holds_alternative(v1)) return false; - const auto &orow = std::get(v1); + const auto& orow = std::get(v1); if (row.size() != orow.size()) return false; - for (const auto &c1 : row) + for (const auto& c1 : row) { - const auto &c2 = orow.find(c1); + const auto& c2 = orow.find(c1); if (c2 == orow.end() || !c2->sameValue(c1)) return false; } @@ -238,6 +238,6 @@ namespace mtconnect::entity { /// @brief Split the data set entries by space delimiters and account for the /// use of single and double quotes as well as curly braces - bool parse(const std::string &s, bool table); + bool parse(const std::string& s, bool table); }; } // namespace mtconnect::entity diff --git a/src/mtconnect/entity/entity.cpp b/src/mtconnect/entity/entity.cpp index dae493bc..114968c7 100644 --- a/src/mtconnect/entity/entity.cpp +++ b/src/mtconnect/entity/entity.cpp @@ -24,8 +24,8 @@ using namespace std; namespace mtconnect::entity { - bool Entity::addToList(const std::string &name, FactoryPtr factory, EntityPtr entity, - ErrorList &errors) + bool Entity::addToList(const std::string& name, FactoryPtr factory, EntityPtr entity, + ErrorList& errors) { if (!hasProperty(name)) { @@ -38,7 +38,7 @@ namespace mtconnect::entity { } else { - auto *entities = std::get_if(&getProperty_(name)); + auto* entities = std::get_if(&getProperty_(name)); if (entities) { std::get((*entities)->getProperty_("LIST")).emplace_back(entity); @@ -53,14 +53,14 @@ namespace mtconnect::entity { return true; } - bool Entity::removeFromList(const std::string &name, EntityPtr entity) + bool Entity::removeFromList(const std::string& name, EntityPtr entity) { - auto &v = getProperty_(name); - auto *p = std::get_if(&v); + auto& v = getProperty_(name); + auto* p = std::get_if(&v); if (p) { - auto &lv = (*p)->getProperty_("LIST"); - auto *l = std::get_if(&lv); + auto& lv = (*p)->getProperty_("LIST"); + auto* l = std::get_if(&lv); if (l) { auto it = std::find(l->begin(), l->end(), entity); @@ -75,44 +75,44 @@ namespace mtconnect::entity { return false; } - inline static void hash(boost::uuids::detail::sha1 &sha1, const DataSet &set); - inline static void hash(boost::uuids::detail::sha1 &sha1, const TableRow &set); + inline static void hash(boost::uuids::detail::sha1& sha1, const DataSet& set); + inline static void hash(boost::uuids::detail::sha1& sha1, const TableRow& set); template struct HashVisitor { - HashVisitor(boost::uuids::detail::sha1 &sha1) : m_sha1(sha1) {} + HashVisitor(boost::uuids::detail::sha1& sha1) : m_sha1(sha1) {} - void operator()(const EntityPtr &arg) { arg->hash(m_sha1); } - void operator()(const EntityList &arg) + void operator()(const EntityPtr& arg) { arg->hash(m_sha1); } + void operator()(const EntityList& arg) { - for (const auto &e : arg) + for (const auto& e : arg) e->hash(m_sha1); } - void operator()(const std::monostate &arg) { m_sha1.process_bytes("NIL", 4); } - void operator()(const Vector &arg) + void operator()(const std::monostate& arg) { m_sha1.process_bytes("NIL", 4); } + void operator()(const Vector& arg) { - for (const auto &e : arg) + for (const auto& e : arg) m_sha1.process_bytes(&e, sizeof(e)); } - void operator()(const std::string &arg) { m_sha1.process_bytes(arg.c_str(), arg.size()); } + void operator()(const std::string& arg) { m_sha1.process_bytes(arg.c_str(), arg.size()); } void operator()(const double arg) { m_sha1.process_bytes(&arg, sizeof(arg)); } void operator()(const int64_t arg) { m_sha1.process_bytes(&arg, sizeof(arg)); } void operator()(const bool arg) { m_sha1.process_bytes(&arg, sizeof(arg)); } - void operator()(const Timestamp &arg) + void operator()(const Timestamp& arg) { auto c = arg.time_since_epoch().count(); m_sha1.process_bytes(&c, sizeof(c)); } - void operator()(const ST &arg) { hash(m_sha1, arg); } - void operator()(const std::nullptr_t &arg) { m_sha1.process_bytes("NULL", 4); } + void operator()(const ST& arg) { hash(m_sha1, arg); } + void operator()(const std::nullptr_t& arg) { m_sha1.process_bytes("NULL", 4); } - boost::uuids::detail::sha1 &m_sha1; + boost::uuids::detail::sha1& m_sha1; }; - inline static void hash(boost::uuids::detail::sha1 &sha1, const DataSet &set) + inline static void hash(boost::uuids::detail::sha1& sha1, const DataSet& set) { - for (auto &e : set) + for (auto& e : set) { sha1.process_bytes(e.m_key.c_str(), e.m_key.size()); if (e.m_removed) @@ -127,9 +127,9 @@ namespace mtconnect::entity { } } - inline static void hash(boost::uuids::detail::sha1 &sha1, const TableRow &set) + inline static void hash(boost::uuids::detail::sha1& sha1, const TableRow& set) { - for (auto &e : set) + for (auto& e : set) { sha1.process_bytes(e.m_key.c_str(), e.m_key.size()); HashVisitor visitor(sha1); @@ -137,17 +137,17 @@ namespace mtconnect::entity { } } - void Entity::hash(boost::uuids::detail::sha1 &sha1, - const boost::unordered_set &skip) const + void Entity::hash(boost::uuids::detail::sha1& sha1, + const boost::unordered_set& skip) const { sha1.process_bytes(m_name.c_str(), m_name.size()); - for (const auto &e : m_properties) + for (const auto& e : m_properties) { // Skip hash if (!skip.contains(e.first) && !isHidden(e.first)) { - const auto &value = e.second; + const auto& value = e.second; sha1.process_bytes(e.first.c_str(), e.first.size()); HashVisitor visitor(sha1); visit(visitor, value); @@ -157,28 +157,28 @@ namespace mtconnect::entity { struct UniqueIdVisitor { - std::unordered_map &m_idMap; - const boost::uuids::detail::sha1 &m_sha1; - UniqueIdVisitor(std::unordered_map &idMap, - const boost::uuids::detail::sha1 &sha1) + std::unordered_map& m_idMap; + const boost::uuids::detail::sha1& m_sha1; + UniqueIdVisitor(std::unordered_map& idMap, + const boost::uuids::detail::sha1& sha1) : m_idMap(idMap), m_sha1(sha1) {} - void operator()(EntityPtr &p) { p->createUniqueId(m_idMap, m_sha1); } + void operator()(EntityPtr& p) { p->createUniqueId(m_idMap, m_sha1); } - void operator()(EntityList &l) + void operator()(EntityList& l) { - for (auto &e : l) + for (auto& e : l) e->createUniqueId(m_idMap, m_sha1); } template - void operator()(const T &) + void operator()(const T&) {} }; std::optional Entity::createUniqueId( - std::unordered_map &idMap, const boost::uuids::detail::sha1 &sha1) + std::unordered_map& idMap, const boost::uuids::detail::sha1& sha1) { optional res; @@ -206,7 +206,7 @@ namespace mtconnect::entity { UniqueIdVisitor visitor(idMap, sha1); // Recurse properties - for (auto &p : m_properties) + for (auto& p : m_properties) { std::visit(visitor, p.second); } @@ -216,26 +216,26 @@ namespace mtconnect::entity { struct ReferenceIdVisitor { - const std::unordered_map &m_idMap; - ReferenceIdVisitor(const std::unordered_map &idMap) : m_idMap(idMap) {} + const std::unordered_map& m_idMap; + ReferenceIdVisitor(const std::unordered_map& idMap) : m_idMap(idMap) {} - void operator()(EntityPtr &p) { p->updateReferences(m_idMap); } + void operator()(EntityPtr& p) { p->updateReferences(m_idMap); } - void operator()(EntityList &l) + void operator()(EntityList& l) { - for (auto &e : l) + for (auto& e : l) e->updateReferences(m_idMap); } template - void operator()(T &) + void operator()(T&) {} }; void Entity::updateReferences(std::unordered_map idMap) { using namespace boost::algorithm; - for (auto &prop : m_properties) + for (auto& prop : m_properties) { if (prop.first != "originalId" && (iends_with(prop.first, "idref") || (prop.first.length() > 2 && iends_with(prop.first, "id")))) @@ -251,7 +251,7 @@ namespace mtconnect::entity { ReferenceIdVisitor visitor(idMap); // Recurse all - for (auto &p : m_properties) + for (auto& p : m_properties) { std::visit(visitor, p.second); } diff --git a/src/mtconnect/entity/entity.hpp b/src/mtconnect/entity/entity.hpp index ec7567fb..aead5ea4 100644 --- a/src/mtconnect/entity/entity.hpp +++ b/src/mtconnect/entity/entity.hpp @@ -38,10 +38,10 @@ namespace mtconnect { struct PropertyKey : public QName { using QName::QName; - PropertyKey(const PropertyKey &s) : QName(s) {} - PropertyKey(const std::string &s) : QName(s) {} - PropertyKey(const std::string &&s) : QName(s) {} - PropertyKey(const char *s) : QName(s) {} + PropertyKey(const PropertyKey& s) : QName(s) {} + PropertyKey(const std::string& s) : QName(s) {} + PropertyKey(const std::string&& s) : QName(s) {} + PropertyKey(const char* s) : QName(s) {} /// @brief clears marks for this property void clearMark() const { m_mark = false; } @@ -66,7 +66,7 @@ namespace mtconnect { /// @param[in] props the set of properties /// @return the property value or std::nullopt template - inline std::optional OptionallyGet(const std::string &key, const Properties &props) + inline std::optional OptionallyGet(const std::string& key, const Properties& props) { auto p = props.find(key); if (p != props.end()) @@ -89,13 +89,13 @@ namespace mtconnect { Entity() {} /// @brief Create an entity with a name /// @param name entity name - Entity(const std::string &name) : m_name(name) {} + Entity(const std::string& name) : m_name(name) {} /// @brief Create an entity with a name and property set /// @param name entity name /// @param props entity properties - Entity(const std::string &name, const Properties &props) : m_name(name), m_properties(props) + Entity(const std::string& name, const Properties& props) : m_name(name), m_properties(props) {} - Entity(const Entity &entity) + Entity(const Entity& entity) : m_name(entity.m_name), m_properties(entity.m_properties), m_order(entity.m_order) { if (entity.m_attributes) @@ -105,19 +105,19 @@ namespace mtconnect { /// @brief Get a shared pointer /// @return shared pointer to the entity - EntityPtr getptr() const { return const_cast(this)->shared_from_this(); } + EntityPtr getptr() const { return const_cast(this)->shared_from_this(); } /// @brief method to return the entities identity. defaults to `id`. /// @return the identity - virtual const entity::Value &getIdentity() const { return getProperty("id"); } + virtual const entity::Value& getIdentity() const { return getProperty("id"); } /// @brief create unique ids recursively /// @param[in,out] idMap old entity id to new entity id map /// @param[in] sha the root sha1 /// @returns optional string value of the new id virtual std::optional createUniqueId( - std::unordered_map &idMap, - const boost::uuids::detail::sha1 &sha1); + std::unordered_map& idMap, + const boost::uuids::detail::sha1& sha1); /// @brief update all id references to the new ids recursively /// @param[in] idMap map of old ids to new ids @@ -147,17 +147,17 @@ namespace mtconnect { /// /// This may be extended to include a property set in the future. /// @returns `true` if the property is hidden - bool isHidden(const std::string &name) const { return name == "originalId"; } + bool isHidden(const std::string& name) const { return name == "originalId"; } /// @brief get the name of the entity /// @return name - const auto &getName() const { return m_name; } + const auto& getName() const { return m_name; } /// @brief get a const reference to the properties /// @return properties - const Properties &getProperties() const { return m_properties; } + const Properties& getProperties() const { return m_properties; } /// @brief get a property for a ley /// @param n the key /// @return The property or a Value with std::monstate() if not found - const Value &getProperty(const std::string &n) const + const Value& getProperty(const std::string& n) const { static Value noValue {std::monostate()}; auto it = m_properties.find(n); @@ -169,17 +169,17 @@ namespace mtconnect { /// @brief set a property /// @param key property key /// @param v property value - virtual void setProperty(const std::string &key, const Value &v) + virtual void setProperty(const std::string& key, const Value& v) { m_properties.insert_or_assign(key, v); } /// @brief set a property using a key/value pair /// @param property the key/value pair - void setProperty(const Property &property) { setProperty(property.first, property.second); } + void setProperty(const Property& property) { setProperty(property.first, property.second); } /// @brief check if a propery exists /// @param n the key /// @return `true` if the property exists - bool hasProperty(const std::string &n) const + bool hasProperty(const std::string& n) const { return m_properties.find(n) != m_properties.end(); } @@ -188,14 +188,14 @@ namespace mtconnect { bool hasValue() const { return hasProperty("VALUE"); } /// @brief set the name to a string /// @param name the name - void setName(const std::string &name) { m_name = name; } + void setName(const std::string& name) { m_name = name; } /// @brief set the name as a qname /// @param name the qname - void setQName(const std::string &name) { m_name.setQName(name); } + void setQName(const std::string& name) { m_name.setQName(name); } /// @brief apply function f to the property if it exists /// @param name the key /// @param f the lambda to be called if the property exists - void applyTo(const std::string &name, std::function f) + void applyTo(const std::string& name, std::function f) { auto p = m_properties.find(name); if (p != m_properties.end()) @@ -203,11 +203,11 @@ namespace mtconnect { } /// @brief apply a function to a `VALUE` property /// @param f the function - void applyToValue(std::function f) { applyTo("VALUE", f); } + void applyToValue(std::function f) { applyTo("VALUE", f); } /// @brief get the `VALUE` property if it exists, Value is mutable /// @return `VALUE` property - Value &getValue() + Value& getValue() { thread_local Value null; null = std::monostate {}; @@ -218,7 +218,7 @@ namespace mtconnect { return null; } /// @brief get a const reference to the `VALUE` property - const Value &getValue() const { return getProperty("VALUE"); } + const Value& getValue() const { return getProperty("VALUE"); } /// @brief get the entity with a list property if it exists /// /// This is a convience method that gets the property by name. If the property is an @@ -226,14 +226,14 @@ namespace mtconnect { /// /// @param name the key for the list /// @return the entity list or std::nullopt - std::optional getList(const std::string &name) const + std::optional getList(const std::string& name) const { - auto &v = getProperty(name); - auto *p = std::get_if(&v); + auto& v = getProperty(name); + auto* p = std::get_if(&v); if (p) { - auto &lv = (*p)->getProperty("LIST"); - auto *l = std::get_if(&lv); + auto& lv = (*p)->getProperty("LIST"); + auto* l = std::get_if(&lv); if (l) return *l; } @@ -243,14 +243,14 @@ namespace mtconnect { /// @brief Get the LIST property if it exists from an entity /// @returns a reference to the entity list. Returns an empty list if it does not exist. - const EntityList &getListProperty() const + const EntityList& getListProperty() const { static EntityList null; auto p = m_properties.find("LIST"); if (p != m_properties.end()) { - auto *l = std::get_if(&p->second); + auto* l = std::get_if(&p->second); if (l) return *l; } @@ -259,7 +259,7 @@ namespace mtconnect { /// @brief Get the LIST property if it exists from an entity /// @returns a reference to the entity list. Returns an empty list if it does not exist. - EntityList &getListProperty() + EntityList& getListProperty() { thread_local EntityList null; null.clear(); @@ -267,7 +267,7 @@ namespace mtconnect { auto p = m_properties.find("LIST"); if (p != m_properties.end()) { - auto *l = std::get_if(&p->second); + auto* l = std::get_if(&p->second); if (l) return *l; } @@ -280,20 +280,20 @@ namespace mtconnect { /// @param entity entity to add /// @param errors errors if add fails /// @return `true` if successful - bool addToList(const std::string &name, FactoryPtr factory, EntityPtr entity, - ErrorList &errors); + bool addToList(const std::string& name, FactoryPtr factory, EntityPtr entity, + ErrorList& errors); /// @brief Remove an entity from an entity list /// @param name the key for the entity list /// @param entity the entity to remove /// @return `true` if successful - bool removeFromList(const std::string &name, EntityPtr entity); + bool removeFromList(const std::string& name, EntityPtr entity); /// @brief sets the `VALUE` property /// @param v the value - void setValue(const Value &v) { setProperty("VALUE", v); } + void setValue(const Value& v) { setProperty("VALUE", v); } /// @brief remove a property /// @param name the key - void erase(const std::string &name) { m_properties.erase(name); } + void erase(const std::string& name) { m_properties.erase(name); } /// @brief get a property for a key /// @tparam T the type of the property @@ -301,7 +301,7 @@ namespace mtconnect { /// @return the value as type T /// @throws `std::bad_variant_access` if incorrect type template - const T &get(const std::string &name) const + const T& get(const std::string& name) const { return std::get(getProperty(name)); } @@ -311,7 +311,7 @@ namespace mtconnect { /// @return the value as type T /// @throws `std::bad_variant_access` if incorrect type template - const T &getValue() const + const T& getValue() const { return std::get(getValue()); } @@ -322,7 +322,7 @@ namespace mtconnect { /// @return the value of the property as type T or nullopt /// @throws `std::bad_variant_access` if incorrect type template - const std::optional maybeGet(const std::string &name) const + const std::optional maybeGet(const std::string& name) const { return OptionallyGet(name, m_properties); } @@ -348,11 +348,11 @@ namespace mtconnect { /// @brief get an iterator to the property /// @param[in] name the key /// @return an iterator to the property - auto find(const std::string &name) { return m_properties.find(name); } + auto find(const std::string& name) { return m_properties.find(name); } /// @brief erase a propery using an iterator /// @param[in] it an iterator pointing to the propery /// @return the iterator after erase - auto erase(Properties::iterator &it) { return m_properties.erase(it); } + auto erase(Properties::iterator& it) { return m_properties.erase(it); } /// @brief tells the entity which properties are attributes for XML generation /// @param[in] a the attributes void setAttributes(AttributeSet a) @@ -362,7 +362,7 @@ namespace mtconnect { } /// @brief get the attributes for XML generation /// @return attribute set - const auto &getAttributes() const + const auto& getAttributes() const { static AttributeSet empty; if (m_attributes) @@ -374,7 +374,7 @@ namespace mtconnect { /// @brief checks if two entity models are different–does a deep analysis /// @param other the other entity to check /// @return `true` if the entities are different - bool different(const Entity &other) const; + bool different(const Entity& other) const; /// @brief cover method for entity comparison /// @param other the other entity to check @@ -384,12 +384,12 @@ namespace mtconnect { /// @brief compare two entities for equality /// @param other the other entity /// @return `true` if they have equal name and properties - bool operator==(const Entity &other) const { return !different(other); } + bool operator==(const Entity& other) const { return !different(other); } /// @brief compare two entities for inequality /// @param other the other entity /// @return `true` if they have unequal name and properties - bool operator!=(const Entity &other) const { return different(other); } + bool operator!=(const Entity& other) const { return different(other); } /// @brief update this entity to be the same as other /// @param other the other entity @@ -433,8 +433,8 @@ namespace mtconnect { /// @brief Computes the sha1 hash of the entity skipping properties in `skip` /// @param[in,out] sha1 The boost sha1 accumulator /// @param[in] skip A set of parameters to skip–not recursive - void hash(boost::uuids::detail::sha1 &sha1, - const boost::unordered_set &skip) const; + void hash(boost::uuids::detail::sha1& sha1, + const boost::unordered_set& skip) const; /// @brief The virtual method that covers `hash(boost::uuids::detail::sha1&, /// boost::unordered_set skip)` @@ -443,7 +443,7 @@ namespace mtconnect { /// {"hash", "timestamp"} that should not be included in the unique hash of the entity. /// /// @param[in,out] sha1 The boost sha1 accumulator - virtual void hash(boost::uuids::detail::sha1 &sha1) const + virtual void hash(boost::uuids::detail::sha1& sha1) const { // Default do not skip anything, subclasses add skipped // parameters. @@ -451,7 +451,7 @@ namespace mtconnect { hash(sha1, skip); } - Value &getProperty_(const std::string &name) + Value& getProperty_(const std::string& name) { thread_local Value noValue {std::monostate()}; noValue = std::monostate {}; @@ -473,16 +473,16 @@ namespace mtconnect { /// @brief variant visitor to compare two entity parameter values for equality struct ValueEqualVisitor { - ValueEqualVisitor(const Value &t) : m_this(t) {} + ValueEqualVisitor(const Value& t) : m_this(t) {} - bool operator()(const EntityPtr &other) + bool operator()(const EntityPtr& other) { return *std::get(m_this) == *(other.get()); } - bool operator()(const EntityList &other) + bool operator()(const EntityList& other) { - const auto &list = std::get(m_this); + const auto& list = std::get(m_this); if (list.size() != other.size()) return false; @@ -493,7 +493,7 @@ namespace mtconnect { { auto id = (*it)->getIdentity(); auto oit = - boost::find_if(other, [&id](const auto &e) { return id == e->getIdentity(); }); + boost::find_if(other, [&id](const auto& e) { return id == e->getIdentity(); }); if (oit == other.end() || *(it->get()) != *(oit->get())) return false; } @@ -511,16 +511,16 @@ namespace mtconnect { } template - bool operator()(const T &other) + bool operator()(const T& other) { return std::get(m_this) == other; } private: - const Value &m_this; + const Value& m_this; }; - inline bool operator==(const Value &v1, const Value &v2) + inline bool operator==(const Value& v1, const Value& v2) { if (v1.index() != v2.index()) return false; @@ -528,9 +528,9 @@ namespace mtconnect { return std::visit(ValueEqualVisitor(v1), v2); } - inline bool operator!=(const Value &v1, const Value &v2) { return !(v1 == v2); } + inline bool operator!=(const Value& v1, const Value& v2) { return !(v1 == v2); } - inline bool Entity::different(const Entity &other) const + inline bool Entity::different(const Entity& other) const { if (m_name != other.m_name) return true; @@ -552,22 +552,22 @@ namespace mtconnect { /// @brief variant visitor to merge two entities struct ValueMergeVisitor { - ValueMergeVisitor(Value &t, const std::set protect) + ValueMergeVisitor(Value& t, const std::set protect) : m_this(t), m_protect(protect) {} - bool operator()(const EntityPtr &other) + bool operator()(const EntityPtr& other) { return std::get(m_this)->reviseTo(other, m_protect); } - bool mergeRemainder(EntityList &list, EntityList &revised, bool changed) + bool mergeRemainder(EntityList& list, EntityList& revised, bool changed) { if (changed) { - for (auto &o : list) + for (auto& o : list) { - const auto &id = o->getIdentity(); + const auto& id = o->getIdentity(); if (std::holds_alternative(id)) { auto s = std::get(id); @@ -578,8 +578,8 @@ namespace mtconnect { } else { - changed = std::any_of(list.begin(), list.end(), [this](const auto &o) { - const auto &id = o->getIdentity(); + changed = std::any_of(list.begin(), list.end(), [this](const auto& o) { + const auto& id = o->getIdentity(); if (std::holds_alternative(id)) { auto s = std::get(id); @@ -595,17 +595,17 @@ namespace mtconnect { return changed; } - bool operator()(const EntityList &other) + bool operator()(const EntityList& other) { bool changed = false; auto list = std::get(m_this); EntityList revised; - for (const auto &o : other) + for (const auto& o : other) { - if (const auto &id = o->getIdentity(); !std::holds_alternative(id)) + if (const auto& id = o->getIdentity(); !std::holds_alternative(id)) { - auto it = boost::find_if(list, [&id](auto &e) { return e->getIdentity() == id; }); + auto it = boost::find_if(list, [&id](auto& e) { return e->getIdentity() == id; }); LOG(trace) << " ... Merging " << o->getName() << " with identity: "; if (std::holds_alternative(id)) LOG(trace) << std::get(id); @@ -631,7 +631,7 @@ namespace mtconnect { { LOG(trace) << " ... Merging " << o->getName() << " with no identity"; - auto it = boost::find_if(list, [&o](auto &e) { return *(o.get()) == *(e.get()); }); + auto it = boost::find_if(list, [&o](auto& e) { return *(o.get()) == *(e.get()); }); if (it != list.end()) { @@ -660,7 +660,7 @@ namespace mtconnect { } template - bool operator()(const T &other) + bool operator()(const T& other) { if (std::get(m_this) != other) { @@ -674,7 +674,7 @@ namespace mtconnect { } private: - Value &m_this; + Value& m_this; std::set m_protect; }; @@ -689,7 +689,7 @@ namespace mtconnect { } std::vector removed; - for (auto &[key, value] : m_properties) + for (auto& [key, value] : m_properties) { auto op = other->m_properties.find(key); if (op != other->m_properties.end()) @@ -717,7 +717,7 @@ namespace mtconnect { } } - for (auto &key : removed) + for (auto& key : removed) { m_properties.erase(key); } @@ -730,20 +730,20 @@ namespace mtconnect { { /// @brief constructor /// @param os the output stream - StreamOutputVisitor(std::ostream &os) : m_os(os) {} + StreamOutputVisitor(std::ostream& os) : m_os(os) {} - void operator()(const std::monostate &) { m_os << "null"; } + void operator()(const std::monostate&) { m_os << "null"; } - void operator()(const EntityPtr &entity) + void operator()(const EntityPtr& entity) { - const auto &id = entity->getIdentity(); + const auto& id = entity->getIdentity(); m_os << "Entity(" << entity->getName() << ":"; StreamOutputVisitor visitor(m_os); std::visit(visitor, id); m_os << ")"; } - void operator()(const EntityList &list) + void operator()(const EntityList& list) { m_os << "EntityList["; for (auto e : list) @@ -755,14 +755,14 @@ namespace mtconnect { m_os << "]"; } - void operator()(const DataSet &dataSet) { m_os << "DataSet(" << dataSet.size() << " items)"; } + void operator()(const DataSet& dataSet) { m_os << "DataSet(" << dataSet.size() << " items)"; } - void operator()(const QName &qname) { m_os << qname.str(); } + void operator()(const QName& qname) { m_os << qname.str(); } - void operator()(const Vector &vec) + void operator()(const Vector& vec) { m_os << "Vector["; - for (const auto &v : vec) + for (const auto& v : vec) { m_os << v << " "; } @@ -770,18 +770,18 @@ namespace mtconnect { } template - void operator()(const T &value) + void operator()(const T& value) { m_os << value; } - std::ostream &m_os; + std::ostream& m_os; }; /// @brief output operator for Value /// @param os the output stream /// @param v the Value to output - inline std::ostream &operator<<(std::ostream &os, const Value &v) + inline std::ostream& operator<<(std::ostream& os, const Value& v) { StreamOutputVisitor visitor(os); std::visit(visitor, v); @@ -791,7 +791,7 @@ namespace mtconnect { /// @brief output operator for Value /// @param os the output stream /// @param v the Value to output - inline std::ostream &operator<<(std::ostream &os, const EntityPtr &v) + inline std::ostream& operator<<(std::ostream& os, const EntityPtr& v) { StreamOutputVisitor visitor(os); visitor(v); diff --git a/src/mtconnect/entity/factory.cpp b/src/mtconnect/entity/factory.cpp index 8f2f1184..7a3ae218 100644 --- a/src/mtconnect/entity/factory.cpp +++ b/src/mtconnect/entity/factory.cpp @@ -27,7 +27,7 @@ using namespace std; namespace mtconnect { namespace entity { - void Factory::_dupFactory(FactoryPtr &factory, FactoryMap &factories) + void Factory::_dupFactory(FactoryPtr& factory, FactoryMap& factories) { auto old = factories.find(factory); if (old != factories.end()) @@ -43,9 +43,9 @@ namespace mtconnect { } } - void Factory::_deepCopy(FactoryMap &factories) + void Factory::_deepCopy(FactoryMap& factories) { - for (auto &r : m_requirements) + for (auto& r : m_requirements) { auto factory = r.getFactory(); if (factory) @@ -55,12 +55,12 @@ namespace mtconnect { } } - for (auto &f : m_matchFactory) + for (auto& f : m_matchFactory) { _dupFactory(f.second, factories); } - for (auto &f : m_stringFactory) + for (auto& f : m_stringFactory) { _dupFactory(f.second, factories); } @@ -75,11 +75,11 @@ namespace mtconnect { return copy; } - void Factory::LogError(const std::string &what) { LOG(warning) << what; } + void Factory::LogError(const std::string& what) { LOG(warning) << what; } - void Factory::performConversions(Properties &properties, ErrorList &errors) const + void Factory::performConversions(Properties& properties, ErrorList& errors) const { - for (const auto &r : m_requirements) + for (const auto& r : m_requirements) { if (r.getType() != ValueType::ENTITY && r.getType() != ValueType::ENTITY_LIST) { @@ -88,10 +88,10 @@ namespace mtconnect { { try { - Value &v = p->second; + Value& v = p->second; ConvertValueToType(v, r.getType()); } - catch (PropertyError &e) + catch (PropertyError& e) { LOG(warning) << "Error occurred converting " << r.getName() << ": " << e.what(); e.setProperty(r.getName()); @@ -103,11 +103,11 @@ namespace mtconnect { } } - bool Factory::isSufficient(Properties &properties, ErrorList &errors) const + bool Factory::isSufficient(Properties& properties, ErrorList& errors) const { NAMED_SCOPE("EntityFactory"); bool success {true}; - for (auto &p : properties) + for (auto& p : properties) p.first.clearMark(); if (m_isList && m_minListSize > 0) @@ -121,7 +121,7 @@ namespace mtconnect { else { p->first.setMark(); - auto &list = get(p->second); + auto& list = get(p->second); if (list.size() < m_minListSize) { errors.emplace_back(new PropertyError("The list must have at least " + @@ -131,7 +131,7 @@ namespace mtconnect { } } - for (const auto &r : m_requirements) + for (const auto& r : m_requirements) { Properties::const_iterator p; if (m_isList && r.getType() == ValueType::ENTITY) @@ -157,7 +157,7 @@ namespace mtconnect { success = false; } } - catch (PropertyError &e) + catch (PropertyError& e) { LogError(e.what()); if (r.isRequired()) @@ -180,7 +180,7 @@ namespace mtconnect { list extra; list remove; namespace ba = boost::algorithm; - for (auto &p : properties) + for (auto& p : properties) { // Check for extra properties if (!p.first.m_mark) @@ -205,7 +205,7 @@ namespace mtconnect { }; // Remove extranous properties - for (auto &p : remove) + for (auto& p : remove) properties.erase(p); // Check if additional properties exist @@ -213,7 +213,7 @@ namespace mtconnect { { std::stringstream os; os << "The following keys were present and not expected: "; - for (auto &k : extra) + for (auto& k : extra) os << k << ","; errors.emplace_back(new PropertyError(os.str())); success = false; diff --git a/src/mtconnect/entity/factory.hpp b/src/mtconnect/entity/factory.hpp index eb72ff87..096a428f 100644 --- a/src/mtconnect/entity/factory.hpp +++ b/src/mtconnect/entity/factory.hpp @@ -32,8 +32,8 @@ namespace mtconnect { class AGENT_LIB_API Factory : public Matcher, public std::enable_shared_from_this { public: - using Function = std::function; - using Matcher = std::function; + using Function = std::function; + using Matcher = std::function; using MatchPair = std::pair; using StringFactory = std::unordered_map; using MatchFactory = std::list; @@ -43,12 +43,12 @@ namespace mtconnect { /// @param name name of the entity /// @param p properties for the entity /// @return shared entity pointer - static auto createEntity(const std::string &name, Properties &p) + static auto createEntity(const std::string& name, Properties& p) { return std::make_shared(name, p); } - Factory(const Factory &other) = default; + Factory(const Factory& other) = default; Factory() : m_function(createEntity) {} ~Factory() = default; @@ -82,15 +82,15 @@ namespace mtconnect { { m_order = std::make_shared(); int i = 0; - for (auto &e : list) + for (auto& e : list) m_order->emplace(e, i++); } /// @brief set the order from a order map /// @param list the order map - void setOrder(OrderMapPtr &list) { m_order = list; } + void setOrder(OrderMapPtr& list) { m_order = list; } /// @brief get the order list /// @return pointer to the order list - const OrderMapPtr &getOrder() const { return m_order; } + const OrderMapPtr& getOrder() const { return m_order; } /// @brief set if this is a list factory /// @param list `true` if this is a list @@ -124,16 +124,16 @@ namespace mtconnect { /// @brief does this factory have a requirement for the property /// @param name the property key /// @return `true` if there is a requirement - bool isProperty(const std::string &name) const { return m_properties.count(name) > 0; } + bool isProperty(const std::string& name) const { return m_properties.count(name) > 0; } /// @brief checks if this is a property set /// @param name the property key /// @return `true` if this is a property with ENTITY or ENTITY_SET with multiplicity more than /// 0 - bool isPropertySet(const std::string &name) const { return m_propertySets.count(name) > 0; } + bool isPropertySet(const std::string& name) const { return m_propertySets.count(name) > 0; } /// @brief is there a requirement with a simple value /// @param name the property key /// @return `true` if this is a value propery - bool isSimpleProperty(const std::string &name) const + bool isSimpleProperty(const std::string& name) const { return m_simpleProperties.count(name) > 0; } @@ -141,12 +141,12 @@ namespace mtconnect { /// @brief is this requirement resolved with a data set /// @param name the name of the property /// @return `true` if this is a data set - bool isDataSet(const std::string &name) const { return m_dataSets.count(name) > 0; } + bool isDataSet(const std::string& name) const { return m_dataSets.count(name) > 0; } /// @brief is this requirement resolved with a table /// @param name the name of the property /// @return `true` if this is a table - bool isTable(const std::string &name) const { return m_tables.count(name) > 0; } + bool isTable(const std::string& name) const { return m_tables.count(name) > 0; } /// @brief is the value of this entity a data set or table /// @returns `true` if the value is a data set or table @@ -159,9 +159,9 @@ namespace mtconnect { /// @brief get the requirement pointer for a key /// @param name the property key /// @return requirement pointer - Requirement *getRequirement(const std::string &name) + Requirement* getRequirement(const std::string& name) { - for (auto &r : m_requirements) + for (auto& r : m_requirements) { if (r.getName() == name) return &r; @@ -171,12 +171,12 @@ namespace mtconnect { /// @brief add requirements to the factory /// @param reqs the set of requirements - void addRequirements(const Requirements &reqs) + void addRequirements(const Requirements& reqs) { - for (const auto &r : reqs) + for (const auto& r : reqs) { auto old = std::find_if(m_requirements.begin(), m_requirements.end(), - [&r](Requirement &o) { return r.getName() == o.getName(); }); + [&r](Requirement& o) { return r.getName() == o.getName(); }); if (old != m_requirements.end()) { *old = r; @@ -191,12 +191,12 @@ namespace mtconnect { /// @brief convert properties to the requirements /// @param[in,out] p the properties to convert /// @param[in,out] errors errors related to conversions - void performConversions(Properties &p, ErrorList &errors) const; + void performConversions(Properties& p, ErrorList& errors) const; /// @brief check if the properties are sufficient for the factory /// @param[in,out] properties the properties for the entity /// @param[in,out] errors errors related to verification /// @return `true` if the properties are sufficient - virtual bool isSufficient(Properties &properties, ErrorList &errors) const; + virtual bool isSufficient(Properties& properties, ErrorList& errors) const; /// @name Entity factory ///@{ @@ -206,7 +206,7 @@ namespace mtconnect { /// @param[in,out] p properties for the entity /// @param[in,out] errors errors when creating the entity /// @return shared entity pointer if successful - EntityPtr make(const std::string &name, Properties &p, ErrorList &errors) const + EntityPtr make(const std::string& name, Properties& p, ErrorList& errors) const { try { @@ -220,14 +220,14 @@ namespace mtconnect { } } - catch (EntityError &e) + catch (EntityError& e) { e.setEntity(name); errors.emplace_back(std::make_unique(e)); LogError("Failed to create " + name + ": " + e.what()); } - for (auto &e : errors) + for (auto& e : errors) { if (e->getEntity().empty()) e->setEntity(name); @@ -237,7 +237,7 @@ namespace mtconnect { } /// @brief alias for `make()` - EntityPtr operator()(const std::string &name, Properties &p, ErrorList &errors) const + EntityPtr operator()(const std::string& name, Properties& p, ErrorList& errors) const { return make(name, p, errors); } @@ -248,7 +248,7 @@ namespace mtconnect { /// @param name the name to match against /// @param factory the factory to create entities /// @return `true` if successful - bool registerFactory(const std::string &name, FactoryPtr factory) + bool registerFactory(const std::string& name, FactoryPtr factory) { m_stringFactory.emplace(make_pair(name, factory)); return true; @@ -257,9 +257,9 @@ namespace mtconnect { /// @param exp expression to match against /// @param factory the factory to create entities /// @return `true` if successful - bool registerFactory(const std::regex &exp, FactoryPtr factory) + bool registerFactory(const std::regex& exp, FactoryPtr factory) { - auto matcher = [exp](const std::string &name) { return std::regex_match(name, exp); }; + auto matcher = [exp](const std::string& name) { return std::regex_match(name, exp); }; m_matchFactory.emplace_back(make_pair(matcher, factory)); return true; } @@ -267,7 +267,7 @@ namespace mtconnect { /// @param matcher matcher to use to match /// @param factory the factory to create entities /// @return `true` if successful - bool registerFactory(const Matcher &matcher, FactoryPtr factory) + bool registerFactory(const Matcher& matcher, FactoryPtr factory) { m_matchFactory.emplace_back(make_pair(matcher, factory)); return true; @@ -276,14 +276,14 @@ namespace mtconnect { /// @brief find a factory for a name /// @param name the name to match /// @return the factory - FactoryPtr factoryFor(const std::string &name) const + FactoryPtr factoryFor(const std::string& name) const { const auto it = m_stringFactory.find(name); if (it != m_stringFactory.end()) return it->second; else { - for (const auto &r : m_matchFactory) + for (const auto& r : m_matchFactory) { if (r.first(name)) return r.second; @@ -296,7 +296,7 @@ namespace mtconnect { /// @brief check if a factory exists /// @param s name to match against /// @return `true` if there is a factory - bool matches(const std::string &s) const override + bool matches(const std::string& s) const override { auto f = factoryFor(s); return (bool)f; @@ -313,7 +313,7 @@ namespace mtconnect { /// @param a list of entities /// @param errors errors when creating entity /// @return entity if successful - EntityPtr create(const std::string &name, EntityList &a, ErrorList &errors) + EntityPtr create(const std::string& name, EntityList& a, ErrorList& errors) { auto factory = factoryFor(name); if (factory) @@ -333,7 +333,7 @@ namespace mtconnect { /// @param[in,out] a the properties /// @param[in,out] errors errors when creating entity /// @return entity if successful - EntityPtr create(const std::string &name, Properties &a, ErrorList &errors) + EntityPtr create(const std::string& name, Properties& a, ErrorList& errors) { auto factory = factoryFor(name); if (factory) @@ -350,7 +350,7 @@ namespace mtconnect { /// @param[in,out] a the properties as an rvalue /// @param[in,out] errors errors when creating entity /// @return entity if successful - EntityPtr create(const std::string &name, Properties &&a, ErrorList &errors) + EntityPtr create(const std::string& name, Properties&& a, ErrorList& errors) { auto factory = factoryFor(name); if (factory) @@ -366,7 +366,7 @@ namespace mtconnect { /// @param name the entity name /// @param[in,out] a the properties as an rvalue /// @return entity if successful - EntityPtr create(const std::string &name, Properties &a) + EntityPtr create(const std::string& name, Properties& a) { ErrorList list; return create(name, a, list); @@ -381,7 +381,7 @@ namespace mtconnect { { m_requirements.emplace_back("originalId", false); } - for (auto &r : m_requirements) + for (auto& r : m_requirements) { m_properties.emplace(r.getName()); auto factory = r.getFactory(); @@ -419,7 +419,7 @@ namespace mtconnect { void registerMatchers() { auto m = getptr(); - for (auto &r : m_requirements) + for (auto& r : m_requirements) { if (r.getUpperMultiplicity() > 1 && !r.hasMatcher()) { @@ -441,9 +441,9 @@ namespace mtconnect { protected: using FactoryMap = std::map; - static void LogError(const std::string &what); - void _deepCopy(FactoryMap &factories); - static void _dupFactory(FactoryPtr &factory, FactoryMap &factories); + static void LogError(const std::string& what); + void _deepCopy(FactoryMap& factories); + static void _dupFactory(FactoryPtr& factory, FactoryMap& factories); protected: Requirements m_requirements; diff --git a/src/mtconnect/entity/json_parser.hpp b/src/mtconnect/entity/json_parser.hpp index d0324aaf..e895b718 100644 --- a/src/mtconnect/entity/json_parser.hpp +++ b/src/mtconnect/entity/json_parser.hpp @@ -46,7 +46,7 @@ namespace mtconnect { /// @param version the version to parse /// @param errors Errors that occurred creating the entities /// @return an entity shared pointer if successful - EntityPtr parse(FactoryPtr factory, const std::string &document, ErrorList &errors); + EntityPtr parse(FactoryPtr factory, const std::string& document, ErrorList& errors); protected: uint32_t m_version; diff --git a/src/mtconnect/entity/json_printer.hpp b/src/mtconnect/entity/json_printer.hpp index 3dc3216c..a4cd5447 100644 --- a/src/mtconnect/entity/json_printer.hpp +++ b/src/mtconnect/entity/json_printer.hpp @@ -31,18 +31,18 @@ namespace mtconnect::entity { protected: struct PropertyVisitor { - PropertyVisitor(T &writer, JsonPrinter &printer, std::optional> &obj, - const EntityPtr &entity) + PropertyVisitor(T& writer, JsonPrinter& printer, std::optional>& obj, + const EntityPtr& entity) : m_obj(obj), m_printer(printer), m_entity(entity), m_writer(writer) {} - void operator()(const EntityPtr &arg) + void operator()(const EntityPtr& arg) { m_obj->Key(m_key->c_str()); m_printer.printEntity(arg); } - void operator()(const EntityList &arg) + void operator()(const EntityList& arg) { bool isPropertyList = *m_key != "LIST"; if (m_entity->hasListWithAttribute()) @@ -61,7 +61,7 @@ namespace mtconnect::entity { { m_obj->Key(m_key->str()); AutoJsonArray ary(m_writer); - for (auto &ei : arg) + for (auto& ei : arg) m_printer.printEntity(ei); } else @@ -70,42 +70,42 @@ namespace mtconnect::entity { } } - void operator()(const std::monostate &arg) {} - void operator()(const std::nullptr_t &arg) {} + void operator()(const std::monostate& arg) {} + void operator()(const std::nullptr_t& arg) {} - void operator()(const Vector &v) + void operator()(const Vector& v) { m_printer.printKey(*m_obj, *m_key); AutoJsonArray ary(m_writer); - for (auto &d : v) + for (auto& d : v) m_obj->Add(d); } - void operator()(const DataSet &v) + void operator()(const DataSet& v) { m_printer.printKey(*m_obj, *m_key); m_printer.print(v); } - void operator()(const Timestamp &v) + void operator()(const Timestamp& v) { m_printer.printKey(*m_obj, *m_key); m_printer.print(v); } template - void operator()(const A &arg) + void operator()(const A& arg) { m_printer.printKey(*m_obj, *m_key); m_obj->Add(arg); } - std::optional> &m_obj; - JsonPrinter &m_printer; - const EntityPtr &m_entity; - T &m_writer; + std::optional>& m_obj; + JsonPrinter& m_printer; + const EntityPtr& m_entity; + T& m_writer; - const PropertyKey *m_key {nullptr}; + const PropertyKey* m_key {nullptr}; }; public: @@ -113,7 +113,7 @@ namespace mtconnect::entity { /// @param version the supported MTConnect serialization version /// - Version 1 has a repreated objects in arrays for collections of objects /// - Version 2 combines arrays of objects by type - JsonPrinter(T &writer, uint32_t version, bool includeHidden = false) + JsonPrinter(T& writer, uint32_t version, bool includeHidden = false) : m_version(version), m_writer(writer), m_includeHidden(includeHidden) {}; /// @brief create a json object from an entity @@ -140,7 +140,7 @@ namespace mtconnect::entity { PropertyVisitor visitor {m_writer, *this, obj, entity}; - for (auto &prop : entity->getProperties()) + for (auto& prop : entity->getProperties()) { if (m_includeHidden || !entity->isHidden(prop.first)) { @@ -154,7 +154,7 @@ namespace mtconnect::entity { /// @param[in] list a list of EntityPtr objects /// @tparam T2 Type of iterable collection must contain Entity subclass template - void printEntityList(const T2 &list, bool embed = false) + void printEntityList(const T2& list, bool embed = false) { if (m_version == 1) printEntityList1(list); @@ -172,10 +172,10 @@ namespace mtconnect::entity { /// @param[in] list a list of EntityPtr objects /// @tparam T2 Type of iterable collection must contain Entity subclass template - void printEntityList1(const T2 &list) + void printEntityList1(const T2& list) { AutoJsonArray ary(m_writer); - for (auto &ei : list) + for (auto& ei : list) { AutoJsonObject obj(m_writer); obj.Key(ei->getName()); @@ -191,12 +191,12 @@ namespace mtconnect::entity { /// @param[in] list a list of EntityPtr objects /// @tparam T2 Type of iterable collection must contain Entity subclass template - void printEntityList2(const T2 &list, bool embed = false) + void printEntityList2(const T2& list, bool embed = false) { AutoJsonObject obj(m_writer, !embed); // Sort the entities by name, use a string view so we don't copy std::multimap entities; - for (auto &e : list) + for (auto& e : list) entities.emplace(std::string_view(e->getName()), e); /// Group the entities by name @@ -204,7 +204,7 @@ namespace mtconnect::entity { { auto next = std::upper_bound(it, entities.end(), it->first, - [](const auto &a, const auto &b) { return a.compare(b.first) < 0; }); + [](const auto& a, const auto& b) { return a.compare(b.first) < 0; }); obj.Key(it->first); @@ -219,7 +219,7 @@ namespace mtconnect::entity { } protected: - void printKey(AutoJsonObject &obj, const PropertyKey &key) + void printKey(AutoJsonObject& obj, const PropertyKey& key) { if (key == "VALUE" || key == "RAW") obj.Key("value"); @@ -229,20 +229,20 @@ namespace mtconnect::entity { struct DataSetVisitor { - DataSetVisitor(T &writer, JsonPrinter &printer, AutoJsonObject &obj) + DataSetVisitor(T& writer, JsonPrinter& printer, AutoJsonObject& obj) : m_writer(writer), m_printer(printer), m_obj(obj) {} - void operator()(const std::monostate &) {} - void operator()(const std::string &st) { m_obj.AddPairs(*m_key, st); } - void operator()(const int64_t &i) { m_obj.AddPairs(*m_key, i); } - void operator()(const double &d) { m_obj.AddPairs(*m_key, d); } - void operator()(const TableRow &arg) + void operator()(const std::monostate&) {} + void operator()(const std::string& st) { m_obj.AddPairs(*m_key, st); } + void operator()(const int64_t& i) { m_obj.AddPairs(*m_key, i); } + void operator()(const double& d) { m_obj.AddPairs(*m_key, d); } + void operator()(const TableRow& arg) { AutoJsonObject row(m_writer, *m_key); DataSetVisitor visitor(m_writer, m_printer, row); - for (auto &c : arg) + for (auto& c : arg) { if (c.m_removed) { @@ -258,17 +258,17 @@ namespace mtconnect::entity { } } - T &m_writer; - JsonPrinter &m_printer; - AutoJsonObject &m_obj; - const std::string *m_key {nullptr}; + T& m_writer; + JsonPrinter& m_printer; + AutoJsonObject& m_obj; + const std::string* m_key {nullptr}; }; - void print(const DataSet &set) + void print(const DataSet& set) { AutoJsonObject obj(m_writer); DataSetVisitor visitor(m_writer, *this, obj); - for (auto &e : set) + for (auto& e : set) { if (e.m_removed) { @@ -283,11 +283,11 @@ namespace mtconnect::entity { } } } - void print(const Timestamp &t) { m_writer.String(format(t).c_str()); } + void print(const Timestamp& t) { m_writer.String(format(t).c_str()); } protected: uint32_t m_version; - T &m_writer; + T& m_writer; bool m_includeHidden {false}; }; @@ -308,7 +308,7 @@ namespace mtconnect::entity { { using namespace rapidjson; StringBuffer output; - RenderJson(output, m_pretty, [&](auto &writer) { + RenderJson(output, m_pretty, [&](auto& writer) { JsonPrinter printer(writer, m_version, m_includeHidden); printer.printEntity(entity); }); @@ -327,7 +327,7 @@ namespace mtconnect::entity { { using namespace rapidjson; StringBuffer output; - RenderJson(output, m_pretty, [&](auto &writer) { + RenderJson(output, m_pretty, [&](auto& writer) { JsonPrinter printer(writer, m_version, m_includeHidden); printer.print(entity); }); diff --git a/src/mtconnect/entity/qname.hpp b/src/mtconnect/entity/qname.hpp index d321e85f..998e86af 100644 --- a/src/mtconnect/entity/qname.hpp +++ b/src/mtconnect/entity/qname.hpp @@ -36,7 +36,7 @@ namespace mtconnect { /// @brief Create a qualified name from name and ns /// @param name the name /// @param ns the namespace prefix - QName(const std::string &name, const std::string &ns) + QName(const std::string& name, const std::string& ns) { assign(ns + ":" + name); m_nsLen = ns.length(); @@ -44,13 +44,13 @@ namespace mtconnect { /// @brief Create a qualified name from a string /// @param qname the name - QName(const std::string &qname) { setQName(qname); } + QName(const std::string& qname) { setQName(qname); } /// @brief Set the qualified name. Parses the qname and looks for a colon and splits the /// name into the namespace prefix and the name /// @param qname /// @param ns - void setQName(const std::string &qname, const std::optional &ns = std::nullopt) + void setQName(const std::string& qname, const std::optional& ns = std::nullopt) { if (ns) { @@ -73,13 +73,13 @@ namespace mtconnect { /// @brief copy constructor /// @param other the source - QName(const QName &other) = default; + QName(const QName& other) = default; ~QName() = default; /// @brief operator = /// @param name the source /// @return this qname - QName &operator=(const std::string &name) + QName& operator=(const std::string& name) { setQName(name); return *this; @@ -87,7 +87,7 @@ namespace mtconnect { /// @brief set the name portion /// @param name - void setName(const std::string &name) + void setName(const std::string& name) { if (m_nsLen == 0) { @@ -106,7 +106,7 @@ namespace mtconnect { /// @brief set the namespace portion /// @param ns the namespace - void setNs(const std::string &ns) + void setNs(const std::string& ns) { std::string name(getName()); m_nsLen = ns.length(); @@ -129,7 +129,7 @@ namespace mtconnect { /// @brief get this qname /// @return this - const auto &getQName() const { return *this; } + const auto& getQName() const { return *this; } /// @brief get a string view to the name portion of the qname /// @return string view of the name @@ -165,10 +165,10 @@ namespace mtconnect { /// @brief get the qname as a string /// @return this - std::string &str() { return *this; } + std::string& str() { return *this; } /// @brief const get this as a string /// @return this - const std::string &str() const { return *this; } + const std::string& str() const { return *this; } protected: size_t m_nsLen; diff --git a/src/mtconnect/entity/requirement.cpp b/src/mtconnect/entity/requirement.cpp index b04c276b..976c90d3 100644 --- a/src/mtconnect/entity/requirement.cpp +++ b/src/mtconnect/entity/requirement.cpp @@ -34,7 +34,7 @@ using namespace std; namespace mtconnect { namespace entity { - Requirement::Requirement(const std::string &name, ValueType type, FactoryPtr f, bool required) + Requirement::Requirement(const std::string& name, ValueType type, FactoryPtr f, bool required) : m_name(name), m_upperMultiplicity(1), m_lowerMultiplicity(required ? 1 : 0), m_type(type) { NAMED_SCOPE("EntityRequirement"); @@ -46,7 +46,7 @@ namespace mtconnect { m_factory = f; } - Requirement::Requirement(const std::string &name, ValueType type, FactoryPtr f, int lower, + Requirement::Requirement(const std::string& name, ValueType type, FactoryPtr f, int lower, int upper) : m_name(name), m_upperMultiplicity(upper), m_lowerMultiplicity(lower), m_type(type) { @@ -57,7 +57,7 @@ namespace mtconnect { m_factory = f; } - bool Requirement::isMetBy(const Value &value) const + bool Requirement::isMetBy(const Value& value) const { // Is this a multiple entry if ((m_type == ValueType::ENTITY || m_type == ValueType::ENTITY_LIST)) @@ -80,7 +80,7 @@ namespace mtconnect { { const auto l = std::get(value); int count = 0; - for (const auto &e : l) + for (const auto& e : l) { if (matches(e->getName())) count++; @@ -110,7 +110,7 @@ namespace mtconnect { } if (std::holds_alternative(value)) { - auto &v = std::get(value); + auto& v = std::get(value); if (m_pattern && !std::regex_match(v, *m_pattern)) { throw PropertyError("Invalid value for '" + m_name + "': '" + v + "' is not allowed", @@ -124,7 +124,7 @@ namespace mtconnect { } else if (std::holds_alternative(value)) { - auto &v = std::get(value); + auto& v = std::get(value); if (m_size) { if (v.size() != *m_size) @@ -162,24 +162,24 @@ namespace mtconnect { ValueConverter(ValueType type, bool table) : m_type(type), m_table(table) {} // ------------ Strings ---------------- - void operator()(const string &arg, DataSet &t) { t.parse(arg, m_table); } - void operator()(const string &arg, int64_t &r) + void operator()(const string& arg, DataSet& t) { t.parse(arg, m_table); } + void operator()(const string& arg, int64_t& r) { - char *ep = nullptr; - const char *sp = arg.c_str(); + char* ep = nullptr; + const char* sp = arg.c_str(); r = strtoll(sp, &ep, 10); if (ep == sp) throw PropertyError("cannot convert string '" + arg + "' to integer"); } - void operator()(const string &arg, double &r) + void operator()(const string& arg, double& r) { - char *ep = nullptr; - const char *sp = arg.c_str(); + char* ep = nullptr; + const char* sp = arg.c_str(); r = strtod(sp, &ep); if (ep == sp) throw PropertyError("cannot convert string '" + arg + "' to double"); } - void operator()(const string &arg, Timestamp &ts) + void operator()(const string& arg, Timestamp& ts) { istringstream in(arg); @@ -195,13 +195,13 @@ namespace mtconnect { date::from_stream(in, "%F", ts); } } - void operator()(const string &arg, Vector &r) + void operator()(const string& arg, Vector& r) { if (arg.empty()) return; - char *np(nullptr); - const char *cp = arg.c_str(); + char* np(nullptr); + const char* cp = arg.c_str(); while (cp && *cp != '\0') { @@ -224,8 +224,8 @@ namespace mtconnect { if (r.size() == 0) throw PropertyError("cannot convert string '" + arg + "' to vector"); } - void operator()(const string &arg, bool &r) { r = arg == "true"; } - void operator()(const string &arg, string &r) + void operator()(const string& arg, bool& r) { r = arg == "true"; } + void operator()(const string& arg, string& r) { r = arg; if (m_type == ValueType::USTRING) @@ -246,83 +246,83 @@ namespace mtconnect { } // ----------------- double - void operator()(const double arg, string &v) { v = format(arg); } - void operator()(const double arg, int64_t &v) { v = arg; } - void operator()(const double arg, bool &v) { v = arg != 0.0; } - void operator()(const double arg, Vector &v) { v.emplace_back(arg); } - void operator()(const double arg, Timestamp &v) + void operator()(const double arg, string& v) { v = format(arg); } + void operator()(const double arg, int64_t& v) { v = arg; } + void operator()(const double arg, bool& v) { v = arg != 0.0; } + void operator()(const double arg, Vector& v) { v.emplace_back(arg); } + void operator()(const double arg, Timestamp& v) { v = std::chrono::system_clock::from_time_t(arg); } template - void operator()(const double arg, T &v) + void operator()(const double arg, T& v) { throw PropertyError("Cannot convert a double to a non-scalar"); } // ------------ int 64 - void operator()(const int64_t arg, string &v) { v = to_string(arg); } - void operator()(const int64_t arg, bool &v) { v = arg != 0; } - void operator()(const int64_t arg, double &v) { v = double(arg); } - void operator()(const int64_t arg, Vector &v) { v.emplace_back(double(arg)); } - void operator()(const int64_t arg, Timestamp &v) + void operator()(const int64_t arg, string& v) { v = to_string(arg); } + void operator()(const int64_t arg, bool& v) { v = arg != 0; } + void operator()(const int64_t arg, double& v) { v = double(arg); } + void operator()(const int64_t arg, Vector& v) { v.emplace_back(double(arg)); } + void operator()(const int64_t arg, Timestamp& v) { v = std::chrono::system_clock::from_time_t(arg); } template - void operator()(const int64_t arg, T &v) + void operator()(const int64_t arg, T& v) { throw PropertyError("Cannot convert a int64 to a non-scalar"); } // ----------- Vector - void operator()(const Vector &arg, string &v) + void operator()(const Vector& arg, string& v) { if (arg.size() > 0) { stringstream s; - for (auto &v : arg) + for (auto& v : arg) s << formatted(v) << ' '; v = string_view(s.str().c_str(), s.str().size() - 1); } } template - void operator()(const Vector &arg, T &v) + void operator()(const Vector& arg, T& v) { throw PropertyError("Cannot convert a Vector to anything other than a string"); } // ------------ Bool - void operator()(const bool arg, string &v) { v = arg ? "true" : "false"; } - void operator()(const bool arg, Vector &v) { v.emplace_back(arg); } - void operator()(const bool arg, int64_t &v) { v = arg; } - void operator()(const bool arg, double &v) { v = arg; } + void operator()(const bool arg, string& v) { v = arg ? "true" : "false"; } + void operator()(const bool arg, Vector& v) { v.emplace_back(arg); } + void operator()(const bool arg, int64_t& v) { v = arg; } + void operator()(const bool arg, double& v) { v = arg; } template - void operator()(const bool arg, T &v) + void operator()(const bool arg, T& v) { throw PropertyError("Cannot convert a bool to a non-scalar"); } // ------------ Timestamp - void operator()(const Timestamp &arg, string &v) { v = format(arg); } - void operator()(const Timestamp &arg, int64_t &v) + void operator()(const Timestamp& arg, string& v) { v = format(arg); } + void operator()(const Timestamp& arg, int64_t& v) { v = chrono::system_clock::to_time_t(arg); } - void operator()(const Timestamp &arg, double &v) { v = arg.time_since_epoch().count(); } - void operator()(const Timestamp &arg, Vector &v) + void operator()(const Timestamp& arg, double& v) { v = arg.time_since_epoch().count(); } + void operator()(const Timestamp& arg, Vector& v) { v.emplace_back(double(arg.time_since_epoch().count())); } template - void operator()(const Timestamp &arg, T &) + void operator()(const Timestamp& arg, T&) { throw PropertyError("Cannot convert a Timestamp to a non-scalar"); } // -- Catch all template - void operator()(const U &arg, T &t) + void operator()(const U& arg, T& t) { stringstream s; s << "Cannot convert from " << typeid(U).name() << " to " << typeid(T).name(); @@ -334,7 +334,7 @@ namespace mtconnect { bool m_table; }; - bool ConvertValueToType(Value &value, ValueType type, bool table) + bool ConvertValueToType(Value& value, ValueType type, bool table) { if (ValueType(value.index()) == type) return false; diff --git a/src/mtconnect/entity/requirement.hpp b/src/mtconnect/entity/requirement.hpp index 473aeb36..364439f7 100644 --- a/src/mtconnect/entity/requirement.hpp +++ b/src/mtconnect/entity/requirement.hpp @@ -93,43 +93,43 @@ namespace mtconnect::entity { /// @param type the target type /// @param table special treatment if a table (data sets of data set) /// @return `true` if conversion was successful - bool AGENT_LIB_API ConvertValueToType(Value &value, ValueType type, bool table = false); + bool AGENT_LIB_API ConvertValueToType(Value& value, ValueType type, bool table = false); /// @brief Error class when an error occurred class AGENT_LIB_API EntityError : public std::logic_error { public: - explicit EntityError(const std::string &s, const std::string &e = "") + explicit EntityError(const std::string& s, const std::string& e = "") : std::logic_error(s), m_entity(e) {} - explicit EntityError(const char *s, const std::string &e = "") + explicit EntityError(const char* s, const std::string& e = "") : std::logic_error(s), m_entity(e) {} - EntityError(const EntityError &o) noexcept : std::logic_error(o), m_entity(o.m_entity) {} + EntityError(const EntityError& o) noexcept : std::logic_error(o), m_entity(o.m_entity) {} ~EntityError() override = default; /// @brief an error related to an entity /// @return the error text - virtual const char *what() const noexcept override + virtual const char* what() const noexcept override { if (m_text.empty()) { - auto *t = const_cast(this); + auto* t = const_cast(this); t->m_text = m_entity + ": " + std::logic_error::what(); } return m_text.c_str(); } /// @brief set the entity text /// @param[in] s the entity text - void setEntity(const std::string &s) + void setEntity(const std::string& s) { m_text.clear(); m_entity = s; } - virtual EntityError *dup() const noexcept { return new EntityError(*this); } - const std::string &getEntity() const { return m_entity; } + virtual EntityError* dup() const noexcept { return new EntityError(*this); } + const std::string& getEntity() const { return m_entity; } protected: std::string m_text; @@ -140,34 +140,34 @@ namespace mtconnect::entity { class AGENT_LIB_API PropertyError : public EntityError { public: - explicit PropertyError(const std::string &s, const std::string &p = "", - const std::string &e = "") + explicit PropertyError(const std::string& s, const std::string& p = "", + const std::string& e = "") : EntityError(s, e), m_property(p) {} - explicit PropertyError(const char *s, const std::string &p = "", const std::string &e = "") + explicit PropertyError(const char* s, const std::string& p = "", const std::string& e = "") : EntityError(s, e), m_property(p) {} - PropertyError(const PropertyError &o) noexcept : EntityError(o), m_property(o.m_property) {} + PropertyError(const PropertyError& o) noexcept : EntityError(o), m_property(o.m_property) {} ~PropertyError() override = default; - virtual const char *what() const noexcept override + virtual const char* what() const noexcept override { if (m_text.empty()) { - auto *t = const_cast(this); + auto* t = const_cast(this); t->m_text = m_entity + "(" + m_property + "): " + std::logic_error::what(); } return m_text.c_str(); } - void setProperty(const std::string &p) + void setProperty(const std::string& p) { m_text.clear(); m_property = p; } - EntityError *dup() const noexcept override { return new PropertyError(*this); } - const std::string &getProperty() const { return m_property; } + EntityError* dup() const noexcept override { return new PropertyError(*this); } + const std::string& getProperty() const { return m_property; } protected: std::string m_property; @@ -179,7 +179,7 @@ namespace mtconnect::entity { struct Matcher { virtual ~Matcher() = default; - virtual bool matches(const std::string &s) const = 0; + virtual bool matches(const std::string& s) const = 0; }; using MatcherPtr = std::weak_ptr; @@ -196,14 +196,14 @@ namespace mtconnect::entity { /// @param name the property key /// @param type the data type /// @param required `true` if the property is required - Requirement(const std::string &name, ValueType type, bool required = true) + Requirement(const std::string& name, ValueType type, bool required = true) : m_name(name), m_upperMultiplicity(1), m_lowerMultiplicity(required ? 1 : 0), m_type(type) {} /// @brief property requirement with a type that can be optional /// @param name the property key /// @param required `true` if the property is required /// @param type the data type defaulted to `STRING` - Requirement(const std::string &name, bool required, ValueType type = ValueType::STRING) + Requirement(const std::string& name, bool required, ValueType type = ValueType::STRING) : m_name(name), m_upperMultiplicity(1), m_lowerMultiplicity(required ? 1 : 0), m_type(type) {} /// @brief property that can occur mode than once @@ -211,7 +211,7 @@ namespace mtconnect::entity { /// @param type they data type /// @param lower a lower bound occurrence /// @param upper an upper bound occurrence - Requirement(const std::string &name, ValueType type, int lower, int upper) + Requirement(const std::string& name, ValueType type, int lower, int upper) : m_name(name), m_upperMultiplicity(upper), m_lowerMultiplicity(lower), m_type(type) {} /// @brief property with required vector size @@ -219,7 +219,7 @@ namespace mtconnect::entity { /// @param type the data type /// @param size the size of the value /// @param required `true` if the property is required - Requirement(const std::string &name, ValueType type, int size, bool required = true) + Requirement(const std::string& name, ValueType type, int size, bool required = true) : m_name(name), m_upperMultiplicity(1), m_lowerMultiplicity(required ? 1 : 0), @@ -231,33 +231,33 @@ namespace mtconnect::entity { /// @param type the data type. `ENTITY` or `ENTITY_LIST` /// @param o the entity factory /// @param required `true` if the property is required - Requirement(const std::string &name, ValueType type, FactoryPtr o, bool required = true); + Requirement(const std::string& name, ValueType type, FactoryPtr o, bool required = true); /// @brief property requirement for an entity or entity list /// @param name the property key /// @param type the data type. `ENTITY` or `ENTITY_LIST` /// @param o the entity factory /// @param lower lower bound for multiplicity /// @param upper upper bound for multiplicity - Requirement(const std::string &name, ValueType type, FactoryPtr o, int lower, int upper); + Requirement(const std::string& name, ValueType type, FactoryPtr o, int lower, int upper); /// @brief property requirement for a string value that must match a controlled vocabulary /// @param name the property key /// @param vocab the set of possible values /// @param required `true` if the property is required - Requirement(const std::string &name, const ControlledVocab &vocab, bool required = true) + Requirement(const std::string& name, const ControlledVocab& vocab, bool required = true) : m_name(name), m_upperMultiplicity(1), m_lowerMultiplicity(required ? 1 : 0), m_type(ValueType::STRING) { m_vocabulary.emplace(); - for (auto &s : vocab) + for (auto& s : vocab) m_vocabulary->emplace(s); } /// @brief propery requirement where the text must match a regex pattern /// @param name the property key /// @param pattern the regex /// @param required `true` if the property is required - Requirement(const std::string &name, const std::regex &pattern, bool required = true) + Requirement(const std::string& name, const std::regex& pattern, bool required = true) : m_name(name), m_upperMultiplicity(1), m_lowerMultiplicity(required ? 1 : 0), @@ -266,8 +266,8 @@ namespace mtconnect::entity { {} Requirement() = default; - Requirement(const Requirement &o) = default; - Requirement &operator=(const Requirement &o) = default; + Requirement(const Requirement& o) = default; + Requirement& operator=(const Requirement& o) = default; ~Requirement() = default; /// @brief gets required state @@ -287,22 +287,22 @@ namespace mtconnect::entity { std::optional getSize() const { return m_size; } /// @brief gets the matcher /// @return the matcher - const auto &getMatcher() const { return m_matcher; } + const auto& getMatcher() const { return m_matcher; } /// @brief sets the matcher for this requirement /// @param[in] m a shared pointer to the matcher void setMatcher(MatcherPtr m) { m_matcher = m; } /// @brief gets the name of the requirement /// @return the name for the property key - const std::string &getName() const { return m_name; } + const std::string& getName() const { return m_name; } /// @brief gets the value type for the requirement /// @return the value type ValueType getType() const { return m_type; } /// @brief gets the factory for elements and element lists /// @return the factory - auto &getFactory() const { return m_factory; } + auto& getFactory() const { return m_factory; } /// @brief sets the factory for an entity and entity list /// @param f the factory - void setFactory(FactoryPtr &f) { m_factory = f; } + void setFactory(FactoryPtr& f) { m_factory = f; } /// @brief set the multiplicity /// @param lower the upper multiplicity /// @param upper the lower multiplicity @@ -318,13 +318,13 @@ namespace mtconnect::entity { /// @param v the value /// @param table if this is a table conversion /// @return `true` if it is successful - bool convertType(Value &v, bool table = false) const + bool convertType(Value& v, bool table = false) const { try { return ConvertValueToType(v, m_type, table); } - catch (PropertyError &e) + catch (PropertyError& e) { e.setProperty(m_name); throw; @@ -337,11 +337,11 @@ namespace mtconnect::entity { /// @brief does a value meet the requirement /// @param value the value /// @return `true` if the requirement is met - bool isMetBy(const Value &value) const; + bool isMetBy(const Value& value) const; /// @brief checks if a string matches the requirement /// @param s the string to check /// @return `true` if it matches - bool matches(const std::string &s) const + bool matches(const std::string& s) const { if (auto m = m_matcher.lock()) { diff --git a/src/mtconnect/entity/xml_parser.cpp b/src/mtconnect/entity/xml_parser.cpp index ab8a32b3..d3f2affd 100644 --- a/src/mtconnect/entity/xml_parser.cpp +++ b/src/mtconnect/entity/xml_parser.cpp @@ -32,7 +32,7 @@ using namespace std; namespace mtconnect::entity { using namespace mtconnect::printer; - extern "C" void XMLCDECL entityXMLErrorFunc([[maybe_unused]] void *ctx, const char *msg, ...) + extern "C" void XMLCDECL entityXMLErrorFunc([[maybe_unused]] void* ctx, const char* msg, ...) { va_list args; @@ -47,18 +47,18 @@ namespace mtconnect::entity { inline entity::QName nodeQName(xmlNodePtr node) { - entity::QName qname((const char *)node->name); + entity::QName qname((const char*)node->name); if (node->ns && node->ns->prefix && - strncmp((const char *)node->ns->href, "urn:mtconnect.org:MTConnectDevices", 34u)) + strncmp((const char*)node->ns->href, "urn:mtconnect.org:MTConnectDevices", 34u)) { - qname.setNs((const char *)node->ns->prefix); + qname.setNs((const char*)node->ns->prefix); } return qname; } - inline void trim(string &s) + inline void trim(string& s) { auto beg = s.find_first_not_of(" \t\n"); if (beg > 0) @@ -81,7 +81,7 @@ namespace mtconnect::entity { auto count = xmlNodeDump(buf, child->doc, child, 0, 0); if (count > 0) { - str << (const char *)buf->content; + str << (const char*)buf->content; } xmlBufferFree(buf); } @@ -92,14 +92,14 @@ namespace mtconnect::entity { } template - static inline bool isType(const string &str, const P &parser, A &value) + static inline bool isType(const string& str, const P& parser, A& value) { std::string::const_iterator first(str.cbegin()), last(str.cend()); return boost::spirit::qi::parse(first, last, parser, value) && first == last; } template - static void parseDataSet(xmlNodePtr node, ST &dataSet, bool table, bool cell = false) + static void parseDataSet(xmlNodePtr node, ST& dataSet, bool table, bool cell = false) { for (xmlNodePtr child = node->children; child; child = child->next) { @@ -113,13 +113,13 @@ namespace mtconnect::entity { { if (attr->type == XML_ATTRIBUTE_NODE) { - string name((const char *)attr->name); + string name((const char*)attr->name); if (name != "key") { throw EntityError("parseDataSet: Expecting ksy for data set Entry: " + - string((const char *)node->name)); + string((const char*)node->name)); } - key = string((const char *)attr->children->content); + key = string((const char*)attr->children->content); break; } } @@ -132,13 +132,13 @@ namespace mtconnect::entity { { if constexpr (std::is_same_v) { - TableRow &row = value.template emplace(); + TableRow& row = value.template emplace(); parseDataSet(child, row, true, true); } } else if (valueNode->type == XML_TEXT_NODE) { - string text = ((const char *)valueNode->content); + string text = ((const char*)valueNode->content); trim(text); if (int64_t v; isType(text, boost::spirit::long_long, v)) @@ -164,12 +164,12 @@ namespace mtconnect::entity { else { throw EntityError("parseDataSet: Expecting Entry for data set: " + - string((const char *)node->name)); + string((const char*)node->name)); } } } - EntityPtr XmlParser::parseXmlNode(FactoryPtr factory, xmlNodePtr node, ErrorList &errors, + EntityPtr XmlParser::parseXmlNode(FactoryPtr factory, xmlNodePtr node, ErrorList& errors, bool parseNamespaces) { auto qname = nodeQName(node); @@ -184,7 +184,7 @@ namespace mtconnect::entity { } Properties properties; - EntityList *l {nullptr}; + EntityList* l {nullptr}; if (ef->isList()) { l = &properties["LIST"].emplace(); @@ -194,10 +194,10 @@ namespace mtconnect::entity { { if (attr->type == XML_ATTRIBUTE_NODE) { - entity::QName qname((const char *)attr->name); + entity::QName qname((const char*)attr->name); if (attr->ns) - qname.setNs((const char *)attr->ns->prefix); - properties.insert({qname, string((const char *)attr->children->content)}); + qname.setNs((const char*)attr->ns->prefix); + properties.insert({qname, string((const char*)attr->children->content)}); if (!islower(qname.getName()[0])) { attrs.emplace(qname); @@ -211,11 +211,11 @@ namespace mtconnect::entity { { string name; if (def->prefix) - name = {string("xmlns:") + (const char *)def->prefix}; + name = {string("xmlns:") + (const char*)def->prefix}; else name = "xmlns"; - properties.insert({name, string((const char *)def->href)}); + properties.insert({name, string((const char*)def->href)}); } } @@ -260,7 +260,7 @@ namespace mtconnect::entity { { if (child->children != nullptr && child->children->content != nullptr) { - string s((const char *)child->children->content); + string s((const char*)child->children->content); trim(s); if (!s.empty()) properties.insert({nodeQName(child), s}); @@ -295,7 +295,7 @@ namespace mtconnect::entity { } else if (child->type == XML_TEXT_NODE) { - string s((const char *)child->content); + string s((const char*)child->content); trim(s); if (!s.empty()) properties.insert({"VALUE", s}); @@ -320,7 +320,7 @@ namespace mtconnect::entity { } return entity; } - catch (EntityError &e) + catch (EntityError& e) { e.setEntity(qname); errors.emplace_back(e.dup()); @@ -330,7 +330,7 @@ namespace mtconnect::entity { return nullptr; } - EntityPtr XmlParser::parse(FactoryPtr factory, const string &document, ErrorList &errors, + EntityPtr XmlParser::parse(FactoryPtr factory, const string& document, ErrorList& errors, bool parseNamespaces) { NAMED_SCOPE("entity.xml_parser"); @@ -351,14 +351,14 @@ namespace mtconnect::entity { errors.emplace_back(new EntityError("Cannot parse document")); } - catch (const EntityError &e) + catch (const EntityError& e) { LOG(error) << "Cannot parse XML document: " << e.what(); errors.emplace_back(e.dup()); entity.reset(); } - catch (const XmlError &e) + catch (const XmlError& e) { LOG(error) << "Cannot parse XML document: " << e.what(); errors.emplace_back(new EntityError(e.what())); diff --git a/src/mtconnect/entity/xml_parser.hpp b/src/mtconnect/entity/xml_parser.hpp index 29d6decd..8e4f81ac 100644 --- a/src/mtconnect/entity/xml_parser.hpp +++ b/src/mtconnect/entity/xml_parser.hpp @@ -36,7 +36,7 @@ namespace mtconnect { public: XmlParser() = default; ~XmlParser() = default; - using xmlNodePtr = _xmlNode *; + using xmlNodePtr = _xmlNode*; /// @brief Parse an xmlNodePointer (libxml2) to an entity /// @param factory The factory to use to create the top level entity @@ -44,7 +44,7 @@ namespace mtconnect { /// @param errors errors that occurred during the parsing /// @param parseNamespaces `true` if namespaces should be parsed /// @return a shared pointer to an entity if successful - static EntityPtr parseXmlNode(FactoryPtr factory, xmlNodePtr node, ErrorList &errors, + static EntityPtr parseXmlNode(FactoryPtr factory, xmlNodePtr node, ErrorList& errors, bool parseNamespaces = true); /// @brief Parse a string document to an entity /// @param factory The factory to use to create the top level entity @@ -52,7 +52,7 @@ namespace mtconnect { /// @param errors errors that occurred during the parsing /// @param parseNamespaces `true` if namespaces should be parsed /// @return a shared pointer to an entity if successful - static EntityPtr parse(FactoryPtr factory, const std::string &document, ErrorList &errors, + static EntityPtr parse(FactoryPtr factory, const std::string& document, ErrorList& errors, bool parseNamespaces = true); }; } // namespace entity diff --git a/src/mtconnect/entity/xml_printer.cpp b/src/mtconnect/entity/xml_printer.cpp index 922ea3c5..1934a535 100644 --- a/src/mtconnect/entity/xml_printer.cpp +++ b/src/mtconnect/entity/xml_printer.cpp @@ -30,8 +30,8 @@ using namespace std; namespace mtconnect { using namespace printer; namespace entity { - inline string stripUndeclaredNamespace(const QName &qname, - const unordered_set &namespaces) + inline string stripUndeclaredNamespace(const QName& qname, + const unordered_set& namespaces) { string name; if (qname.hasNs() && namespaces.count(string(qname.getNs())) == 0) @@ -42,7 +42,7 @@ namespace mtconnect { return name; } - void printDataSet(xmlTextWriterPtr writer, const std::string &name, const DataSet &set) + void printDataSet(xmlTextWriterPtr writer, const std::string& name, const DataSet& set) { AutoElement ele(writer); if (name != "VALUE") @@ -50,30 +50,30 @@ namespace mtconnect { ele.reset(name); } - for (auto &e : set) + for (auto& e : set) { map attrs = {{"key", e.m_key}}; if (e.m_removed) { attrs["removed"] = "true"; } - visit(overloaded {[&writer, &attrs](const monostate &st) { + visit(overloaded {[&writer, &attrs](const monostate& st) { addSimpleElement(writer, "Entry", "", attrs); }, - [&writer, &attrs](const string &st) { + [&writer, &attrs](const string& st) { addSimpleElement(writer, "Entry", st, attrs); }, - [&writer, &attrs](const int64_t &i) { + [&writer, &attrs](const int64_t& i) { addSimpleElement(writer, "Entry", to_string(i), attrs); }, - [&writer, &attrs](const double &d) { + [&writer, &attrs](const double& d) { addSimpleElement(writer, "Entry", format(d), attrs); }, - [&writer, &attrs](const TableRow &row) { + [&writer, &attrs](const TableRow& row) { // Table AutoElement ele(writer, "Entry"); addAttributes(writer, attrs); - for (auto &c : row) + for (auto& c : row) { map attrs = {{"key", c.m_key}}; if (c.m_removed) @@ -81,16 +81,16 @@ namespace mtconnect { attrs["removed"] = "true"; } visit(overloaded { - [&writer, &attrs](const string &s) { + [&writer, &attrs](const string& s) { addSimpleElement(writer, "Cell", s, attrs); }, - [&writer, &attrs](const int64_t &i) { + [&writer, &attrs](const int64_t& i) { addSimpleElement(writer, "Cell", to_string(i), attrs); }, - [&writer, &attrs](const double &d) { + [&writer, &attrs](const double& d) { addSimpleElement(writer, "Cell", format(d), attrs); }, - [](auto &a) { + [](auto& a) { LOG(error) << "Invalid type for DataSetVariant cell"; }}, c.m_value); @@ -100,9 +100,9 @@ namespace mtconnect { } } - const char *toCharPtr(const Value &value, string &temp) + const char* toCharPtr(const Value& value, string& temp) { - const string *s; + const string* s; if (!holds_alternative(value)) { Value conv = value; @@ -118,11 +118,11 @@ namespace mtconnect { return s->c_str(); } - void printProperty(xmlTextWriterPtr writer, const Property &p, - const unordered_set &namespaces) + void printProperty(xmlTextWriterPtr writer, const Property& p, + const unordered_set& namespaces) { string t; - const char *s = toCharPtr(p.second, t); + const char* s = toCharPtr(p.second, t); if (p.first == "VALUE") { // The value is the content for a simple element @@ -145,12 +145,12 @@ namespace mtconnect { } void XmlPrinter::print(xmlTextWriterPtr writer, const EntityPtr entity, - const std::unordered_set &namespaces) + const std::unordered_set& namespaces) { NAMED_SCOPE("entity.xml_printer"); - const auto &properties = entity->getProperties(); + const auto& properties = entity->getProperties(); const auto order = entity->getOrder(); - const auto *localNamespaces = &namespaces; + const auto* localNamespaces = &namespaces; // If this element has a namespace and there is a xmlns delcaration, create a new set of // namespaces with this one added @@ -177,10 +177,10 @@ namespace mtconnect { list elements; // Partition the properties - const auto &attrs = entity->getAttributes(); - for (const auto &prop : properties) + const auto& attrs = entity->getAttributes(); + for (const auto& prop : properties) { - auto &key = prop.first; + auto& key = prop.first; if (m_includeHidden || !entity->isHidden(key)) { if (islower(key.getName()[0]) || attrs.count(key) > 0) @@ -195,7 +195,7 @@ namespace mtconnect { { // Sort all ordered elements first based on the order in the // ordering list - elements.sort([&order](auto &e1, auto &e2) -> bool { + elements.sort([&order](auto& e1, auto& e2) -> bool { auto it1 = order->find(e1.first); if (it1 == order->end()) return false; @@ -206,7 +206,7 @@ namespace mtconnect { }); } - for (auto &a : attributes) + for (auto& a : attributes) { string t; QName name(a.first); @@ -218,17 +218,17 @@ namespace mtconnect { } } - for (auto &e : elements) + for (auto& e : elements) { - visit(overloaded {[&writer, localNamespaces, this](const EntityPtr &v) { + visit(overloaded {[&writer, localNamespaces, this](const EntityPtr& v) { print(writer, v, *localNamespaces); }, - [&writer, localNamespaces, this](const EntityList &list) { - for (auto &en : list) + [&writer, localNamespaces, this](const EntityList& list) { + for (auto& en : list) print(writer, en, *localNamespaces); }, - [&writer, &e](const DataSet &v) { printDataSet(writer, e.first, v); }, - [&writer, &e, localNamespaces](const auto &v) { + [&writer, &e](const DataSet& v) { printDataSet(writer, e.first, v); }, + [&writer, &e, localNamespaces](const auto& v) { printProperty(writer, e, *localNamespaces); }}, e.second); diff --git a/src/mtconnect/entity/xml_printer.hpp b/src/mtconnect/entity/xml_printer.hpp index 906b3f1a..046427b3 100644 --- a/src/mtconnect/entity/xml_printer.hpp +++ b/src/mtconnect/entity/xml_printer.hpp @@ -25,7 +25,7 @@ extern "C" { using xmlTextWriter = struct _xmlTextWriter; - using xmlTextWriterPtr = xmlTextWriter *; + using xmlTextWriterPtr = xmlTextWriter*; } namespace mtconnect { @@ -41,7 +41,7 @@ namespace mtconnect { /// @param entity the entity /// @param namespaces a set of namespaces to use in the document void print(xmlTextWriterPtr writer, const EntityPtr entity, - const std::unordered_set &namespaces); + const std::unordered_set& namespaces); protected: bool m_includeHidden {false}; diff --git a/src/mtconnect/mqtt/mqtt_client.hpp b/src/mtconnect/mqtt/mqtt_client.hpp index cf6825d1..476ac71d 100644 --- a/src/mtconnect/mqtt/mqtt_client.hpp +++ b/src/mtconnect/mqtt/mqtt_client.hpp @@ -30,8 +30,8 @@ namespace mtconnect { struct ClientHandler { using Connect = std::function)>; - using Received = std::function, const std::string &topic, - const std::string &payload)>; + using Received = std::function, const std::string& topic, + const std::string& payload)>; Connect m_connected; Connect m_connecting; @@ -54,7 +54,7 @@ namespace mtconnect { /// @param ClientHandler configuration options /// - ConnectInterval, defaults to 5000 - MqttClient(boost::asio::io_context &ioc, std::unique_ptr &&handler, + MqttClient(boost::asio::io_context& ioc, std::unique_ptr&& handler, const std::optional willTopic = std::nullopt, const std::optional willPayload = std::nullopt) : m_ioContext(ioc), @@ -67,11 +67,11 @@ namespace mtconnect { /// @brief get the clientId /// @return the clientId - const auto &getIdentity() const { return m_identity; } + const auto& getIdentity() const { return m_identity; } /// @brief get the Url link mqtt://localhost:1883 /// @return the Url to access localhost - const auto &getUrl() const { return m_url; } + const auto& getUrl() const { return m_url; } /// @brief Start the Mqtt Client virtual bool start() = 0; @@ -82,20 +82,20 @@ namespace mtconnect { /// @brief Subscribe Topic to the Mqtt Client /// @param topic Subscribing to the topic /// @return boolean either topic sucessfully connected and subscribed - virtual bool subscribe(const std::string &topic) = 0; + virtual bool subscribe(const std::string& topic) = 0; /// @brief Publish Topic to the Mqtt Client /// @param topic Publishing to the topic /// @param payload Publishing to the payload /// @return boolean either topic sucessfully connected and published - virtual bool publish(const std::string &topic, const std::string &payload, bool retain = true, + virtual bool publish(const std::string& topic, const std::string& payload, bool retain = true, QOS qos = QOS::at_least_once) = 0; /// @brief Publish Topic to the Mqtt Client and call the async handler /// @param topic Publishing to the topic /// @param payload Publishing to the payload /// @return boolean either topic sucessfully connected and published - virtual bool asyncPublish(const std::string &topic, const std::string &payload, + virtual bool asyncPublish(const std::string& topic, const std::string& payload, std::function callback, bool retain = true, QOS qos = QOS::at_least_once) = 0; @@ -111,7 +111,7 @@ namespace mtconnect { void connectComplete() { m_connected = true; } protected: - boost::asio::io_context &m_ioContext; + boost::asio::io_context& m_ioContext; std::string m_url; std::string m_identity; std::unique_ptr m_handler; diff --git a/src/mtconnect/mqtt/mqtt_client_impl.hpp b/src/mtconnect/mqtt/mqtt_client_impl.hpp index 31b7b006..d7d0a4d5 100644 --- a/src/mtconnect/mqtt/mqtt_client_impl.hpp +++ b/src/mtconnect/mqtt/mqtt_client_impl.hpp @@ -52,14 +52,14 @@ namespace mtconnect { template using mqtt_tls_client_ws_ptr = decltype(mqtt::make_tls_async_client_ws(std::declval()...)); - using mqtt_client = mqtt_client_ptr; - using mqtt_tls_client = mqtt_tls_client_ptr; using mqtt_tls_client_ws = - mqtt_tls_client_ws_ptr; - using mqtt_client_ws = mqtt_client_ws_ptr; /// @brief The Mqtt Client Source @@ -73,8 +73,8 @@ namespace mtconnect { /// - Port, defaults to 1883 /// - MqttTls, defaults to false /// - MqttHost, defaults to LocalHost - MqttClientImpl(boost::asio::io_context &ioContext, const ConfigOptions &options, - std::unique_ptr &&handler, + MqttClientImpl(boost::asio::io_context& ioContext, const ConfigOptions& options, + std::unique_ptr&& handler, const std::optional willTopic = std::nullopt, const std::optional willPayload = std::nullopt) : MqttClient(ioContext, std::move(handler), willTopic, willPayload), @@ -118,7 +118,7 @@ namespace mtconnect { ~MqttClientImpl() { stop(); } - Derived &derived() { return static_cast(*this); } + Derived& derived() { return static_cast(*this); } /// @brief Start the Mqtt Client bool start() override @@ -247,7 +247,7 @@ namespace mtconnect { /// @brief Subscribe Topic to the Mqtt Client /// @param topic Subscribing to the topic /// @return boolean either topic sucessfully connected and subscribed - bool subscribe(const std::string &topic) override + bool subscribe(const std::string& topic) override { NAMED_SCOPE("MqttClientImpl::subscribe"); if (!m_connected) @@ -279,7 +279,7 @@ namespace mtconnect { /// @param topic Publishing to the topic /// @param payload Publishing to the payload /// @return boolean either topic sucessfully connected and published - bool publish(const std::string &topic, const std::string &payload, bool retain = true, + bool publish(const std::string& topic, const std::string& payload, bool retain = true, QOS qos = QOS::at_least_once) override { NAMED_SCOPE("MqttClientImpl::publish"); @@ -328,7 +328,7 @@ namespace mtconnect { /// @param topic Publishing to the topic /// @param payload Publishing to the payload /// @return boolean either topic sucessfully connected and published - bool asyncPublish(const std::string &topic, const std::string &payload, + bool asyncPublish(const std::string& topic, const std::string& payload, std::function callback, bool retain = true, QOS qos = QOS::at_least_once) override { @@ -397,7 +397,7 @@ namespace mtconnect { }); } - void receive(mqtt::buffer &topic, mqtt::buffer &contents) + void receive(mqtt::buffer& topic, mqtt::buffer& contents) { if (m_handler && m_handler->m_receive) m_handler->m_receive(shared_from_this(), string(topic), string(contents)); @@ -432,7 +432,7 @@ namespace mtconnect { m_reconnectTimer.expires_after(m_connectInterval); m_reconnectTimer.async_wait(boost::asio::bind_executor( - derived().getClient()->get_executor(), [this](const boost::system::error_code &error) { + derived().getClient()->get_executor(), [this](const boost::system::error_code& error) { if (error != boost::asio::error::operation_aborted) { LOG(info) << "MqttClientImpl::reconnect: reconnect now"; @@ -479,7 +479,7 @@ namespace mtconnect { /// @brief Get the Mqtt TCP Client /// @return pointer to the Mqtt TCP Client - auto &getClient() + auto& getClient() { if (!m_client) { @@ -512,7 +512,7 @@ namespace mtconnect { /// @brief Get the Mqtt TLS Client /// @return pointer to the Mqtt TLS Client - auto &getClient() + auto& getClient() { if (!m_client) { @@ -561,7 +561,7 @@ namespace mtconnect { /// @brief Get the Mqtt TLS WebSocket Client /// @return pointer to the Mqtt TLS WebSocket Client - auto &getClient() + auto& getClient() { if (!m_client) { @@ -600,7 +600,7 @@ namespace mtconnect { /// @brief Get the Mqtt TLS WebSocket Client /// @return pointer to the Mqtt TLS WebSocket Client - auto &getClient() + auto& getClient() { if (!m_client) { diff --git a/src/mtconnect/mqtt/mqtt_server.hpp b/src/mtconnect/mqtt/mqtt_server.hpp index 745f872e..dc7e638d 100644 --- a/src/mtconnect/mqtt/mqtt_server.hpp +++ b/src/mtconnect/mqtt/mqtt_server.hpp @@ -26,13 +26,13 @@ namespace mtconnect { public: /// @brief Create an Mqtt server with an asio context /// @param ioc a boost asio context - MqttServer(boost::asio::io_context &ioc) : m_ioContext(ioc), m_port(1883) {} + MqttServer(boost::asio::io_context& ioc) : m_ioContext(ioc), m_port(1883) {} virtual ~MqttServer() = default; /// @brief Get the Mqtt url /// @return Mqtt url - const auto &getUrl() const { return m_url; } + const auto& getUrl() const { return m_url; } /// @brief get the bind port /// @return the port being bound @@ -44,10 +44,10 @@ namespace mtconnect { /// @brief Shutdown the Mqtt server virtual void stop() = 0; - auto &getWill() { return m_will; } + auto& getWill() { return m_will; } protected: - boost::asio::io_context &m_ioContext; + boost::asio::io_context& m_ioContext; std::string m_url; uint16_t m_port; std::optional m_will; diff --git a/src/mtconnect/mqtt/mqtt_server_impl.hpp b/src/mtconnect/mqtt/mqtt_server_impl.hpp index bc6a66fc..63f44fbe 100644 --- a/src/mtconnect/mqtt/mqtt_server_impl.hpp +++ b/src/mtconnect/mqtt/mqtt_server_impl.hpp @@ -84,7 +84,7 @@ namespace mtconnect { /// - Port, defaults to 0/1883 /// - MqttTls, defaults to false /// - ServerIp, defaults to 127.0.0.1/LocalHost - MqttServerImpl(boost::asio::io_context &ioContext, const ConfigOptions &options) + MqttServerImpl(boost::asio::io_context& ioContext, const ConfigOptions& options) : MqttServer(ioContext), m_options(options), m_host(*GetOption(options, configuration::ServerIp)) @@ -96,7 +96,7 @@ namespace mtconnect { ~MqttServerImpl() { stop(); } - Derived &derived() { return static_cast(*this); } + Derived& derived() { return static_cast(*this); } /// @brief Start the Mqtt server @@ -104,10 +104,10 @@ namespace mtconnect { { NAMED_SCOPE("MqttServer::start"); - auto &server = derived().createServer(); + auto& server = derived().createServer(); server.set_accept_handler([&server, this](con_sp_t spep) { - auto &ep = *spep; + auto& ep = *spep; std::weak_ptr wp = spep; using packet_id_t = typename std::remove_reference_t::packet_id_t; LOG(info) << "Server: Accepted" << std::endl; @@ -156,7 +156,7 @@ namespace mtconnect { return false; } m_connections.erase(con); - auto &idx = m_subs.get(); + auto& idx = m_subs.get(); auto r = idx.equal_range(con); idx.erase(r.first, r.second); @@ -172,7 +172,7 @@ namespace mtconnect { return false; } m_connections.erase(con); - auto &idx = m_subs.get(); + auto& idx = m_subs.get(); auto r = idx.equal_range(con); idx.erase(r.first, r.second); @@ -191,7 +191,7 @@ namespace mtconnect { LOG(error) << "Server Endpoint has been deleted"; return false; } - for (auto const &e : entries) + for (auto const& e : entries) { LOG(debug) << "Server: topic_filter: " << e.topic_filter << " qos: " << e.subopts.get_qos() << std::endl; @@ -215,7 +215,7 @@ namespace mtconnect { LOG(debug) << "Server topic_name: " << topic_name; LOG(debug) << "Server contents: " << contents; - for (const auto &sub : m_subs) + for (const auto& sub : m_subs) { if (mqtt::broker::compare_topic_filter(sub.topic, topic_name)) { @@ -238,7 +238,7 @@ namespace mtconnect { /// @brief Stop the Mqtt server void stop() override { - auto &server = derived().getServer(); + auto& server = derived().getServer(); auto url = m_url; if (server) @@ -271,7 +271,7 @@ namespace mtconnect { /// - Port, defaults to 0/1883 /// - MqttTls, defaults to false /// - ServerIp, defaults to 127.0.0.1/LocalHost - MqttTcpServer(boost::asio::io_context &ioContext, const ConfigOptions &options) + MqttTcpServer(boost::asio::io_context& ioContext, const ConfigOptions& options) : base(ioContext, options) { m_port = GetOption(options, configuration::MqttPort).value_or(1883); @@ -279,9 +279,9 @@ namespace mtconnect { /// @brief Get the Mqtt TCP Server /// @return pointer to the Mqtt TCP Server - auto &getServer() { return m_server; } + auto& getServer() { return m_server; } - auto &createServer() + auto& createServer() { if (!m_server) { @@ -308,7 +308,7 @@ namespace mtconnect { /// - Port, defaults to 0/1883 /// - MqttTls, defaults to True /// - ServerIp, defaults to 127.0.0.1/LocalHost - MqttTlsServer(boost::asio::io_context &ioContext, const ConfigOptions &options) + MqttTlsServer(boost::asio::io_context& ioContext, const ConfigOptions& options) : base(ioContext, options) { m_port = GetOption(options, configuration::Port).value_or(8883); @@ -319,9 +319,9 @@ namespace mtconnect { /// @brief Get the Mqtt TLS Server /// @return pointer to the Mqtt TLS Server - auto &getServer() { return m_server; } + auto& getServer() { return m_server; } - auto &createServer() + auto& createServer() { if (!m_server) { @@ -338,7 +338,8 @@ namespace mtconnect { { ctx.set_password_callback( [this](size_t, boost::asio::ssl::context_base::password_purpose) -> std::string { - return *GetOption(m_options, configuration::TlsCertificatePassword); + return *GetOption(m_options, + configuration::TlsCertificatePassword); }); } @@ -358,7 +359,8 @@ namespace mtconnect { if (HasOption(m_options, configuration::TlsClientCAs)) { LOG(info) << "Server: Adding Client Certificates."; - ctx.load_verify_file(*GetOption(m_options, configuration::TlsClientCAs)); + ctx.load_verify_file( + *GetOption(m_options, configuration::TlsClientCAs)); } } } @@ -385,7 +387,7 @@ namespace mtconnect { /// - Port, defaults to 0/1883 /// - MqttTls, defaults to True /// - ServerIp, defaults to 127.0.0.1/LocalHost - MqttTlsWSServer(boost::asio::io_context &ioContext, const ConfigOptions &options) + MqttTlsWSServer(boost::asio::io_context& ioContext, const ConfigOptions& options) : base(ioContext, options) { m_port = GetOption(options, configuration::Port).value_or(8883); @@ -396,9 +398,9 @@ namespace mtconnect { /// @brief Get the Mqtt TLS WebSocket Server /// @return pointer to the Mqtt TLS WebSocket Server - auto &getServer() { return m_server; } + auto& getServer() { return m_server; } - auto &createServer() + auto& createServer() { if (!m_server) { diff --git a/src/mtconnect/observation/change_observer.cpp b/src/mtconnect/observation/change_observer.cpp index 6ee9e2f7..93c42736 100644 --- a/src/mtconnect/observation/change_observer.cpp +++ b/src/mtconnect/observation/change_observer.cpp @@ -22,7 +22,7 @@ using namespace std; namespace mtconnect::observation { - void AsyncObserver::observe(const std::optional &from, Resolver resolver) + void AsyncObserver::observe(const std::optional& from, Resolver resolver) { using std::placeholders::_1; @@ -39,7 +39,7 @@ namespace mtconnect::observation { // This object will automatically clean up all the observer from the // signalers in an exception proof manor. // Add observers - for (const auto &item : m_filter) + for (const auto& item : m_filter) { auto cs = resolver(item); if (cs) diff --git a/src/mtconnect/observation/change_observer.hpp b/src/mtconnect/observation/change_observer.hpp index 4eaec484..d9991826 100644 --- a/src/mtconnect/observation/change_observer.hpp +++ b/src/mtconnect/observation/change_observer.hpp @@ -44,7 +44,7 @@ namespace mtconnect::observation { public: /// @brief Create a change observer that runs in a strand /// @param[in] strand the strand - ChangeObserver(boost::asio::io_context::strand &strand) + ChangeObserver(boost::asio::io_context::strand& strand) : m_strand(strand), m_timer(strand.context()) {} @@ -154,22 +154,22 @@ namespace mtconnect::observation { void clear(); private: - boost::asio::io_context::strand &m_strand; + boost::asio::io_context::strand& m_strand; mutable std::recursive_mutex m_mutex; boost::asio::steady_timer m_timer; - std::vector m_signalers; + std::vector m_signalers; std::atomic m_sequence {UINT64_MAX}; bool m_noCancelOnSignal {false}; protected: friend class ChangeSignaler; - void addSignaler(ChangeSignaler *sig) + void addSignaler(ChangeSignaler* sig) { std::unique_lock lock(m_mutex); m_signalers.emplace_back(sig); } - bool removeSignaler(ChangeSignaler *sig) + bool removeSignaler(ChangeSignaler* sig) { std::lock_guard lock(m_mutex); return std::erase(m_signalers, sig) > 0; @@ -182,7 +182,7 @@ namespace mtconnect::observation { public: /// @brief add an observer to the list /// @param[in] observer an observer - void addObserver(ChangeObserver *observer) + void addObserver(ChangeObserver* observer) { std::lock_guard lock(m_observerMutex); m_observers.emplace_back(observer); @@ -191,7 +191,7 @@ namespace mtconnect::observation { /// @brief remove an observer /// @param[in] observer an observer /// @return `true` if the observer was removed - bool removeObserver(ChangeObserver *observer) + bool removeObserver(ChangeObserver* observer) { std::lock_guard lock(m_observerMutex); std::erase(m_observers, observer); @@ -200,7 +200,7 @@ namespace mtconnect::observation { /// @brief check if an observer is in the list /// @param[in] observer an observer /// @return `true` if the observer is in the list - bool hasObserver(ChangeObserver *observer) const + bool hasObserver(ChangeObserver* observer) const { std::lock_guard lock(m_observerMutex); auto foundPos = std::find(m_observers.begin(), m_observers.end(), observer); @@ -225,7 +225,7 @@ namespace mtconnect::observation { protected: // Observer Lists mutable std::recursive_mutex m_observerMutex; - std::vector m_observers; + std::vector m_observers; }; // -- Deferred ChangeObserver method definitions (need complete ChangeSignaler) -- @@ -263,13 +263,13 @@ namespace mtconnect::observation { virtual bool isRunning() = 0; /// @brief get the request id for webservices - const auto &getRequestId() const { return m_requestId; } + const auto& getRequestId() const { return m_requestId; } /// @brief sets the optional request id for webservices. - void setRequestId(const std::optional &id) { m_requestId = id; } + void setRequestId(const std::optional& id) { m_requestId = id; } /// @brief Get the interval - const auto &getInterval() const { return m_interval; } + const auto& getInterval() const { return m_interval; } protected: std::chrono::milliseconds m_interval { @@ -295,7 +295,7 @@ namespace mtconnect::observation { using Handler = std::function)>; /// @brief Resolve a string to a change signaler - using Resolver = std::function; + using Resolver = std::function; /// @brief create async observer to manage data item callbacks /// @param strand the strand to handle the async actions @@ -303,8 +303,8 @@ namespace mtconnect::observation { /// @param filter the data items to observe /// @param interval minimum amount of time to wait for observations /// @param heartbeat maximum amount of time to wait before sending a heartbeat - AsyncObserver(boost::asio::io_context::strand &strand, - mtconnect::buffer::CircularBuffer &buffer, FilterSet &&filter, + AsyncObserver(boost::asio::io_context::strand& strand, + mtconnect::buffer::CircularBuffer& buffer, FilterSet&& filter, std::chrono::milliseconds interval, std::chrono::milliseconds heartbeat) : AsyncResponse(interval), m_heartbeat(heartbeat), @@ -326,7 +326,7 @@ namespace mtconnect::observation { /// @param from optional starting point. If not specified, defaults to the beginning of the /// buffer /// @param resolver resolve an id to a signaler - void observe(const std::optional &from, Resolver resolver); + void observe(const std::optional& from, Resolver resolver); /// @brief handle the operation completion after the handler is called /// @@ -350,7 +350,7 @@ namespace mtconnect::observation { } /// @brief abstract call to failure handler - virtual void fail(boost::beast::http::status status, const std::string &message) = 0; + virtual void fail(boost::beast::http::status status, const std::string& message) = 0; /// @brief Stop all timers and release resources. bool cancel() override @@ -367,7 +367,7 @@ namespace mtconnect::observation { auto getSequence() const { return m_sequence; } auto isEndOfBuffer() const { return m_endOfBuffer; } - const auto &getFilter() const { return m_filter; } + const auto& getFilter() const { return m_filter; } ///@} mutable bool m_endOfBuffer {false}; //! Public indicator that we are at the end of the buffer @@ -389,6 +389,6 @@ namespace mtconnect::observation { boost::asio::io_context::strand m_strand; //! Strand to use for async dispatch ChangeObserver m_observer; //! the change observer - mtconnect::buffer::CircularBuffer &m_buffer; //! reference to the circular buffer + mtconnect::buffer::CircularBuffer& m_buffer; //! reference to the circular buffer }; } // namespace mtconnect::observation diff --git a/src/mtconnect/observation/observation.cpp b/src/mtconnect/observation/observation.cpp index 5c9fe476..37b16ca5 100644 --- a/src/mtconnect/observation/observation.cpp +++ b/src/mtconnect/observation/observation.cpp @@ -50,7 +50,7 @@ namespace mtconnect { {"compositionId", false}, {"quality", ControlledVocab {"VALID", "INVALID", "UNVERIFIABLE"}, false}, {"deprecated", ValueType::BOOL, false}}), - [](const std::string &name, Properties &props) -> EntityPtr { + [](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); @@ -66,47 +66,47 @@ namespace mtconnect { // regex(".+TimeSeries$") factory->registerFactory( - [](const std::string &name) { return name.ends_with("TimeSeries"); }, + [](const std::string& name) { return name.ends_with("TimeSeries"); }, Timeseries::getFactory()); - factory->registerFactory([](const std::string &name) { return name.ends_with("DataSet"); }, + factory->registerFactory([](const std::string& name) { return name.ends_with("DataSet"); }, DataSetEvent::getFactory()); - factory->registerFactory([](const std::string &name) { return name.ends_with("Table"); }, + factory->registerFactory([](const std::string& name) { return name.ends_with("Table"); }, TableEvent::getFactory()); factory->registerFactory( - [](const std::string &name) { return name.starts_with("Condition:"); }, + [](const std::string& name) { return name.starts_with("Condition:"); }, Condition::getFactory()); factory->registerFactory( - [](const std::string &name) { + [](const std::string& name) { return name.starts_with("Samples:") && name.ends_with(":3D"); }, ThreeSpaceSample::getFactory()); factory->registerFactory( - [](const std::string &name) { + [](const std::string& name) { return name.starts_with("Events:") && name.ends_with(":3D"); }, ThreeSpaceSample::getFactory()); factory->registerFactory( - [](const std::string &name) { return name.starts_with("Samples:"); }, + [](const std::string& name) { return name.starts_with("Samples:"); }, Sample::getFactory()); factory->registerFactory( - [](const std::string &name) { + [](const std::string& name) { return name.starts_with("Events:") && name.ends_with(":DOUBLE"); }, DoubleEvent::getFactory()); factory->registerFactory( - [](const std::string &name) { + [](const std::string& name) { return name.starts_with("Events:") && name.ends_with(":INT"); }, IntEvent::getFactory()); factory->registerFactory( - [](const std::string &name) { return name.starts_with("Events:"); }, + [](const std::string& name) { return name.starts_with("Events:"); }, Event::getFactory()); } return factory; } - ObservationPtr Observation::make(const DataItemPtr dataItem, const Properties &incompingProps, - const Timestamp ×tamp, entity::ErrorList &errors) + ObservationPtr Observation::make(const DataItemPtr dataItem, const Properties& incompingProps, + const Timestamp& timestamp, entity::ErrorList& errors) { NAMED_SCOPE("Observation"); @@ -153,7 +153,7 @@ namespace mtconnect { if (!ent) { LOG(warning) << "Could not parse properties for data item: " << dataItem->getId(); - for (auto &e : errors) + for (auto& e : errors) { LOG(warning) << " Error: " << e->what(); } @@ -181,7 +181,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Observation::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); factory->addRequirements( @@ -197,12 +197,12 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Observation::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { auto ent = make_shared(name, props); auto v = ent->m_properties.find("VALUE"); if (v != ent->m_properties.end()) { - auto &ds = std::get(v->second); + auto& ds = std::get(v->second); ent->m_properties.insert_or_assign("count", int64_t(ds.size())); } return ent; @@ -221,12 +221,12 @@ namespace mtconnect { if (!factory) { factory = make_shared(*DataSetEvent::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { auto ent = make_shared(name, props); auto v = ent->m_properties.find("VALUE"); if (v != ent->m_properties.end()) { - auto &ds = std::get(v->second); + auto& ds = std::get(v->second); ent->m_properties.insert_or_assign("count", int64_t(ds.size())); } return ent; @@ -244,7 +244,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Observation::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); factory->addRequirements(Requirements({{"resetTriggered", ValueType::USTRING, false}, @@ -261,7 +261,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Observation::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); factory->addRequirements(Requirements({{"resetTriggered", ValueType::USTRING, false}, @@ -278,7 +278,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Observation::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); factory->addRequirements(Requirements({{"sampleRate", ValueType::DOUBLE, false}, @@ -296,7 +296,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Sample::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); factory->addRequirements(Requirements({{"VALUE", ValueType::VECTOR, 3, false}})); @@ -310,12 +310,12 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Sample::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { auto ent = make_shared(name, props); auto v = ent->m_properties.find("VALUE"); if (v != ent->m_properties.end()) { - auto &ts = std::get(v->second); + auto& ts = std::get(v->second); ent->m_properties.insert_or_assign("sampleCount", int64_t(ts.size())); } return ent; @@ -333,7 +333,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Observation::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { auto cond = make_shared(name, props); if (cond) { @@ -368,7 +368,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Event::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { auto ent = make_shared(name, props); if (!ent->hasProperty("assetType") && !ent->hasValue()) { @@ -387,7 +387,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Event::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); factory->addRequirements(Requirements {{"hash", false}}); @@ -401,7 +401,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Event::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); factory->addRequirements(Requirements({{"nativeCode", false}})); @@ -415,7 +415,7 @@ namespace mtconnect { if (!factory) { factory = make_shared(*Event::getFactory()); - factory->setFunction([](const std::string &name, Properties &props) -> EntityPtr { + factory->setFunction([](const std::string& name, Properties& props) -> EntityPtr { return make_shared(name, props); }); factory->addRequirements(Requirements({{"code", false}, @@ -426,7 +426,7 @@ namespace mtconnect { return factory; } - bool Condition::replace(ConditionPtr &old, ConditionPtr &_new) + bool Condition::replace(ConditionPtr& old, ConditionPtr& _new) { if (!m_prev) return false; @@ -453,7 +453,7 @@ namespace mtconnect { return n; } - ConditionPtr Condition::deepCopyAndRemove(ConditionPtr &old) + ConditionPtr Condition::deepCopyAndRemove(ConditionPtr& old) { if (this->getptr() == old) { diff --git a/src/mtconnect/observation/observation.hpp b/src/mtconnect/observation/observation.hpp index 456d88c8..899f999f 100644 --- a/src/mtconnect/observation/observation.hpp +++ b/src/mtconnect/observation/observation.hpp @@ -58,15 +58,15 @@ namespace mtconnect::observation { /// @param[in] timestamp the timestamp /// @param[in,out] errors any errors that occurred when creating the observation /// @return shared pointer to the observations - static ObservationPtr make(const DataItemPtr dataItem, const entity::Properties &props, - const Timestamp ×tamp, entity::ErrorList &errors); + static ObservationPtr make(const DataItemPtr dataItem, const entity::Properties& props, + const Timestamp& timestamp, entity::ErrorList& errors); /// @brief utility method to copy the properties from a data item to a set of properties /// @param[in] dataItem the data item /// @param[out] props properties to recieve data item properties - static void setProperties(const DataItemPtr dataItem, entity::Properties &props) + static void setProperties(const DataItemPtr dataItem, entity::Properties& props) { - for (auto &prop : dataItem->getObservationProperties()) + for (auto& prop : dataItem->getObservationProperties()) props.emplace(prop); } @@ -87,7 +87,7 @@ namespace mtconnect::observation { /// @brief update related data item when the device is updated /// @param[in] diMap a map of data item ids to data items - void updateDataItem(std::unordered_map &diMap) + void updateDataItem(std::unordered_map& diMap) { auto old = m_dataItem.lock(); auto ndi = diMap.find(old->getId()); @@ -99,7 +99,7 @@ namespace mtconnect::observation { /// @brief set the timestamp /// @param[in] ts the timestamp - void setTimestamp(const Timestamp &ts) + void setTimestamp(const Timestamp& ts) { m_timestamp = ts; setProperty("timestamp", m_timestamp); @@ -137,7 +137,7 @@ namespace mtconnect::observation { /// compare by the data item and then by sequence number /// @param[in] another the other observation /// @return `true` if this observation is less than `another` - bool operator<(const Observation &another) const + bool operator<(const Observation& another) const { auto di = m_dataItem.lock(); if (!di) @@ -259,7 +259,7 @@ namespace mtconnect::observation { /// @brief set the level as a string /// @param[in] s the level - void setLevel(const std::string &s) + void setLevel(const std::string& s) { if (iequals("normal", s)) setLevel(NORMAL); @@ -330,7 +330,7 @@ namespace mtconnect::observation { /// @brief Get a list of all active conditions /// @param[out] list the list condtions - void getConditionList(ConditionList &list) + void getConditionList(ConditionList& list) { if (m_prev) m_prev->getConditionList(list); @@ -341,7 +341,7 @@ namespace mtconnect::observation { /// @brief find a condition by code in the condition list /// @param[in] code te code /// @return shared pointer to the condition if found - ConditionPtr find(const std::string &code) + ConditionPtr find(const std::string& code) { if (m_code == code) return getptr(); @@ -355,7 +355,7 @@ namespace mtconnect::observation { /// @brief const find a condition by code in the condition list /// @param[in] code te code /// @return shared pointer to the condition if found - const ConditionPtr find(const std::string &code) const + const ConditionPtr find(const std::string& code) const { if (m_code == code) return std::dynamic_pointer_cast(Entity::getptr()); @@ -370,18 +370,18 @@ namespace mtconnect::observation { /// @param[in] old the condition to be placed /// @param[in] _new the replacement condition /// @return `true` if the old condition was found - bool replace(ConditionPtr &old, ConditionPtr &_new); + bool replace(ConditionPtr& old, ConditionPtr& _new); /// @brief copy the condition and all conditions in the list /// @return a new shared condition pointer ConditionPtr deepCopy(); /// @brief copy the condition and all conditions in the list removing one condition /// @param[in] old the condition to skip /// @return the new condition pointer - ConditionPtr deepCopyAndRemove(ConditionPtr &old); + ConditionPtr deepCopyAndRemove(ConditionPtr& old); /// @brief Get the code for the condition /// @return the code - const std::string &getCode() const { return m_code; } + const std::string& getCode() const { return m_code; } /// @brief get the condition level /// @return the level Level getLevel() const { return m_level; } @@ -453,14 +453,14 @@ namespace mtconnect::observation { } /// @brief get the data set value /// @return the value - const entity::DataSet &getDataSet() const + const entity::DataSet& getDataSet() const { - const entity::Value &v = getValue(); + const entity::Value& v = getValue(); return std::get(v); } /// @brief set the data set value and the count /// @param[in] set the data set - void setDataSet(const entity::DataSet &set) + void setDataSet(const entity::DataSet& set) { setValue(set); setProperty("count", int64_t(set.size())); @@ -528,6 +528,6 @@ namespace mtconnect::observation { ObservationPtr copy() const override { return std::make_shared(*this); } }; - using ObservationComparer = bool (*)(ObservationPtr &, ObservationPtr &); - inline bool ObservationCompare(ObservationPtr &aE1, ObservationPtr &aE2) { return *aE1 < *aE2; } + using ObservationComparer = bool (*)(ObservationPtr&, ObservationPtr&); + inline bool ObservationCompare(ObservationPtr& aE1, ObservationPtr& aE2) { return *aE1 < *aE2; } } // namespace mtconnect::observation diff --git a/src/mtconnect/parser/json_parser.cpp b/src/mtconnect/parser/json_parser.cpp index 6c676a6b..4c04aea2 100644 --- a/src/mtconnect/parser/json_parser.cpp +++ b/src/mtconnect/parser/json_parser.cpp @@ -34,7 +34,7 @@ namespace rj = ::rapidjson; namespace mtconnect::parser { using namespace device_model; - list JsonParser::parseFile(const string &filePath) + list JsonParser::parseFile(const string& filePath) { NAMED_SCOPE("json.parser"); @@ -50,7 +50,7 @@ namespace mtconnect::parser { return parseDocument(buffer.str()); } - list JsonParser::parseDocument(const string &jsonDoc) + list JsonParser::parseDocument(const string& jsonDoc) { NAMED_SCOPE("json.parser"); @@ -80,7 +80,7 @@ namespace mtconnect::parser { throw FatalException("JSON document does not contain MTConnectDevices"); } - const auto &mtcDevices = mtcIt->value; + const auto& mtcDevices = mtcIt->value; // Use document jsonVersion if present, otherwise fall back to the default uint32_t version = m_version; @@ -105,7 +105,7 @@ namespace mtconnect::parser { return deviceList; } - const auto &devices = devicesIt->value; + const auto& devices = devicesIt->value; if (version == 1) { @@ -118,7 +118,7 @@ namespace mtconnect::parser { for (rj::SizeType i = 0; i < devices.Size(); ++i) { - const auto &item = devices[i]; + const auto& item = devices[i]; if (item.IsObject() && item.MemberCount() > 0) { // Re-serialize the single device wrapper object for the entity parser @@ -148,7 +148,7 @@ namespace mtconnect::parser { { for (rj::SizeType i = 0; i < deviceArrayIt->value.Size(); ++i) { - const auto &deviceObj = deviceArrayIt->value[i]; + const auto& deviceObj = deviceArrayIt->value[i]; // Wrap as {"Device": {...}} for the entity parser rj::StringBuffer sb; rj::Writer writer(sb); @@ -169,7 +169,7 @@ namespace mtconnect::parser { return deviceList; } - DevicePtr JsonParser::parseDevice(const std::string &jsonDoc, uint32_t version) + DevicePtr JsonParser::parseDevice(const std::string& jsonDoc, uint32_t version) { NAMED_SCOPE("json.parser"); @@ -183,7 +183,7 @@ namespace mtconnect::parser { if (!errors.empty()) { - for (auto &e : errors) + for (auto& e : errors) { LOG(warning) << "Error parsing JSON Device: " << e->what(); } @@ -198,7 +198,7 @@ namespace mtconnect::parser { LOG(error) << "Failed to parse JSON device document"; } } - catch (const exception &e) + catch (const exception& e) { LOG(fatal) << "Cannot parse JSON document: " << e.what(); throw FatalException(e.what()); diff --git a/src/mtconnect/parser/json_parser.hpp b/src/mtconnect/parser/json_parser.hpp index a9c61bf0..2addf82a 100644 --- a/src/mtconnect/parser/json_parser.hpp +++ b/src/mtconnect/parser/json_parser.hpp @@ -39,18 +39,18 @@ namespace mtconnect::parser { /// devices /// @param[in] filePath the path to the JSON file /// @returns a list of device pointers - std::list parseFile(const std::string &filePath); + std::list parseFile(const std::string& filePath); /// @brief Parses a JSON string containing an MTConnectDevices document and returns a list of /// devices. Navigates MTConnectDevices/Devices to find device nodes. /// @param[in] jsonDoc the JSON document string /// @returns a list of device pointers - std::list parseDocument(const std::string &jsonDoc); + std::list parseDocument(const std::string& jsonDoc); /// @brief Parses a JSON string containing a single device and returns the device /// @param[in] jsonDoc the JSON document string wrapping a single Device /// @returns a shared device pointer if successful - device_model::DevicePtr parseDevice(const std::string &jsonDoc) + device_model::DevicePtr parseDevice(const std::string& jsonDoc) { return parseDevice(jsonDoc, m_version); } @@ -59,11 +59,11 @@ namespace mtconnect::parser { /// @param[in] jsonDoc the JSON document string wrapping a single Device /// @param[in] version the JSON serialization version to use /// @returns a shared device pointer if successful - device_model::DevicePtr parseDevice(const std::string &jsonDoc, uint32_t version); + device_model::DevicePtr parseDevice(const std::string& jsonDoc, uint32_t version); /// @brief get the schema version parsed from the document /// @return the version if found - const auto &getSchemaVersion() const { return m_schemaVersion; } + const auto& getSchemaVersion() const { return m_schemaVersion; } protected: uint32_t m_version; diff --git a/src/mtconnect/parser/xml_parser.cpp b/src/mtconnect/parser/xml_parser.cpp index b329f59a..bb2c0b5e 100644 --- a/src/mtconnect/parser/xml_parser.cpp +++ b/src/mtconnect/parser/xml_parser.cpp @@ -62,7 +62,7 @@ namespace mtconnect::parser { using namespace device_model; using namespace printer; - extern "C" void XMLCDECL agentXMLErrorFunc([[maybe_unused]] void *ctx, const char *msg, ...) + extern "C" void XMLCDECL agentXMLErrorFunc([[maybe_unused]] void* ctx, const char* msg, ...) { va_list args; @@ -75,13 +75,13 @@ namespace mtconnect::parser { LOG(error) << "XML: " << buffer; } - static inline std::string getAttribute(xmlNodePtr node, const char *name) + static inline std::string getAttribute(xmlNodePtr node, const char* name) { auto value = xmlGetProp(node, BAD_CAST name); string res; if (value) { - res = (const char *)value; + res = (const char*)value; xmlFree(value); } return res; @@ -89,12 +89,12 @@ namespace mtconnect::parser { XmlParser::XmlParser() { NAMED_SCOPE("xml.parser"); } - inline static bool isMTConnectUrn(const char *aUrn) + inline static bool isMTConnectUrn(const char* aUrn) { return !strncmp(aUrn, "urn:mtconnect.org:MTConnect", 27u); } - std::list XmlParser::parseFile(const std::string &filePath, XmlPrinter *aPrinter) + std::list XmlParser::parseFile(const std::string& filePath, XmlPrinter* aPrinter) { using namespace boost::adaptors; using namespace boost::range; @@ -129,7 +129,7 @@ namespace mtconnect::parser { THROW_IF_XML2_ERROR(xmlXPathRegisterNs(xpathCtx, BAD_CAST "m", root->ns->href)); // Get schema version from Devices.xml - string ns((const char *)root->ns->href); + string ns((const char*)root->ns->href); size_t colon = string::npos; if (ns.find_first_of("urn:mtconnect.org:MTConnectDevices") == 0 && (colon = ns.find_last_of(':')) != string::npos) @@ -159,7 +159,7 @@ namespace mtconnect::parser { string prefix; if (ns && ns->prefix) - prefix = (const char *)ns->prefix; + prefix = (const char*)ns->prefix; aPrinter->addDevicesNamespace(locationUrn, uri, prefix); } @@ -174,12 +174,12 @@ namespace mtconnect::parser { { // Skip the standard namespaces for MTConnect and the w3c. Make sure we don't re-add the // schema location again. - if (!isMTConnectUrn((const char *)ns->href) && - strncmp((const char *)ns->href, "http://www.w3.org/", 18u) != 0 && - locationUrn != (const char *)ns->href && ns->prefix) + if (!isMTConnectUrn((const char*)ns->href) && + strncmp((const char*)ns->href, "http://www.w3.org/", 18u) != 0 && + locationUrn != (const char*)ns->href && ns->prefix) { - string urn = (const char *)ns->href; - string prefix = (const char *)ns->prefix; + string urn = (const char*)ns->href; + string prefix = (const char*)ns->prefix; aPrinter->addDevicesNamespace(urn, "", prefix); } @@ -214,7 +214,7 @@ namespace mtconnect::parser { if (!errors.empty()) { - for (auto &e : errors) + for (auto& e : errors) { if (device) LOG(warning) << "When loading device " << device->get("name") @@ -230,7 +230,7 @@ namespace mtconnect::parser { xmlXPathFreeObject(devices); xmlXPathFreeContext(xpathCtx); } - catch (const string &e) + catch (const string& e) { if (devices) xmlXPathFreeObject(devices); @@ -255,7 +255,7 @@ namespace mtconnect::parser { return deviceList; } - DevicePtr XmlParser::parseDevice(const std::string &deviceXml, printer::XmlPrinter *aPrinter) + DevicePtr XmlParser::parseDevice(const std::string& deviceXml, printer::XmlPrinter* aPrinter) { DevicePtr device; std::unique_lock lock(m_mutex); @@ -306,7 +306,7 @@ namespace mtconnect::parser { entity::ErrorList errors; auto entity = entity::XmlParser::parseXmlNode(Device::getRoot(), deviceNode, errors); - for (auto &e : errors) + for (auto& e : errors) { if (entity) LOG(warning) << "When parsing device, a problem was skipped: " << e->what(); @@ -322,13 +322,13 @@ namespace mtconnect::parser { xmlFreeDoc(doc); doc = nullptr; } - catch (const runtime_error &e) + catch (const runtime_error& e) { if (doc) xmlFreeDoc(doc); LOG(error) << "Cannot parse device XML: " << e.what(); } - catch (const string &e) + catch (const string& e) { if (doc) xmlFreeDoc(doc); @@ -355,7 +355,7 @@ namespace mtconnect::parser { } } - void XmlParser::loadDocument(const std::string &doc) + void XmlParser::loadDocument(const std::string& doc) { std::unique_lock lock(m_mutex); @@ -374,14 +374,14 @@ namespace mtconnect::parser { nullptr, XML_PARSE_NOBLANKS)); } - catch (const string &e) + catch (const string& e) { LOG(fatal) << "Cannot parse XML document: " << e; throw FatalException("Cannot parse XML document: " + e); } } - void XmlParser::getDataItems(FilterSet &filterSet, const string &inputPath, xmlNodePtr node) + void XmlParser::getDataItems(FilterSet& filterSet, const string& inputPath, xmlNodePtr node) { std::shared_lock lock(m_mutex); @@ -406,7 +406,7 @@ namespace mtconnect::parser { { if (ns->prefix) { - if (strncmp((const char *)ns->href, "urn:mtconnect.org:MTConnectDevices", 34u) != 0) + if (strncmp((const char*)ns->href, "urn:mtconnect.org:MTConnectDevices", 34u) != 0) { THROW_IF_XML2_ERROR(xmlXPathRegisterNs(xpathCtx, ns->prefix, ns->href)); } diff --git a/src/mtconnect/parser/xml_parser.hpp b/src/mtconnect/parser/xml_parser.hpp index a9951b74..18bd001a 100644 --- a/src/mtconnect/parser/xml_parser.hpp +++ b/src/mtconnect/parser/xml_parser.hpp @@ -50,26 +50,26 @@ namespace mtconnect::parser { /// @param[in] aPath to the file /// @param[in] aPrinter the printer to obtain and set namespaces /// @returns a list of device pointers - std::list parseFile(const std::string &aPath, - printer::XmlPrinter *aPrinter); + std::list parseFile(const std::string& aPath, + printer::XmlPrinter* aPrinter); /// @brief Parses a single device fragment /// @param[in] deviceXml device xml of a single device /// @param[in] aPrinter the printer to obtain and set namespaces /// @returns a shared device pointer if successful - device_model::DevicePtr parseDevice(const std::string &deviceXml, - printer::XmlPrinter *aPrinter); + device_model::DevicePtr parseDevice(const std::string& deviceXml, + printer::XmlPrinter* aPrinter); /// @brief Just loads the document, assumed it has already been parsed before. /// @param aDoc the XML document to parse - void loadDocument(const std::string &aDoc); + void loadDocument(const std::string& aDoc); /// @brief get data items given a filter set and an xpath /// @param[out] filterSet a filter set to build /// @param[in] path the xpath /// @param[in] node an option node pointer to start from. defaults to the document root. - void getDataItems(FilterSet &filterSet, const std::string &path, xmlNodePtr node = nullptr); + void getDataItems(FilterSet& filterSet, const std::string& path, xmlNodePtr node = nullptr); /// @brief get the schema version /// @return the version - const auto &getSchemaVersion() const { return m_schemaVersion; } + const auto& getSchemaVersion() const { return m_schemaVersion; } protected: // LibXML XML Doc diff --git a/src/mtconnect/pipeline/convert_sample.hpp b/src/mtconnect/pipeline/convert_sample.hpp index c6b1598b..2cc4dc20 100644 --- a/src/mtconnect/pipeline/convert_sample.hpp +++ b/src/mtconnect/pipeline/convert_sample.hpp @@ -32,14 +32,14 @@ namespace mtconnect::pipeline { using namespace observation; m_guard = TypeGuard(RUN) || TypeGuard(SKIP); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { using namespace observation; using namespace entity; auto sample = std::dynamic_pointer_cast(entity); if (sample && !sample->isOrphan() && !sample->isUnavailable()) { - auto &converter = sample->getDataItem()->getConverter(); + auto& converter = sample->getDataItem()->getConverter(); if (converter) converter->convertValue(sample->getValue()); } diff --git a/src/mtconnect/pipeline/correct_timestamp.hpp b/src/mtconnect/pipeline/correct_timestamp.hpp index ebc566d7..3ac2db04 100644 --- a/src/mtconnect/pipeline/correct_timestamp.hpp +++ b/src/mtconnect/pipeline/correct_timestamp.hpp @@ -31,7 +31,7 @@ namespace mtconnect::pipeline { }; public: - CorrectTimestamp(const CorrectTimestamp &) = default; + CorrectTimestamp(const CorrectTimestamp&) = default; /// @brief Create a duplicate filter with shared state from the context /// @param context the context CorrectTimestamp(PipelineContextPtr context) @@ -46,7 +46,7 @@ namespace mtconnect::pipeline { /// @brief check if the entity is a duplicate /// @param[in] entity the entity to check /// @return the result of the transform if not a duplicate or an empty entity - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { using namespace observation; @@ -55,7 +55,7 @@ namespace mtconnect::pipeline { return entity::EntityPtr(); auto di = obs->getDataItem(); - auto &id = di->getId(); + auto& id = di->getId(); auto ts = obs->getTimestamp(); std::lock_guard guard(*m_state); diff --git a/src/mtconnect/pipeline/deliver.cpp b/src/mtconnect/pipeline/deliver.cpp index d4fbc931..4e0e761e 100644 --- a/src/mtconnect/pipeline/deliver.cpp +++ b/src/mtconnect/pipeline/deliver.cpp @@ -35,7 +35,7 @@ namespace mtconnect { using namespace entity; namespace pipeline { - EntityPtr DeliverObservation::operator()(entity::EntityPtr &&entity) + EntityPtr DeliverObservation::operator()(entity::EntityPtr&& entity) { using namespace observation; auto o = std::dynamic_pointer_cast(entity); @@ -100,7 +100,7 @@ namespace mtconnect { double avg = delta + exp(-(dt.count() / 60.0)) * (m_lastAvg - delta); LOG(debug) << *m_dataItem << " - Average for last 1 minutes: " << (avg / dt.count()); LOG(debug) << *m_dataItem - << " - Delta for last 10 seconds: " << (double(delta) / dt.count()); + << " - Delta for last 10 seconds: " << (double(delta) / dt.count()); m_last = count; if (avg != m_lastAvg) @@ -125,7 +125,7 @@ namespace mtconnect { } } - EntityPtr DeliverAsset::operator()(entity::EntityPtr &&entity) + EntityPtr DeliverAsset::operator()(entity::EntityPtr&& entity) { auto a = std::dynamic_pointer_cast(entity); if (!a) @@ -139,7 +139,7 @@ namespace mtconnect { return entity; } - EntityPtr DeliverDevice::operator()(entity::EntityPtr &&entity) + EntityPtr DeliverDevice::operator()(entity::EntityPtr&& entity) { auto d = std::dynamic_pointer_cast(entity); if (!d) @@ -152,11 +152,11 @@ namespace mtconnect { return entity; } - EntityPtr DeliverDevices::operator()(entity::EntityPtr &&entity) + EntityPtr DeliverDevices::operator()(entity::EntityPtr&& entity) { auto entities = entity->getValue(); std::list devices; - for (auto &entity : entities) + for (auto& entity : entities) { auto device = std::dynamic_pointer_cast(entity); if (device) @@ -169,19 +169,19 @@ namespace mtconnect { return entity; } - entity::EntityPtr DeliverConnectionStatus::operator()(entity::EntityPtr &&entity) + entity::EntityPtr DeliverConnectionStatus::operator()(entity::EntityPtr&& entity) { m_contract->deliverConnectStatus(entity, m_devices, m_autoAvailable); return entity; } - entity::EntityPtr DeliverAssetCommand::operator()(entity::EntityPtr &&entity) + entity::EntityPtr DeliverAssetCommand::operator()(entity::EntityPtr&& entity) { m_contract->deliverAssetCommand(entity); return entity; } - entity::EntityPtr DeliverCommand::operator()(entity::EntityPtr &&entity) + entity::EntityPtr DeliverCommand::operator()(entity::EntityPtr&& entity) { if (m_defaultDevice) entity->setProperty("device", *m_defaultDevice); diff --git a/src/mtconnect/pipeline/deliver.hpp b/src/mtconnect/pipeline/deliver.hpp index dd00a807..b26daced 100644 --- a/src/mtconnect/pipeline/deliver.hpp +++ b/src/mtconnect/pipeline/deliver.hpp @@ -37,9 +37,9 @@ namespace mtconnect::pipeline { /// @param contract contract to use /// @param dataItem the data item to post the metrics /// @param count a shared count - ComputeMetrics(boost::asio::io_context::strand &st, PipelineContract *contract, - const std::optional &dataItem, - std::shared_ptr &count) + ComputeMetrics(boost::asio::io_context::strand& st, PipelineContract* contract, + const std::optional& dataItem, + std::shared_ptr& count) : m_count(count), m_contract(contract), m_dataItem(dataItem), @@ -64,11 +64,11 @@ namespace mtconnect::pipeline { void start(); std::shared_ptr m_count; - PipelineContract *m_contract {nullptr}; + PipelineContract* m_contract {nullptr}; std::optional m_dataItem; std::chrono::time_point m_lastTime; - boost::asio::io_context::strand &m_strand; + boost::asio::io_context::strand& m_strand; boost::asio::steady_timer m_timer; bool m_first {true}; bool m_stopped {false}; @@ -84,8 +84,8 @@ namespace mtconnect::pipeline { /// @param name the name of the transform from the subclass /// @param context the pipeline context /// @param metricsDataItem the data item used for an observation when the metrics are updated - MeteredTransform(const std::string &name, PipelineContextPtr context, - const std::optional &metricsDataItem = std::nullopt) + MeteredTransform(const std::string& name, PipelineContextPtr context, + const std::optional& metricsDataItem = std::nullopt) : Transform(name), m_contract(context->m_contract.get()), m_count(std::make_shared(0)), @@ -109,7 +109,7 @@ namespace mtconnect::pipeline { /// @brief start the metrics /// @param st the context to post observations - void start(boost::asio::io_context::strand &st) override + void start(boost::asio::io_context::strand& st) override { if (m_dataItem) { @@ -122,7 +122,7 @@ namespace mtconnect::pipeline { protected: friend struct ComputeMetrics; - PipelineContract *m_contract; + PipelineContract* m_contract; std::shared_ptr m_count; std::shared_ptr m_metrics; std::optional m_dataItem; @@ -134,12 +134,12 @@ namespace mtconnect::pipeline { public: using Deliver = std::function; DeliverObservation(PipelineContextPtr context, - const std::optional &metricDataItem = std::nullopt) + const std::optional& metricDataItem = std::nullopt) : MeteredTransform("DeliverObservation", context, metricDataItem) { m_guard = TypeGuard(RUN); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override; + entity::EntityPtr operator()(entity::EntityPtr&& entity) override; }; /// @brief A transform to deliver and meter asset delivery @@ -148,12 +148,12 @@ namespace mtconnect::pipeline { public: using Deliver = std::function; DeliverAsset(PipelineContextPtr context, - const std::optional &metricsDataItem = std::nullopt) + const std::optional& metricsDataItem = std::nullopt) : MeteredTransform("DeliverAsset", context, metricsDataItem) { m_guard = TypeGuard(RUN); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override; + entity::EntityPtr operator()(entity::EntityPtr&& entity) override; }; /// @brief A transform to deliver a device @@ -166,10 +166,10 @@ namespace mtconnect::pipeline { { m_guard = EntityNameGuard("Devices", RUN); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override; + entity::EntityPtr operator()(entity::EntityPtr&& entity) override; protected: - PipelineContract *m_contract; + PipelineContract* m_contract; }; /// @brief A transform to deliver a device @@ -182,10 +182,10 @@ namespace mtconnect::pipeline { { m_guard = TypeGuard(RUN); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override; + entity::EntityPtr operator()(entity::EntityPtr&& entity) override; protected: - PipelineContract *m_contract; + PipelineContract* m_contract; }; /// @brief deliver the connection status of an adapter @@ -193,7 +193,7 @@ namespace mtconnect::pipeline { { public: using Deliver = std::function; - DeliverConnectionStatus(PipelineContextPtr context, const StringList &devices, + DeliverConnectionStatus(PipelineContextPtr context, const StringList& devices, bool autoAvailable) : Transform("DeliverConnectionStatus"), m_contract(context->m_contract.get()), @@ -202,10 +202,10 @@ namespace mtconnect::pipeline { { m_guard = EntityNameGuard("ConnectionStatus", RUN); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override; + entity::EntityPtr operator()(entity::EntityPtr&& entity) override; protected: - PipelineContract *m_contract; + PipelineContract* m_contract; std::list m_devices; bool m_autoAvailable; }; @@ -220,10 +220,10 @@ namespace mtconnect::pipeline { { m_guard = EntityNameGuard("AssetCommand", RUN); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override; + entity::EntityPtr operator()(entity::EntityPtr&& entity) override; protected: - PipelineContract *m_contract; + PipelineContract* m_contract; }; /// @brief Deliver an adapter command @@ -231,15 +231,15 @@ namespace mtconnect::pipeline { { public: using Deliver = std::function; - DeliverCommand(PipelineContextPtr context, const std::optional &device) + DeliverCommand(PipelineContextPtr context, const std::optional& device) : Transform("DeliverCommand"), m_contract(context->m_contract.get()), m_defaultDevice(device) { m_guard = EntityNameGuard("Command", RUN); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override; + entity::EntityPtr operator()(entity::EntityPtr&& entity) override; protected: - PipelineContract *m_contract; + PipelineContract* m_contract; std::optional m_defaultDevice; }; } // namespace mtconnect::pipeline diff --git a/src/mtconnect/pipeline/delta_filter.hpp b/src/mtconnect/pipeline/delta_filter.hpp index ac42924c..6e21743a 100644 --- a/src/mtconnect/pipeline/delta_filter.hpp +++ b/src/mtconnect/pipeline/delta_filter.hpp @@ -42,7 +42,7 @@ namespace mtconnect { m_contract(context->m_contract.get()) { using namespace observation; - constexpr static auto lambda = [](const Sample &s) { + constexpr static auto lambda = [](const Sample& s) { return bool(!s.isOrphan() && s.getDataItem()->getMinimumDelta()); }; m_guard = LambdaGuard>(lambda, RUN) || @@ -51,7 +51,7 @@ namespace mtconnect { ~DeltaFilter() override = default; - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { using namespace std; using namespace observation; @@ -63,7 +63,7 @@ namespace mtconnect { if (o->isOrphan()) return EntityPtr(); auto di = o->getDataItem(); - auto &id = di->getId(); + auto& id = di->getId(); if (o->isUnavailable()) { @@ -80,7 +80,7 @@ namespace mtconnect { } protected: - bool filterMinimumDelta(const std::string &id, const double value, const double fv) + bool filterMinimumDelta(const std::string& id, const double value, const double fv) { auto last = m_state->m_lastSampleValue.find(id); if (last != m_state->m_lastSampleValue.end()) @@ -102,7 +102,7 @@ namespace mtconnect { protected: std::shared_ptr m_state; - PipelineContract *m_contract; + PipelineContract* m_contract; }; } // namespace pipeline } // namespace mtconnect diff --git a/src/mtconnect/pipeline/duplicate_filter.hpp b/src/mtconnect/pipeline/duplicate_filter.hpp index 1f075ce2..3b430d8b 100644 --- a/src/mtconnect/pipeline/duplicate_filter.hpp +++ b/src/mtconnect/pipeline/duplicate_filter.hpp @@ -25,7 +25,7 @@ namespace mtconnect::pipeline { class AGENT_LIB_API DuplicateFilter : public Transform { public: - DuplicateFilter(const DuplicateFilter &) = default; + DuplicateFilter(const DuplicateFilter&) = default; /// @brief Create a duplicate filter with shared state from the context /// @param context the context DuplicateFilter(PipelineContextPtr context) : Transform("DuplicateFilter"), m_context(context) @@ -37,7 +37,7 @@ namespace mtconnect::pipeline { /// @brief check if the entity is a duplicate /// @param[in] entity the entity to check /// @return the result of the transform if not a duplicate or an empty entity - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { using namespace observation; diff --git a/src/mtconnect/pipeline/guard.hpp b/src/mtconnect/pipeline/guard.hpp index 3a45649f..45b3eb55 100644 --- a/src/mtconnect/pipeline/guard.hpp +++ b/src/mtconnect/pipeline/guard.hpp @@ -31,7 +31,7 @@ namespace mtconnect { }; /// @brief Guard is a lambda function returning a `GuardAction` taking an entity - using Guard = std::function; + using Guard = std::function; /// @brief A simple GuardClass returning a simple match /// @@ -42,19 +42,19 @@ namespace mtconnect { /// @brief Construct a GuardCls /// @param match the action if matched GuardCls(GuardAction action) : m_action(action) {} - GuardCls(const GuardCls &) = default; + GuardCls(const GuardCls&) = default; - GuardAction operator()(const entity::Entity *entity) { return m_action; } + GuardAction operator()(const entity::Entity* entity) { return m_action; } /// @brief set the alternative guard /// @param alt alternative - void setAlternative(Guard &alt) { m_alternative = alt; } + void setAlternative(Guard& alt) { m_alternative = alt; } /// @brief check the matched state and if matched then return action. /// @param matched if `true` return the action otherwise check an alternative /// @param entity an entity /// @return the guard action - GuardAction check(bool matched, const entity::Entity *entity) + GuardAction check(bool matched, const entity::Entity* entity) { if (matched) return m_action; @@ -67,7 +67,7 @@ namespace mtconnect { /// @brief set the alternative to the other /// @param other a guard /// @return this - auto &operator||(Guard other) + auto& operator||(Guard other) { m_alternative = other; return *this; @@ -75,7 +75,7 @@ namespace mtconnect { /// @brief Set the alternative to a static action /// @param other the guard action /// @return this - auto &operator||(GuardAction other) + auto& operator||(GuardAction other) { m_alternative = GuardCls(other); return *this; @@ -102,29 +102,29 @@ namespace mtconnect { /// @param ti the type info we're checking /// @return `true` if matches template - constexpr bool match(const entity::Entity *ep) + constexpr bool match(const entity::Entity* ep) { if constexpr ((sizeof...(R)) == 0) - return dynamic_cast(ep); + return dynamic_cast(ep); else - return dynamic_cast(ep) != nullptr || match(ep); + return dynamic_cast(ep) != nullptr || match(ep); } /// @brief constexpr expanded type match /// @param entity the entity /// @return `true` if matches - constexpr bool matches(const entity::Entity *entity) { return match(entity); } + constexpr bool matches(const entity::Entity* entity) { return match(entity); } /// @brief Check if the entity matches one of the types /// @param[in] entity pointer to the entity /// @returns the actionn to take if the types match - GuardAction operator()(const entity::Entity *entity) + GuardAction operator()(const entity::Entity* entity) { return check(matches(entity), entity); } /// @brief set the alternative action if this guard does not match - auto &operator||(Guard other) + auto& operator||(Guard other) { m_alternative = other; return *this; @@ -145,7 +145,7 @@ namespace mtconnect { /// @param ti the type info we're checking /// @return `true` if matches template - constexpr bool match(const std::type_info &ti) + constexpr bool match(const std::type_info& ti) { if constexpr ((sizeof...(R)) == 0) return typeid(T) == ti; @@ -156,23 +156,23 @@ namespace mtconnect { /// @brief constexpr expanded type match /// @param entity the entity /// @return `true` if matches - constexpr bool matches(const entity::Entity *entity) + constexpr bool matches(const entity::Entity* entity) { - auto &e = *entity; - auto &ti = typeid(e); + auto& e = *entity; + auto& ti = typeid(e); return match(ti); } /// @brief Check if the entity exactly matches one of the types /// @param[in] entity pointer to the entity /// @returns the action to take if the types match - GuardAction operator()(const entity::Entity *entity) + GuardAction operator()(const entity::Entity* entity) { return check(matches(entity), entity); } /// @brief set the alternative action if this guard does not match - auto &operator||(Guard other) + auto& operator||(Guard other) { m_alternative = other; return *this; @@ -183,20 +183,20 @@ namespace mtconnect { class EntityNameGuard : public GuardCls { public: - EntityNameGuard(const std::string &name, GuardAction match) : GuardCls(match), m_name(name) {} + EntityNameGuard(const std::string& name, GuardAction match) : GuardCls(match), m_name(name) {} - bool matches(const entity::Entity *entity) { return entity->getName() == m_name; } + bool matches(const entity::Entity* entity) { return entity->getName() == m_name; } /// @brief Check if the entity name matches /// @param[in] entity pointer to the entity /// @returns the action to take if the types match - GuardAction operator()(const entity::Entity *entity) + GuardAction operator()(const entity::Entity* entity) { return check(matches(entity), entity); } /// @brief set the alternative action if this guard does not match - auto &operator||(Guard other) + auto& operator||(Guard other) { m_alternative = other; return *this; @@ -213,24 +213,24 @@ namespace mtconnect { class LambdaGuard : public B { public: - using Lambda = std::function; + using Lambda = std::function; /// @brief Construct a lambda guard with a function returning bool and an action /// @param guard the lambda function /// @param match the action if the lambda returns true LambdaGuard(Lambda guard, GuardAction match) : B(match), m_lambda(guard) {} - LambdaGuard(const LambdaGuard &) = default; + LambdaGuard(const LambdaGuard&) = default; ~LambdaGuard() = default; /// @brief call the `B::matches()` method with the entity /// @param entity the entity /// @return `true` if matched - bool matches(const entity::Entity *entity) + bool matches(const entity::Entity* entity) { bool matched = B::matches(entity); if (matched) { - auto o = dynamic_cast(entity); + auto o = dynamic_cast(entity); matched = o != nullptr && m_lambda(*o); } @@ -240,13 +240,13 @@ namespace mtconnect { /// @brief Check if the entity name matches the base guard and the lambda /// @param[in] entity pointer to the entity /// @returns the action to take if the types match - GuardAction operator()(const entity::Entity *entity) + GuardAction operator()(const entity::Entity* entity) { return B::check(matches(entity), entity); } /// @brief set the alternative action if this guard does not match - auto &operator||(Guard other) + auto& operator||(Guard other) { B::m_alternative = other; return *this; diff --git a/src/mtconnect/pipeline/json_mapper.cpp b/src/mtconnect/pipeline/json_mapper.cpp index c841d5c9..b5e9f15e 100644 --- a/src/mtconnect/pipeline/json_mapper.cpp +++ b/src/mtconnect/pipeline/json_mapper.cpp @@ -64,7 +64,7 @@ namespace mtconnect::pipeline { ParserContext(PipelineContextPtr pipelineContext) : m_pipelineContext(pipelineContext) {} using Forward = - std::function; //!< Lambda to send a completed entity + std::function; //!< Lambda to send a completed entity /// @brief clear the current state void clear() @@ -75,7 +75,7 @@ namespace mtconnect::pipeline { } /// @brief Get the data item for a device - DataItemPtr getDataItemForDevice(const std::string_view &sv) + DataItemPtr getDataItemForDevice(const std::string_view& sv) { DataItemPtr di; DevicePtr device; @@ -103,20 +103,20 @@ namespace mtconnect::pipeline { } /// @brief get a device from the agent - DevicePtr getDevice(const std::string_view &name) + DevicePtr getDevice(const std::string_view& name) { return m_pipelineContext->m_contract->findDevice({name.data(), name.length()}); } /// @brief set the timestamp - void setTimestamp(Timestamp &ts, optional &duration) + void setTimestamp(Timestamp& ts, optional& duration) { m_timestamp.emplace(ts); m_duration = duration; } /// @brief send a complete observation when the data item and props have values. - void send(DataItemPtr dataItem, entity::Properties &props) + void send(DataItemPtr dataItem, entity::Properties& props) { if (!m_timestamp) { @@ -131,7 +131,7 @@ namespace mtconnect::pipeline { auto obs = observation::Observation::make(dataItem, props, *m_timestamp, errors); if (!errors.empty()) { - for (auto &e : errors) + for (auto& e : errors) { LOG(warning) << "Error while parsing json: " << e->what(); } @@ -166,7 +166,7 @@ namespace mtconnect::pipeline { if (!m_timestamp) m_timestamp = DefaultNow(); - for (auto &e : m_queue) + for (auto& e : m_queue) { send(e.first, e.second); } @@ -191,7 +191,7 @@ namespace mtconnect::pipeline { ErrorHandler(int depth = 0) : m_depth(depth) {} bool Default() { return true; } - bool Key(const Ch *str, rj::SizeType length, bool copy) { return true; } + bool Key(const Ch* str, rj::SizeType length, bool copy) { return true; } bool StartObject() { m_depth++; @@ -213,7 +213,7 @@ namespace mtconnect::pipeline { return true; } - bool operator()(rj::Reader &reader, rj::StringStream &buff) + bool operator()(rj::Reader& reader, rj::StringStream& buff) { LOG(warning) << "Consuming value due to error"; @@ -239,7 +239,7 @@ namespace mtconnect::pipeline { { using Ch = typename Encoding::Ch; - DataSetHandler(ST &set, optional key, bool table = false) : m_set(set), m_table(table) + DataSetHandler(ST& set, optional key, bool table = false) : m_set(set), m_table(table) { if (key) { @@ -283,16 +283,16 @@ namespace mtconnect::pipeline { m_entry.m_value.template emplace(d); return true; } - bool RawNumber(const Ch *str, rj::SizeType length, bool copy) + bool RawNumber(const Ch* str, rj::SizeType length, bool copy) { return String(str, length, copy); } - bool String(const Ch *str, rj::SizeType length, bool copy) + bool String(const Ch* str, rj::SizeType length, bool copy) { if (m_expectation != Expectation::VALUE) return false; - m_entry.m_value.template emplace((const char *)str, length); + m_entry.m_value.template emplace((const char*)str, length); return true; } bool StartObject() @@ -312,11 +312,11 @@ namespace mtconnect::pipeline { // Table handler return true; } - bool Key(const Ch *str, rj::SizeType length, bool copy) + bool Key(const Ch* str, rj::SizeType length, bool copy) { // Check for resetTriggered m_expectation = Expectation::VALUE; - m_entry.m_key = std::string((const char *)str, length); + m_entry.m_key = std::string((const char*)str, length); return true; } bool EndObject(rj::SizeType memberCount) @@ -327,7 +327,7 @@ namespace mtconnect::pipeline { bool StartArray() { return false; } bool EndArray(rj::SizeType elementCount) { return false; } - bool operator()(rj::Reader &reader, rj::StringStream &buff) + bool operator()(rj::Reader& reader, rj::StringStream& buff) { // Parse initial object if (m_expectation == Expectation::OBJECT && @@ -370,7 +370,7 @@ namespace mtconnect::pipeline { // For tables, recurse down to read the entry data set if constexpr (std::is_same_v) { - auto &row = m_entry.m_value.template emplace(); + auto& row = m_entry.m_value.template emplace(); DataSetHandler handler(row, nullopt, false); auto success = handler(reader, buff); if (!success) @@ -402,7 +402,7 @@ namespace mtconnect::pipeline { return true; } - ST &m_set; + ST& m_set; ET m_entry; optional m_resetTriggered; bool m_table {false}; @@ -429,7 +429,7 @@ namespace mtconnect::pipeline { /// and field name. struct PropertiesHandler : rj::BaseReaderHandler, PropertiesHandler> { - PropertiesHandler(DataItemPtr dataItem, entity::Properties &props) + PropertiesHandler(DataItemPtr dataItem, entity::Properties& props) : m_props(props), m_dataItem(dataItem), m_key("VALUE"), m_expectation(Expectation::VALUE) {} @@ -472,11 +472,11 @@ namespace mtconnect::pipeline { setValue(d); return true; } - bool RawNumber(const Ch *str, rj::SizeType length, bool copy) + bool RawNumber(const Ch* str, rj::SizeType length, bool copy) { return String(str, length, copy); } - bool String(const Ch *str, rj::SizeType length, bool copy) + bool String(const Ch* str, rj::SizeType length, bool copy) { setValue(string(str, length)); return true; @@ -487,7 +487,7 @@ namespace mtconnect::pipeline { m_depth++; if (m_dataItem->isTimeSeries() || m_dataItem->isThreeSpace()) { - auto &value = m_props["VALUE"]; + auto& value = m_props["VALUE"]; m_vector = &value.emplace(); m_expectation = Expectation::VECTOR; return true; @@ -516,7 +516,7 @@ namespace mtconnect::pipeline { } } - bool Key(const Ch *str, rj::SizeType length, bool copy) + bool Key(const Ch* str, rj::SizeType length, bool copy) { std::string_view sv(str, length); map::const_iterator f, e; @@ -579,7 +579,7 @@ namespace mtconnect::pipeline { return false; } - bool operator()(rj::Reader &reader, rj::StringStream &buff) + bool operator()(rj::Reader& reader, rj::StringStream& buff) { while (!reader.IterativeParseComplete() && !m_done) { @@ -601,8 +601,8 @@ namespace mtconnect::pipeline { } else if (m_expectation == Expectation::DATA_SET) { - auto &value = m_props["VALUE"]; - DataSet &set = value.emplace(); + auto& value = m_props["VALUE"]; + DataSet& set = value.emplace(); DataSetHandler handler(set, m_key, m_dataItem->isTable()); if (!handler(reader, buff)) return false; @@ -630,9 +630,9 @@ namespace mtconnect::pipeline { return true; } - entity::Properties &m_props; + entity::Properties& m_props; DataItemPtr m_dataItem; - Vector *m_vector {nullptr}; + Vector* m_vector {nullptr}; bool m_done {false}; bool m_object {false}; std::string m_key; @@ -648,7 +648,7 @@ namespace mtconnect::pipeline { return false; } - bool String(const Ch *str, rj::SizeType length, bool copy) + bool String(const Ch* str, rj::SizeType length, bool copy) { std::string_view sv(str, length); std::optional base; @@ -659,7 +659,7 @@ namespace mtconnect::pipeline { return true; } - bool operator()(rj::Reader &reader, rj::StringStream &buff) + bool operator()(rj::Reader& reader, rj::StringStream& buff) { auto success = (!reader.IterativeParseComplete() && reader.IterativeParseNext(buff, *this)); @@ -672,21 +672,21 @@ namespace mtconnect::pipeline { struct AssetHandler : rj::BaseReaderHandler, TimestampHandler> { - AssetHandler(ParserContext &context) : m_context(context) {} + AssetHandler(ParserContext& context) : m_context(context) {} bool Default() { LOG(warning) << "Expecting an asset"; return false; } - bool Key(const Ch *str, rj::SizeType length, bool copy) + bool Key(const Ch* str, rj::SizeType length, bool copy) { m_assetId = string(str, length); m_expectation = Expectation::ASSET; return true; } - bool String(const Ch *str, rj::SizeType length, bool copy) + bool String(const Ch* str, rj::SizeType length, bool copy) { using namespace mtconnect::asset; ErrorList errors; @@ -697,7 +697,7 @@ namespace mtconnect::pipeline { if (!errors.empty()) { LOG(warning) << "Errors while parsing json asset: "; - for (const auto &e : errors) + for (const auto& e : errors) { LOG(warning) << " " << e->what(); } @@ -733,7 +733,7 @@ namespace mtconnect::pipeline { return true; } - bool operator()(rj::Reader &reader, rj::StringStream &buff) + bool operator()(rj::Reader& reader, rj::StringStream& buff) { // Consume start object if (m_expectation == Expectation::OBJECT) @@ -769,7 +769,7 @@ namespace mtconnect::pipeline { return true; } - ParserContext &m_context; + ParserContext& m_context; Expectation m_expectation {Expectation::OBJECT}; string m_assetId; bool m_done {false}; @@ -777,7 +777,7 @@ namespace mtconnect::pipeline { struct ObjectHandler : rj::BaseReaderHandler, ObjectHandler> { - ObjectHandler(ParserContext &context) : m_context(context) {} + ObjectHandler(ParserContext& context) : m_context(context) {} bool Default() { LOG(warning) << "Expecting a key"; @@ -785,7 +785,7 @@ namespace mtconnect::pipeline { return true; } - bool Key(const Ch *str, rj::SizeType length, bool copy) + bool Key(const Ch* str, rj::SizeType length, bool copy) { std::string_view sv(str, length); if (sv == "timestamp") @@ -831,7 +831,7 @@ namespace mtconnect::pipeline { return true; } - bool operator()(rj::Reader &reader, rj::StringStream &buff) + bool operator()(rj::Reader& reader, rj::StringStream& buff) { while (!m_complete && !reader.IterativeParseComplete()) { @@ -931,7 +931,7 @@ namespace mtconnect::pipeline { optional m_timestamp; optional m_duration; - ParserContext &m_context; + ParserContext& m_context; bool m_complete {false}; Expectation m_expectation {Expectation::KEY}; DataItemPtr m_dataItem; @@ -940,7 +940,7 @@ namespace mtconnect::pipeline { struct ArrayHandler : rj::BaseReaderHandler, ArrayHandler> { - ArrayHandler(ParserContext &context) : m_context(context) {} + ArrayHandler(ParserContext& context) : m_context(context) {} bool Default() { LOG(warning) << "Expecting an array of objects"; @@ -954,7 +954,7 @@ namespace mtconnect::pipeline { return true; } - bool operator()(rj::Reader &reader, rj::StringStream &buff) + bool operator()(rj::Reader& reader, rj::StringStream& buff) { while (!reader.IterativeParseComplete() && !m_complete) { @@ -977,13 +977,13 @@ namespace mtconnect::pipeline { } Expectation m_expectation {Expectation::OBJECT}; - ParserContext &m_context; + ParserContext& m_context; bool m_complete {false}; }; struct TopLevelHandler : rj::BaseReaderHandler, TopLevelHandler> { - TopLevelHandler(ParserContext &context) : m_context(context) {} + TopLevelHandler(ParserContext& context) : m_context(context) {} bool Default() { LOG(warning) << "Top level can only be an object or array"; @@ -1003,7 +1003,7 @@ namespace mtconnect::pipeline { } bool EndArray(rj::SizeType elementCount) { return true; } - bool operator()(rj::Reader &reader, rj::StringStream &buff) + bool operator()(rj::Reader& reader, rj::StringStream& buff) { while (!reader.IterativeParseComplete()) { @@ -1029,25 +1029,25 @@ namespace mtconnect::pipeline { } Expectation m_expectation {Expectation::NONE}; - ParserContext &m_context; + ParserContext& m_context; }; /// @brief Use rapidjson to parse the json content. If there is an error, output the text and /// log the error. - EntityPtr JsonMapper::operator()(entity::EntityPtr &&entity) + EntityPtr JsonMapper::operator()(entity::EntityPtr&& entity) { static const auto GetParseError = rj::GetParseError_En; auto source = entity->maybeGet("source"); auto json = std::dynamic_pointer_cast(entity); DevicePtr device = json->m_device.lock(); - auto &body = entity->getValue(); + auto& body = entity->getValue(); rj::StringStream buff(body.c_str()); rj::Reader reader; reader.IterativeParseInit(); ParserContext context(m_context); - context.m_forward = [this](entity::EntityPtr &&entity) { next(std::move(entity)); }; + context.m_forward = [this](entity::EntityPtr&& entity) { next(std::move(entity)); }; context.m_source = source; TopLevelHandler handler(context); diff --git a/src/mtconnect/pipeline/json_mapper.hpp b/src/mtconnect/pipeline/json_mapper.hpp index 46a0d3d8..a47a596d 100644 --- a/src/mtconnect/pipeline/json_mapper.hpp +++ b/src/mtconnect/pipeline/json_mapper.hpp @@ -32,7 +32,7 @@ namespace mtconnect::pipeline { class AGENT_LIB_API JsonMapper : public Transform { public: - JsonMapper(const JsonMapper &) = default; + JsonMapper(const JsonMapper&) = default; JsonMapper(PipelineContextPtr context) : Transform("JsonMapper"), m_context(context) { m_guard = TypeGuard(RUN); @@ -40,7 +40,7 @@ namespace mtconnect::pipeline { /// @brief Use rapidjson to parse the json content. If there is an error, output the text and /// log the error. - EntityPtr operator()(entity::EntityPtr &&entity) override; + EntityPtr operator()(entity::EntityPtr&& entity) override; protected: PipelineContextPtr m_context; diff --git a/src/mtconnect/pipeline/message_mapper.hpp b/src/mtconnect/pipeline/message_mapper.hpp index 274b6119..bd5d60f2 100644 --- a/src/mtconnect/pipeline/message_mapper.hpp +++ b/src/mtconnect/pipeline/message_mapper.hpp @@ -37,14 +37,14 @@ namespace mtconnect::pipeline { class AGENT_LIB_API DataMapper : public Transform { public: - DataMapper(const DataMapper &) = default; - DataMapper(PipelineContextPtr context, source::adapter::Handler *handler) + DataMapper(const DataMapper&) = default; + DataMapper(PipelineContextPtr context, source::adapter::Handler* handler) : Transform("DataMapper"), m_context(context), m_handler(handler) { m_guard = TypeGuard(RUN); } - EntityPtr operator()(entity::EntityPtr &&entity) override + EntityPtr operator()(entity::EntityPtr&& entity) override { auto source = entity->maybeGet("source"); auto data = std::dynamic_pointer_cast(entity); @@ -63,11 +63,11 @@ namespace mtconnect::pipeline { return next(std::move(obs)); } } - catch (entity::EntityError &e) + catch (entity::EntityError& e) { LOG(error) << "Could not create observation: " << e.what(); } - for (auto &e : errors) + for (auto& e : errors) { LOG(warning) << "Error while parsing message data: " << e->what(); } @@ -112,6 +112,6 @@ namespace mtconnect::pipeline { protected: PipelineContextPtr m_context; - source::adapter::Handler *m_handler; + source::adapter::Handler* m_handler; }; } // namespace mtconnect::pipeline diff --git a/src/mtconnect/pipeline/mtconnect_xml_transform.hpp b/src/mtconnect/pipeline/mtconnect_xml_transform.hpp index 33f6a75f..7f7a19df 100644 --- a/src/mtconnect/pipeline/mtconnect_xml_transform.hpp +++ b/src/mtconnect/pipeline/mtconnect_xml_transform.hpp @@ -43,15 +43,15 @@ namespace mtconnect::pipeline { class AGENT_LIB_API MTConnectXmlTransform : public Transform { public: - MTConnectXmlTransform(const MTConnectXmlTransform &) = default; + MTConnectXmlTransform(const MTConnectXmlTransform&) = default; /// @brief Construct a transfor, /// @param context the pipeline context /// @param feedback a feedback object to pass back protocol info /// @param device an associated device - MTConnectXmlTransform(PipelineContextPtr context, XmlTransformFeedback &feedback, - const std::optional &device = std::nullopt, - const std::optional &uuid = std::nullopt) + MTConnectXmlTransform(PipelineContextPtr context, XmlTransformFeedback& feedback, + const std::optional& device = std::nullopt, + const std::optional& uuid = std::nullopt) : Transform("MTConnectXmlTransform"), m_context(context), m_defaultDevice(device), @@ -61,13 +61,13 @@ namespace mtconnect::pipeline { m_guard = EntityNameGuard("Data", RUN); } - EntityPtr operator()(EntityPtr &&entity) override + EntityPtr operator()(EntityPtr&& entity) override { using namespace pipeline; using namespace entity; using namespace mtconnect::source; - const auto &data = entity->getValue(); + const auto& data = entity->getValue(); ResponseDocument rd; ResponseDocument::parse(data, rd, m_context, m_defaultDevice, m_uuid); @@ -101,7 +101,7 @@ namespace mtconnect::pipeline { } else { - for (auto &entity : rd.m_entities) + for (auto& entity : rd.m_entities) { next(std::move(entity)); } @@ -113,6 +113,6 @@ namespace mtconnect::pipeline { PipelineContextPtr m_context; std::optional m_defaultDevice; std::optional m_uuid; - XmlTransformFeedback &m_feedback; + XmlTransformFeedback& m_feedback; }; } // namespace mtconnect::pipeline diff --git a/src/mtconnect/pipeline/period_filter.hpp b/src/mtconnect/pipeline/period_filter.hpp index 47407ec1..e30c62a9 100644 --- a/src/mtconnect/pipeline/period_filter.hpp +++ b/src/mtconnect/pipeline/period_filter.hpp @@ -36,7 +36,7 @@ namespace mtconnect::pipeline { /// @brief Construct a Last Observation /// @param p the amount of time in the period /// @param st the strand to use for the time - LastObservation(std::chrono::milliseconds p, boost::asio::io_context::strand &st) + LastObservation(std::chrono::milliseconds p, boost::asio::io_context::strand& st) : m_timer(st.context()), m_period(p) {} @@ -69,14 +69,14 @@ namespace mtconnect::pipeline { /// @brief Construct a period filter with a context /// @param context the context /// @param st strand for the timer - PeriodFilter(PipelineContextPtr context, boost::asio::io_context::strand &st) + PeriodFilter(PipelineContextPtr context, boost::asio::io_context::strand& st) : Transform("PeriodFilter"), m_state(context->getSharedState(m_name)), m_contract(context->m_contract.get()), m_strand(st) { using namespace observation; - constexpr static auto lambda = [](const Observation &s) { + constexpr static auto lambda = [](const Observation& s) { return bool(!s.isOrphan() && s.getDataItem()->getMinimumPeriod()); }; m_guard = LambdaGuard>(lambda, RUN) || @@ -84,7 +84,7 @@ namespace mtconnect::pipeline { } ~PeriodFilter() override = default; - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { using namespace std; using namespace observation; @@ -98,7 +98,7 @@ namespace mtconnect::pipeline { return EntityPtr(); auto di = obs->getDataItem(); - auto &id = di->getId(); + auto& id = di->getId(); if (obs->isUnavailable()) { @@ -132,20 +132,20 @@ namespace mtconnect::pipeline { protected: // Returns true if the observation is filtered. - bool filtered(LastObservation &last, const std::string &id, observation::ObservationPtr &obs) + bool filtered(LastObservation& last, const std::string& id, observation::ObservationPtr& obs) { using namespace std; using namespace chrono; using namespace observation; - const auto &ts = obs->getTimestamp(); + const auto& ts = obs->getTimestamp(); #ifdef DEBUG_PERIOD_FILTER std::cout << "<<<< Delta for obs at " << format(ts) << " is " << duration_cast(last.m_next - ts).count() << std::endl; #endif const auto start = last.m_next - last.m_period; - const auto &end = last.m_next; + const auto& end = last.m_next; if (ts < start) { @@ -233,7 +233,7 @@ namespace mtconnect::pipeline { } } - void delayDelivery(LastObservation &last, const std::string &id) + void delayDelivery(LastObservation& last, const std::string& id) { using std::placeholders::_1; using namespace std; @@ -280,7 +280,7 @@ namespace mtconnect::pipeline { auto lastIt = m_state->m_lastObservation.find(id); if (lastIt != m_state->m_lastObservation.end() && lastIt->second.m_observation) { - auto &last = lastIt->second; + auto& last = lastIt->second; #ifdef DEBUG_PERIOD_FILTER std::cout << "sendObservation: last timestamp is " @@ -321,7 +321,7 @@ namespace mtconnect::pipeline { protected: std::shared_ptr m_state; - PipelineContract *m_contract; - boost::asio::io_context::strand &m_strand; + PipelineContract* m_contract; + boost::asio::io_context::strand& m_strand; }; } // namespace mtconnect::pipeline diff --git a/src/mtconnect/pipeline/pipeline.hpp b/src/mtconnect/pipeline/pipeline.hpp index 0fbbdb54..4bed84aa 100644 --- a/src/mtconnect/pipeline/pipeline.hpp +++ b/src/mtconnect/pipeline/pipeline.hpp @@ -51,7 +51,7 @@ namespace mtconnect { { public: /// @brief A splice function type for resplicing the pipeline after it is rebuilt - using Splice = std::function; + using Splice = std::function; /// @brief Pipeline constructor /// @param context The pipeline context @@ -59,25 +59,25 @@ namespace mtconnect { /// @note All pipelines run in a single strand (thread) and therefor all operations are /// thread-safe in one pipeline. - Pipeline(PipelineContextPtr context, boost::asio::io_context::strand &st) + Pipeline(PipelineContextPtr context, boost::asio::io_context::strand& st) : m_start(std::make_shared()), m_context(context), m_strand(st) {} /// @brief Destructor stops the pipeline virtual ~Pipeline() { m_start->stop(); } /// @brief Build the pipeline /// @param options A set of configuration options - virtual void build(const ConfigOptions &options) = 0; + virtual void build(const ConfigOptions& options) = 0; /// @brief Has the pipeline started? /// @return `true` if started bool started() const { return m_started; } /// @brief Get a reference to the strand /// @return the strand - boost::asio::io_context::strand &getStrand() { return m_strand; } + boost::asio::io_context::strand& getStrand() { return m_strand; } /// @brief Apply the splices after rebuilding void applySplices() { - for (auto &splice : m_splices) + for (auto& splice : m_splices) { splice(this); } @@ -124,7 +124,7 @@ namespace mtconnect { /// @brief Find all transforms that match the target /// @param[in] target the named transforms to find /// @return a list of all matching transforms - Transform::ListOfTransforms find(const std::string &target) + Transform::ListOfTransforms find(const std::string& target) { Transform::ListOfTransforms xforms; m_start->find(target, xforms); @@ -136,7 +136,7 @@ namespace mtconnect { /// @param[in] transform the transform to add before /// @param[in] reapplied `true` if the pipeline is being rebuilt /// @returns `true` if the target is found and spliced - bool spliceBefore(const std::string &target, TransformPtr transform, bool reapplied = false) + bool spliceBefore(const std::string& target, TransformPtr transform, bool reapplied = false) { Transform::ListOfTransforms xforms; m_start->find(target, xforms); @@ -144,7 +144,7 @@ namespace mtconnect { return false; transform->unlink(); - for (auto &pair : xforms) + for (auto& pair : xforms) { pair.first->spliceBefore(pair.second, transform); } @@ -152,7 +152,7 @@ namespace mtconnect { if (!reapplied) { m_splices.emplace_back( - [target, transform](Pipeline *pipe) { pipe->spliceBefore(target, transform, true); }); + [target, transform](Pipeline* pipe) { pipe->spliceBefore(target, transform, true); }); } return true; @@ -163,7 +163,7 @@ namespace mtconnect { /// @param[in] transform the transform to add before /// @param[in] reapplied `true` if the pipeline is being rebuilt /// @returns `true` if the target is found and spliced - bool spliceAfter(const std::string &target, TransformPtr transform, bool reapplied = false) + bool spliceAfter(const std::string& target, TransformPtr transform, bool reapplied = false) { Transform::ListOfTransforms xforms; m_start->find(target, xforms); @@ -171,7 +171,7 @@ namespace mtconnect { return false; transform->unlink(); - for (auto &pair : xforms) + for (auto& pair : xforms) { pair.second->spliceAfter(transform); } @@ -179,7 +179,7 @@ namespace mtconnect { if (!reapplied) { m_splices.emplace_back( - [target, transform](Pipeline *pipe) { pipe->spliceAfter(target, transform, true); }); + [target, transform](Pipeline* pipe) { pipe->spliceAfter(target, transform, true); }); } return true; @@ -190,14 +190,14 @@ namespace mtconnect { /// @param[in] transform the transform to add before /// @param[in] reapplied `true` if the pipeline is being rebuilt /// @returns `true` if the target is found and spliced - bool firstAfter(const std::string &target, TransformPtr transform, bool reapplied = false) + bool firstAfter(const std::string& target, TransformPtr transform, bool reapplied = false) { Transform::ListOfTransforms xforms; m_start->find(target, xforms); if (xforms.empty()) return false; - for (auto &pair : xforms) + for (auto& pair : xforms) { pair.second->firstAfter(transform); } @@ -205,7 +205,7 @@ namespace mtconnect { if (!reapplied) { m_splices.emplace_back( - [target, transform](Pipeline *pipe) { pipe->firstAfter(target, transform, true); }); + [target, transform](Pipeline* pipe) { pipe->firstAfter(target, transform, true); }); } return true; } @@ -215,14 +215,14 @@ namespace mtconnect { /// @param[in] transform the transform to add before /// @param[in] reapplied `true` if the pipeline is being rebuilt /// @returns `true` if the target is found and spliced - bool lastAfter(const std::string &target, TransformPtr transform, bool reapplied = false) + bool lastAfter(const std::string& target, TransformPtr transform, bool reapplied = false) { Transform::ListOfTransforms xforms; m_start->find(target, xforms); if (xforms.empty()) return false; - for (auto &pair : xforms) + for (auto& pair : xforms) { pair.second->bind(transform); } @@ -230,7 +230,7 @@ namespace mtconnect { if (!reapplied) { m_splices.emplace_back( - [target, transform](Pipeline *pipe) { pipe->lastAfter(target, transform, true); }); + [target, transform](Pipeline* pipe) { pipe->lastAfter(target, transform, true); }); } return true; } @@ -240,7 +240,7 @@ namespace mtconnect { /// @param[in] transform the transform to add before /// @param[in] reapplied `true` if the pipeline is being rebuilt /// @returns `true` if the target is found and spliced - bool replace(const std::string &target, TransformPtr transform, bool reapplied = false) + bool replace(const std::string& target, TransformPtr transform, bool reapplied = false) { Transform::ListOfTransforms xforms; m_start->find(target, xforms); @@ -248,7 +248,7 @@ namespace mtconnect { return false; transform->unlink(); - for (auto &pair : xforms) + for (auto& pair : xforms) { pair.first->replace(pair.second, transform); } @@ -256,7 +256,7 @@ namespace mtconnect { if (!reapplied) { m_splices.emplace_back( - [target, transform](Pipeline *pipe) { pipe->replace(target, transform, true); }); + [target, transform](Pipeline* pipe) { pipe->replace(target, transform, true); }); } return true; @@ -265,19 +265,19 @@ namespace mtconnect { /// @brief removes the named transform. /// @param[in] target the named transforms to replace /// @returns `true` if the target is found and spliced - bool remove(const std::string &target) + bool remove(const std::string& target) { Transform::ListOfTransforms xforms; m_start->find(target, xforms); if (xforms.empty()) return false; - for (auto &pair : xforms) + for (auto& pair : xforms) { pair.first->remove(pair.second); } - m_splices.emplace_back([target](Pipeline *pipe) { pipe->remove(target); }); + m_splices.emplace_back([target](Pipeline* pipe) { pipe->remove(target); }); return true; } @@ -285,7 +285,7 @@ namespace mtconnect { /// @brief Sends the entity through the pipeline /// @param[in] entity the entity to send through the pipeline /// @return the entity returned from the transform - entity::EntityPtr run(entity::EntityPtr &&entity) { return m_start->next(std::move(entity)); } + entity::EntityPtr run(entity::EntityPtr&& entity) { return m_start->next(std::move(entity)); } /// @brief Bind the transform to the start /// @param[in] transform the transform to bind @@ -308,7 +308,7 @@ namespace mtconnect { PipelineContextPtr getContext() { return m_context; } /// @brief gets the pipeline contract /// @returns the pipeline contract - const auto &getContract() { return m_context->m_contract; } + const auto& getContract() { return m_context->m_contract; } protected: class AGENT_LIB_API Start : public Transform @@ -316,11 +316,11 @@ namespace mtconnect { public: Start() : Transform("Start") { - m_guard = [](const entity::Entity *entity) { return SKIP; }; + m_guard = [](const entity::Entity* entity) { return SKIP; }; } ~Start() override = default; - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { return entity::EntityPtr(); } diff --git a/src/mtconnect/pipeline/pipeline_context.hpp b/src/mtconnect/pipeline/pipeline_context.hpp index e152f262..78af9308 100644 --- a/src/mtconnect/pipeline/pipeline_context.hpp +++ b/src/mtconnect/pipeline/pipeline_context.hpp @@ -58,9 +58,9 @@ namespace mtconnect::pipeline { /// @param[in] name the name of the shared state /// @return a shared pointer to the shared state. template - std::shared_ptr getSharedState(const std::string &name) + std::shared_ptr getSharedState(const std::string& name) { - auto &state = m_sharedState[name]; + auto& state = m_sharedState[name]; if (!state) state = std::make_shared(); return std::dynamic_pointer_cast(state); diff --git a/src/mtconnect/pipeline/pipeline_contract.hpp b/src/mtconnect/pipeline/pipeline_contract.hpp index 0a83c561..92b670ee 100644 --- a/src/mtconnect/pipeline/pipeline_contract.hpp +++ b/src/mtconnect/pipeline/pipeline_contract.hpp @@ -67,12 +67,12 @@ namespace mtconnect { /// @brief Find a device by name or uuid /// @param[in] device device name or uuid /// @return shared pointer to the device if found - virtual DevicePtr findDevice(const std::string &device) = 0; + virtual DevicePtr findDevice(const std::string& device) = 0; /// @brief Find a data item for a device by name. /// @param[in] device name or uuid of the device /// @param[in] name name or id of the data item /// @return shared pointer to the data item if found - virtual DataItemPtr findDataItem(const std::string &device, const std::string &name) = 0; + virtual DataItemPtr findDataItem(const std::string& device, const std::string& name) = 0; /// @brief get the current schema version as an integer /// @returns the schema version as an integer [major * 100 + minor] as a 32bit integer. virtual int32_t getSchemaVersion() const = 0; @@ -104,18 +104,18 @@ namespace mtconnect { /// @param[in] status the status of the source /// @param[in] devices a list of known devices /// @param[in] autoAvailable if the connection status should change availability - virtual void deliverConnectStatus(entity::EntityPtr status, const StringList &devices, + virtual void deliverConnectStatus(entity::EntityPtr status, const StringList& devices, bool autoAvailable) = 0; /// @brief The source is no longer viable, do not try to reconnect /// @param[in] identity the identity of the source - virtual void sourceFailed(const std::string &identity) = 0; + virtual void sourceFailed(const std::string& identity) = 0; /// @brief Check the observation with the current cache to determine if this is a /// duplicate /// @param[in] obs the observation to check /// @returns `obs` if it is not a duplicate, `nullptr` if it is. The observation /// may be modified if the observation needs to be subset. - virtual const ObservationPtr checkDuplicate(const ObservationPtr &obs) const = 0; + virtual const ObservationPtr checkDuplicate(const ObservationPtr& obs) const = 0; }; } // namespace pipeline } // namespace mtconnect diff --git a/src/mtconnect/pipeline/response_document.cpp b/src/mtconnect/pipeline/response_document.cpp index 81762171..1946dc26 100644 --- a/src/mtconnect/pipeline/response_document.cpp +++ b/src/mtconnect/pipeline/response_document.cpp @@ -51,7 +51,7 @@ namespace mtconnect::pipeline { return false; } - inline bool eachElement(xmlNodePtr node, const char *name, std::function cb) + inline bool eachElement(xmlNodePtr node, const char* name, std::function cb) { for (auto child = node->children; child != nullptr; child = child->next) { @@ -79,13 +79,13 @@ namespace mtconnect::pipeline { return false; } - inline string attributeValue(xmlNodePtr node, const char *name, bool optional = false) + inline string attributeValue(xmlNodePtr node, const char* name, bool optional = false) { string res; if (!eachAttribute(node, [&name, &res](xmlAttrPtr attr) { if (xmlStrcmp(BAD_CAST name, attr->name) == 0) { - res = (const char *)(attr->children->content); + res = (const char*)(attr->children->content); return false; } return true; @@ -98,7 +98,7 @@ namespace mtconnect::pipeline { return res; } - inline static xmlNodePtr findChild(xmlNodePtr node, const char *name, bool optional = false) + inline static xmlNodePtr findChild(xmlNodePtr node, const char* name, bool optional = false) { xmlNodePtr child; if (!eachElement(node, name, [&child](xmlNodePtr node) { @@ -114,7 +114,7 @@ namespace mtconnect::pipeline { return child; } - static inline bool parseHeader(ResponseDocument &out, xmlNodePtr root) + static inline bool parseHeader(ResponseDocument& out, xmlNodePtr root) { auto header = findChild(root, "Header"); if (header) @@ -131,7 +131,7 @@ namespace mtconnect::pipeline { return true; } - LOG(error) << "Received incorred document: " << (const char *)root->name; + LOG(error) << "Received incorred document: " << (const char*)root->name; return false; } @@ -142,17 +142,17 @@ namespace mtconnect::pipeline { { if (n->type == XML_TEXT_NODE) { - return trim((const char *)n->content); + return trim((const char*)n->content); } } return ""; } - inline static bool parseDevices(ResponseDocument &out, xmlNodePtr node, + inline static bool parseDevices(ResponseDocument& out, xmlNodePtr node, pipeline::PipelineContextPtr context, - const std::optional &device, - const std::optional &uuid) + const std::optional& device, + const std::optional& uuid) { using namespace entity; using namespace device_model; @@ -184,8 +184,8 @@ namespace mtconnect::pipeline { auto dev = parser.parseXmlNode(Device::getRoot(), n, errors); if (!errors.empty()) { - LOG(warning) << "Could not parse asset: " << (const char *)n->name; - for (auto &e : errors) + LOG(warning) << "Could not parse asset: " << (const char*)n->name; + for (auto& e : errors) { LOG(warning) << " Message: " << e->what(); } @@ -223,7 +223,7 @@ namespace mtconnect::pipeline { } template - inline VT type(const string &s) + inline VT type(const string& s) { using namespace boost; if (s.empty()) @@ -252,7 +252,7 @@ namespace mtconnect::pipeline { return lexical_cast(s); } - inline void dataSet(xmlNodePtr node, bool table, DataSet &ds) + inline void dataSet(xmlNodePtr node, bool table, DataSet& ds) { eachElement(node, "Entry", [table, &ds](xmlNodePtr n) { DataSetEntry entry; @@ -261,7 +261,7 @@ namespace mtconnect::pipeline { if (table) { - TableRow &row = entry.m_value.emplace(); + TableRow& row = entry.m_value.emplace(); eachElement(n, "Cell", [&row](xmlNodePtr c) { row.emplace(attributeValue(c, "key"), type(text(c))); @@ -281,13 +281,13 @@ namespace mtconnect::pipeline { }); } - inline static DataItemPtr findDataItem(const std::string &name, DevicePtr device, - const entity::Properties &properties) + inline static DataItemPtr findDataItem(const std::string& name, DevicePtr device, + const entity::Properties& properties) { auto id = properties.find("dataItemId"); if (id == properties.end()) { - const string &uuid = *(device->getUuid()); + const string& uuid = *(device->getUuid()); LOG(warning) << "Device: " << uuid << ": Cannot find dataItemId for " << name; return nullptr; } @@ -298,7 +298,7 @@ namespace mtconnect::pipeline { auto diName = properties.find("name"); if (diName == properties.end()) { - const string &uuid = *(device->getUuid()); + const string& uuid = *(device->getUuid()); LOG(warning) << "Device: " << uuid << ": Cannot data item for id and no name:" << get(id->second); return nullptr; @@ -306,7 +306,7 @@ namespace mtconnect::pipeline { di = device->getDeviceDataItem(get(diName->second)); if (!di) { - const string &uuid = *(device->getUuid()); + const string& uuid = *(device->getUuid()); LOG(warning) << "Device: " << uuid << ": Cannot data item for id " << get(id->second) << " or name:" << get(diName->second); @@ -317,9 +317,9 @@ namespace mtconnect::pipeline { return di; } - inline static bool parseObservations(ResponseDocument &out, xmlNodePtr node, + inline static bool parseObservations(ResponseDocument& out, xmlNodePtr node, pipeline::PipelineContextPtr context, - const std::optional &deviceName) + const std::optional& deviceName) { auto streams = findChild(node, "Streams"); if (streams == nullptr) @@ -359,15 +359,15 @@ namespace mtconnect::pipeline { eachAttribute(o, [&properties](xmlAttrPtr attr) { if (xmlStrcmp(BAD_CAST "sequence", attr->name) != 0) { - string s((const char *)attr->children->content); - properties.insert({(const char *)attr->name, s}); + string s((const char*)attr->children->content); + properties.insert({(const char*)attr->name, s}); } return true; }); // Check for table or data set - string name((const char *)o->name); + string name((const char*)o->name); auto di = findDataItem(name, device, properties); if (!di) { @@ -397,9 +397,9 @@ namespace mtconnect::pipeline { } else // isDataSet { - Value &v = properties["VALUE"]; + Value& v = properties["VALUE"]; v.emplace(); - DataSet &ds = get(v); + DataSet& ds = get(v); dataSet(o, di->isTable(), ds); } @@ -407,7 +407,7 @@ namespace mtconnect::pipeline { auto obs = observation::Observation::make(di, properties, timestamp, errors); if (!errors.empty()) { - for (auto &e : errors) + for (auto& e : errors) { LOG(warning) << "Error while parsing XML: " << e->what(); } @@ -432,8 +432,8 @@ namespace mtconnect::pipeline { return true; } - inline static bool parseAssets(ResponseDocument &out, xmlNodePtr node, - const std::optional &device) + inline static bool parseAssets(ResponseDocument& out, xmlNodePtr node, + const std::optional& device) { using namespace entity; using namespace asset; @@ -448,8 +448,8 @@ namespace mtconnect::pipeline { auto res = parser.parseXmlNode(Asset::getRoot(), n, errors); if (!errors.empty()) { - LOG(warning) << "Could not parse asset: " << (const char *)n->name; - for (auto &e : errors) + LOG(warning) << "Could not parse asset: " << (const char*)n->name; + for (auto& e : errors) { LOG(warning) << " Message: " << e->what(); } @@ -463,7 +463,7 @@ namespace mtconnect::pipeline { return true; } - inline static void parseErrors(ResponseDocument &out, xmlNodePtr node) + inline static void parseErrors(ResponseDocument& out, xmlNodePtr node) { auto errors = findChild(node, "Errors"); if (errors == nullptr) @@ -492,10 +492,10 @@ namespace mtconnect::pipeline { } } - bool ResponseDocument::parse(const std::string_view &content, ResponseDocument &out, + bool ResponseDocument::parse(const std::string_view& content, ResponseDocument& out, pipeline::PipelineContextPtr context, - const std::optional &device, - const std::optional &uuid) + const std::optional& device, + const std::optional& uuid) { unique_ptr> doc( xmlReadMemory(content.data(), static_cast(content.length()), "incoming.xml", nullptr, @@ -532,7 +532,7 @@ namespace mtconnect::pipeline { } else { - LOG(error) << "Unknown document type: " << (const char *)root->name; + LOG(error) << "Unknown document type: " << (const char*)root->name; return false; } } diff --git a/src/mtconnect/pipeline/response_document.hpp b/src/mtconnect/pipeline/response_document.hpp index 05a9a08d..7cabf3ac 100644 --- a/src/mtconnect/pipeline/response_document.hpp +++ b/src/mtconnect/pipeline/response_document.hpp @@ -52,10 +52,10 @@ namespace mtconnect::pipeline { /// @param[in] context pipeline context /// @param[in] device optional device uuid /// @return `true` if successful - static bool parse(const std::string_view &content, ResponseDocument &doc, + static bool parse(const std::string_view& content, ResponseDocument& doc, pipeline::PipelineContextPtr context, - const std::optional &device = std::nullopt, - const std::optional &uuid = std::nullopt); + const std::optional& device = std::nullopt, + const std::optional& uuid = std::nullopt); // Parsed data SequenceNumber_t m_next; ///< Next sequence number diff --git a/src/mtconnect/pipeline/shdr_token_mapper.cpp b/src/mtconnect/pipeline/shdr_token_mapper.cpp index 19cbb2ba..8e569fee 100644 --- a/src/mtconnect/pipeline/shdr_token_mapper.cpp +++ b/src/mtconnect/pipeline/shdr_token_mapper.cpp @@ -30,7 +30,7 @@ using namespace std; namespace mtconnect { using namespace observation; namespace pipeline { - inline bool unavailable(const string &str) + inline bool unavailable(const string& str) { const static string unavailable("UNAVAILABLE"); return equal(str.cbegin(), str.cend(), unavailable.cbegin(), unavailable.cend(), @@ -38,7 +38,7 @@ namespace mtconnect { } inline static std::pair, std::optional> - splitPair(const std::string &key) + splitPair(const std::string& key) { string_view sv(key.c_str()); auto c = sv.find(':'); @@ -52,7 +52,7 @@ namespace mtconnect { } inline static std::pair> splitKey( - const std::string &key) + const std::string& key) { auto c = key.find(':'); if (c != string::npos) @@ -83,7 +83,7 @@ namespace mtconnect { static entity::Requirements s_event {{"VALUE", false}}; static entity::Requirements s_dataSet {{"VALUE", entity::ValueType::DATA_SET, false}}; - static inline size_t firtNonWsColon(const string &token) + static inline size_t firtNonWsColon(const string& token) { auto len = token.size(); for (size_t i = 0; i < len; i++) @@ -97,8 +97,8 @@ namespace mtconnect { return string::npos; } - static inline std::string extractResetTrigger(const DataItemPtr dataItem, const string &token, - Properties &properties) + static inline std::string extractResetTrigger(const DataItemPtr dataItem, const string& token, + Properties& properties) { size_t pos; // Check for reset triggered @@ -133,17 +133,17 @@ namespace mtconnect { } } - inline ObservationPtr zipProperties(const DataItemPtr dataItem, const Timestamp ×tamp, - const entity::Requirements &reqs, - TokenList::const_iterator &token, - const TokenList::const_iterator &end, ErrorList &errors, + inline ObservationPtr zipProperties(const DataItemPtr dataItem, const Timestamp& timestamp, + const entity::Requirements& reqs, + TokenList::const_iterator& token, + const TokenList::const_iterator& end, ErrorList& errors, int32_t schemaVersion, bool validation) { NAMED_SCOPE("zipProperties"); Properties props; for (auto req = reqs.begin(); token != end && req != reqs.end(); token++, req++) { - const string &tok = *token; + const string& tok = *token; if (req->getName() == "VALUE" || req->getName() == "level") { @@ -164,7 +164,7 @@ namespace mtconnect { req->convertType(value, dataItem->isTable()); props.insert_or_assign(req->getName(), value); } - catch (entity::PropertyError &e) + catch (entity::PropertyError& e) { LOG(debug) << "Cannot convert value for data item id '" << dataItem->getId() << "': " << *token << " - " << e.what(); @@ -203,11 +203,11 @@ namespace mtconnect { return Observation::make(dataItem, props, timestamp, errors); } - EntityPtr ShdrTokenMapper::mapTokensToDataItem(const Timestamp ×tamp, - const std::optional &source, - TokenList::const_iterator &token, - const TokenList::const_iterator &end, - ErrorList &errors) + EntityPtr ShdrTokenMapper::mapTokensToDataItem(const Timestamp& timestamp, + const std::optional& source, + TokenList::const_iterator& token, + const TokenList::const_iterator& end, + ErrorList& errors) { NAMED_SCOPE("DataItemMapper.ShdrTokenMapper.mapTokensToDataItem"); auto key = *token++; @@ -244,7 +244,7 @@ namespace mtconnect { // LOG(trace) << "Mapped " << key; // } - entity::Requirements *reqs {nullptr}; + entity::Requirements* reqs {nullptr}; // Extract the remaining tokens if ((dataItem->isDataSet() || dataItem->isTable()) && @@ -296,11 +296,11 @@ namespace mtconnect { return nullptr; } - EntityPtr ShdrTokenMapper::mapTokensToAsset(const Timestamp ×tamp, - const std::optional &source, - TokenList::const_iterator &token, - const TokenList::const_iterator &end, - ErrorList &errors) + EntityPtr ShdrTokenMapper::mapTokensToAsset(const Timestamp& timestamp, + const std::optional& source, + TokenList::const_iterator& token, + const TokenList::const_iterator& end, + ErrorList& errors) { using namespace mtconnect::asset; EntityPtr res; @@ -330,7 +330,7 @@ namespace mtconnect { if (!errors.empty()) { LOG(warning) << "Could not parse asset: " << body; - for (auto &e : errors) + for (auto& e : errors) { LOG(warning) << " Message: " << e->what(); } @@ -369,7 +369,7 @@ namespace mtconnect { return res; } - EntityPtr ShdrTokenMapper::operator()(EntityPtr &&entity) + EntityPtr ShdrTokenMapper::operator()(EntityPtr&& entity) { NAMED_SCOPE("DataItemMapper.ShdrTokenMapper.operator"); if (auto timestamped = std::dynamic_pointer_cast(entity)) @@ -378,7 +378,7 @@ namespace mtconnect { auto res = std::make_shared(*timestamped, TokenList {}); EntityList entities; - auto &tokens = timestamped->m_tokens; + auto& tokens = timestamped->m_tokens; auto token = tokens.cbegin(); auto end = tokens.end(); @@ -418,11 +418,11 @@ namespace mtconnect { break; } } - catch (entity::EntityError &e) + catch (entity::EntityError& e) { LOG(error) << "Could not create observation: " << e.what(); } - for (auto &e : errors) + for (auto& e : errors) { LOG(warning) << "Error while parsing tokens: " << e->what(); for (auto it = start; it != token; it++) diff --git a/src/mtconnect/pipeline/shdr_token_mapper.hpp b/src/mtconnect/pipeline/shdr_token_mapper.hpp index 8feef6c9..f69c250c 100644 --- a/src/mtconnect/pipeline/shdr_token_mapper.hpp +++ b/src/mtconnect/pipeline/shdr_token_mapper.hpp @@ -39,9 +39,9 @@ namespace mtconnect::pipeline { class AGENT_LIB_API ShdrTokenMapper : public Transform { public: - ShdrTokenMapper(const ShdrTokenMapper &) = default; + ShdrTokenMapper(const ShdrTokenMapper&) = default; ShdrTokenMapper(PipelineContextPtr context, - const std::optional &device = std::nullopt, int version = 1) + const std::optional& device = std::nullopt, int version = 1) : Transform("ShdrTokenMapper"), m_contract(context->m_contract.get()), m_defaultDevice(device), @@ -49,7 +49,7 @@ namespace mtconnect::pipeline { { m_guard = TypeGuard(RUN); } - EntityPtr operator()(entity::EntityPtr &&entity) override; + EntityPtr operator()(entity::EntityPtr&& entity) override; /// @brief Takes a tokenized set of fields and maps them data items /// @param[in] timestamp the timestamp from prior extraction @@ -58,10 +58,10 @@ namespace mtconnect::pipeline { /// @param[in] end the sentinal end token /// @param[in,out] errors /// @return returns an observation list - EntityPtr mapTokensToDataItem(const Timestamp ×tamp, - const std::optional &source, - TokenList::const_iterator &token, - const TokenList::const_iterator &end, ErrorList &errors); + EntityPtr mapTokensToDataItem(const Timestamp& timestamp, + const std::optional& source, + TokenList::const_iterator& token, + const TokenList::const_iterator& end, ErrorList& errors); /// @brief Takes a tokenized set of fields and maps them to assets /// @param timestamp the timestamp /// @param source the optional source @@ -69,14 +69,14 @@ namespace mtconnect::pipeline { /// @param[in] end the sentinal end token /// @param[in,out] errors /// @return An asset - EntityPtr mapTokensToAsset(const Timestamp ×tamp, const std::optional &source, - TokenList::const_iterator &token, - const TokenList::const_iterator &end, ErrorList &errors); + EntityPtr mapTokensToAsset(const Timestamp& timestamp, const std::optional& source, + TokenList::const_iterator& token, + const TokenList::const_iterator& end, ErrorList& errors); protected: // Logging Context std::set m_logOnce; - PipelineContract *m_contract; + PipelineContract* m_contract; std::optional m_defaultDevice; std::unordered_map m_dataItemMap; int m_shdrVersion {1}; diff --git a/src/mtconnect/pipeline/shdr_tokenizer.hpp b/src/mtconnect/pipeline/shdr_tokenizer.hpp index 245be1f7..b5287097 100644 --- a/src/mtconnect/pipeline/shdr_tokenizer.hpp +++ b/src/mtconnect/pipeline/shdr_tokenizer.hpp @@ -32,9 +32,9 @@ namespace mtconnect::pipeline { { public: using entity::Entity::Entity; - Tokens(const Tokens &) = default; + Tokens(const Tokens&) = default; Tokens() = default; - Tokens(const Tokens &ts, const TokenList &list) : Entity(ts), m_tokens(list) {} + Tokens(const Tokens& ts, const TokenList& list) : Entity(ts), m_tokens(list) {} TokenList m_tokens; }; @@ -43,13 +43,13 @@ namespace mtconnect::pipeline { class AGENT_LIB_API ShdrTokenizer : public Transform { public: - ShdrTokenizer(const ShdrTokenizer &) = default; + ShdrTokenizer(const ShdrTokenizer&) = default; ShdrTokenizer() : Transform("ShdrTokenizer") { m_guard = EntityNameGuard("Data", RUN); } ~ShdrTokenizer() = default; - entity::EntityPtr operator()(entity::EntityPtr &&data) override + entity::EntityPtr operator()(entity::EntityPtr&& data) override { - auto &body = data->getValue(); + auto& body = data->getValue(); entity::Properties props; if (auto source = data->maybeGet("source")) props["source"] = *source; @@ -59,7 +59,7 @@ namespace mtconnect::pipeline { } template - inline static std::string remove(const T &range, const char c) + inline static std::string remove(const T& range, const char c) { using namespace std; string res; @@ -69,7 +69,7 @@ namespace mtconnect::pipeline { return res; } - inline static std::string trim(const std::string &str) + inline static std::string trim(const std::string& str) { using namespace std; @@ -84,7 +84,7 @@ namespace mtconnect::pipeline { return str.substr(first, last - first + 1); } - static inline void tokenize(const std::string &data, TokenList &tokens) + static inline void tokenize(const std::string& data, TokenList& tokens) { using namespace std; auto cp = data.c_str(); @@ -96,7 +96,7 @@ namespace mtconnect::pipeline { cp++; auto start = cp, orig = cp; - const char *end = 0; + const char* end = 0; if (*cp == '"') { cp = ++start; @@ -112,7 +112,7 @@ namespace mtconnect::pipeline { cp = start + dist; copied = true; } - memmove(const_cast(cp), cp + 1, strlen(cp)); + memmove(const_cast(cp), cp + 1, strlen(cp)); } else if (*cp == '|') { diff --git a/src/mtconnect/pipeline/timestamp_extractor.hpp b/src/mtconnect/pipeline/timestamp_extractor.hpp index 73ef2c53..71bb6930 100644 --- a/src/mtconnect/pipeline/timestamp_extractor.hpp +++ b/src/mtconnect/pipeline/timestamp_extractor.hpp @@ -32,9 +32,9 @@ namespace mtconnect::pipeline { { public: using Tokens::Tokens; - Timestamped(const Timestamped &ts) = default; - Timestamped(const Tokens &ptr) : Tokens(ptr) {} - Timestamped(const Timestamped &ts, TokenList list) + Timestamped(const Timestamped& ts) = default; + Timestamped(const Tokens& ptr) : Tokens(ptr) {} + Timestamped(const Timestamped& ts, TokenList list) : Tokens(ts, list), m_timestamp(ts.m_timestamp), m_duration(ts.m_duration) {} ~Timestamped() = default; @@ -54,7 +54,7 @@ namespace mtconnect::pipeline { static auto inline DefaultNow = []() -> Timestamp { return std::chrono::system_clock::now(); }; - inline std::optional GetDuration(std::string_view ×tamp) + inline std::optional GetDuration(std::string_view& timestamp) { std::optional duration; @@ -63,7 +63,7 @@ namespace mtconnect::pipeline { { auto read = pos + 1; auto dur {timestamp.substr(read)}; - char *end {nullptr}; + char* end {nullptr}; duration = std::strtod(dur.data(), &end); if (end == 0) duration.reset(); @@ -77,10 +77,10 @@ namespace mtconnect::pipeline { /// @brief Parse a token with a timestamp and return the timestamp /// @param token the string with a 8601 timestamp /// @returns a Timestamp - inline std::pair> ParseTimestamp(const std::string_view &token, + inline std::pair> ParseTimestamp(const std::string_view& token, bool relative, - std::optional &base, - Microseconds &offset, + std::optional& base, + Microseconds& offset, Now now = DefaultNow) { using namespace std; @@ -120,7 +120,7 @@ namespace mtconnect::pipeline { double off; if (!has_t) { - char *end {0}; + char* end {0}; off = std::strtod(timestamp.data(), &end); if (end == timestamp.data()) { @@ -160,7 +160,7 @@ namespace mtconnect::pipeline { class AGENT_LIB_API ExtractTimestamp : public Transform { public: - ExtractTimestamp(const ExtractTimestamp &) = default; + ExtractTimestamp(const ExtractTimestamp&) = default; /// @brief Construct a timestamp extractor /// @param relativeTime `true` if using realtive time stamps ExtractTimestamp(bool relativeTime) @@ -170,7 +170,7 @@ namespace mtconnect::pipeline { } ~ExtractTimestamp() override = default; - EntityPtr operator()(entity::EntityPtr &&ptr) override + EntityPtr operator()(entity::EntityPtr&& ptr) override { TimestampedPtr res; std::optional token; @@ -197,7 +197,7 @@ namespace mtconnect::pipeline { return next(res); } - void extractTimestamp(const std::string &token, TimestampedPtr &ts) + void extractTimestamp(const std::string& token, TimestampedPtr& ts) { auto [timestamp, duration] = ParseTimestamp(token, m_relativeTime, m_base, m_offset, @@ -222,10 +222,10 @@ namespace mtconnect::pipeline { { public: IgnoreTimestamp() : ExtractTimestamp("IgnoreTimestamp") {} - IgnoreTimestamp(const IgnoreTimestamp &) = default; + IgnoreTimestamp(const IgnoreTimestamp&) = default; ~IgnoreTimestamp() override = default; - EntityPtr operator()(entity::EntityPtr &&ptr) override + EntityPtr operator()(entity::EntityPtr&& ptr) override { TimestampedPtr res; std::optional token; diff --git a/src/mtconnect/pipeline/topic_mapper.hpp b/src/mtconnect/pipeline/topic_mapper.hpp index 5d87debf..829fa324 100644 --- a/src/mtconnect/pipeline/topic_mapper.hpp +++ b/src/mtconnect/pipeline/topic_mapper.hpp @@ -61,8 +61,8 @@ namespace mtconnect::pipeline { class AGENT_LIB_API TopicMapper : public Transform { public: - TopicMapper(const TopicMapper &) = default; - TopicMapper(PipelineContextPtr context, const std::optional &device = std::nullopt) + TopicMapper(const TopicMapper&) = default; + TopicMapper(PipelineContextPtr context, const std::optional& device = std::nullopt) : Transform("TopicMapper"), m_context(context), m_defaultDeviceName(device) { m_guard = EntityNameGuard("Message", RUN); @@ -80,7 +80,7 @@ namespace mtconnect::pipeline { /// If found, remember the mapping of the topic to the data item /// @param topic the topic /// @return - auto resolve(const std::string &topic) + auto resolve(const std::string& topic) { using namespace std; namespace algo = boost::algorithm; @@ -115,7 +115,7 @@ namespace mtconnect::pipeline { if (!dataItem) { - for (auto &tok : path) + for (auto& tok : path) { device = m_context->m_contract->findDevice(tok); if (device) @@ -124,7 +124,7 @@ namespace mtconnect::pipeline { if (device) { - for (auto &tok : path) + for (auto& tok : path) { dataItem = device->getDeviceDataItem(tok); if (dataItem) @@ -140,10 +140,10 @@ namespace mtconnect::pipeline { return std::make_tuple(device, dataItem); } - EntityPtr operator()(entity::EntityPtr &&entity) override + EntityPtr operator()(entity::EntityPtr&& entity) override { PipelineMessagePtr result; - auto &body = entity->getValue(); + auto& body = entity->getValue(); auto c = body[0]; DataItemPtr dataItem; diff --git a/src/mtconnect/pipeline/transform.hpp b/src/mtconnect/pipeline/transform.hpp index 40a5680e..125cd76f 100644 --- a/src/mtconnect/pipeline/transform.hpp +++ b/src/mtconnect/pipeline/transform.hpp @@ -45,41 +45,41 @@ namespace mtconnect { using ApplyDataItem = std::function; using EachDataItem = std::function; - using FindDataItem = std::function; + using FindDataItem = std::function; /// @brief Abstract entity transformation class AGENT_LIB_API Transform : public std::enable_shared_from_this { public: - Transform(const Transform &) = default; + Transform(const Transform&) = default; /// @brief Construct a transform with a name /// @param[in] name transform name - Transform(const std::string &name) : m_name(name) {} + Transform(const std::string& name) : m_name(name) {} virtual ~Transform() = default; /// @brief Get the transform name /// @return the name - auto &getName() const { return m_name; } + auto& getName() const { return m_name; } /// @brief stop this transform and all the following transforms virtual void stop() { - for (auto &t : m_next) + for (auto& t : m_next) t->stop(); } /// @brief start the transform on a strand and all the following transforms /// @param st the strand - virtual void start(boost::asio::io_context::strand &st) + virtual void start(boost::asio::io_context::strand& st) { - for (auto &t : m_next) + for (auto& t : m_next) t->start(st); } /// @brief remove all the next transforms virtual void clear() { - for (auto &t : m_next) + for (auto& t : m_next) t->clear(); unlink(); } @@ -90,17 +90,17 @@ namespace mtconnect { /// @brief the transform method must be overloaded /// @param entity the entity /// @return the resulting entity - virtual entity::EntityPtr operator()(entity::EntityPtr &&entity) = 0; + virtual entity::EntityPtr operator()(entity::EntityPtr&& entity) = 0; TransformPtr getptr() { return shared_from_this(); } /// @brief get the list of next transforms /// @return the list of following transforms - TransformList &getNext() { return m_next; } + TransformList& getNext() { return m_next; } /// @brief Find the next transform to forward the entity on to /// @param entity the entity /// @return return the result of the transformation - entity::EntityPtr next(entity::EntityPtr &&entity) + entity::EntityPtr next(entity::EntityPtr&& entity) { if (m_next.empty()) return entity; @@ -108,7 +108,7 @@ namespace mtconnect { using namespace std; using namespace entity; - for (auto &t : m_next) + for (auto& t : m_next) { switch (t->check(entity.get())) { @@ -141,7 +141,7 @@ namespace mtconnect { /// @brief get the guard action for an entity /// @param[in] entity the entity /// @return the action to perform - GuardAction check(const entity::Entity *entity) + GuardAction check(const entity::Entity* entity) { if (!m_guard) return RUN; @@ -151,10 +151,10 @@ namespace mtconnect { /// @brief Get a reference to the guard /// @return the guard - const Guard &getGuard() const { return m_guard; } + const Guard& getGuard() const { return m_guard; } /// @brief set the guard /// @param guard a guard - void setGuard(const Guard &guard) { m_guard = guard; } + void setGuard(const Guard& guard) { m_guard = guard; } using TransformPair = std::pair; using ListOfTransforms = std::list; @@ -162,9 +162,9 @@ namespace mtconnect { /// @brief recursive step to find all transforms with a given name /// @param[in] target the target transform name /// @param[out] xforms the list of transform pairs - void findRec(const std::string &target, ListOfTransforms &xforms) + void findRec(const std::string& target, ListOfTransforms& xforms) { - for (auto &t : m_next) + for (auto& t : m_next) { if (t->getName() == target) { @@ -177,7 +177,7 @@ namespace mtconnect { /// @brief find all transforms with a given name /// @param[in] target the target transform name /// @param[out] xforms the transform pairs - void find(const std::string &target, ListOfTransforms &xforms) + void find(const std::string& target, ListOfTransforms& xforms) { if (m_name == target) { @@ -271,7 +271,7 @@ namespace mtconnect { { public: NullTransform(Guard guard) : Transform("NullTransform") { m_guard = guard; } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override { return entity; } + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { return entity; } }; /// @brief A transform that forwards an enetity baed on a guard. Used to merge streams.. @@ -279,7 +279,7 @@ namespace mtconnect { { public: MergeTransform(Guard guard) : Transform("MergeTransform") { m_guard = guard; } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { return next(std::move(entity)); } diff --git a/src/mtconnect/pipeline/upcase_value.hpp b/src/mtconnect/pipeline/upcase_value.hpp index 2e688a3e..b7f09b7d 100644 --- a/src/mtconnect/pipeline/upcase_value.hpp +++ b/src/mtconnect/pipeline/upcase_value.hpp @@ -27,7 +27,7 @@ #include "transform.hpp" namespace mtconnect::pipeline { - inline static std::string &upcase(std::string &s) + inline static std::string& upcase(std::string& s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); @@ -38,14 +38,14 @@ namespace mtconnect::pipeline { class AGENT_LIB_API UpcaseValue : public Transform { public: - UpcaseValue(const UpcaseValue &) = default; + UpcaseValue(const UpcaseValue&) = default; UpcaseValue() : Transform("UpcaseValue") { using namespace observation; m_guard = ExactTypeGuard(RUN) || TypeGuard(SKIP); } - EntityPtr operator()(entity::EntityPtr &&entity) override + EntityPtr operator()(entity::EntityPtr&& entity) override { using namespace observation; auto event = std::dynamic_pointer_cast(entity); diff --git a/src/mtconnect/pipeline/validator.hpp b/src/mtconnect/pipeline/validator.hpp index 1c50f05d..2d4fa439 100644 --- a/src/mtconnect/pipeline/validator.hpp +++ b/src/mtconnect/pipeline/validator.hpp @@ -35,7 +35,7 @@ namespace mtconnect::pipeline { class AGENT_LIB_API Validator : public Transform { public: - Validator(const Validator &) = default; + Validator(const Validator&) = default; Validator(PipelineContextPtr context) : Transform("Validator"), m_contract(context->m_contract.get()) { @@ -45,12 +45,12 @@ namespace mtconnect::pipeline { /// @brief validate the Event /// @param entity The Event entity /// @returns modified entity with quality and deprecated properties - EntityPtr operator()(entity::EntityPtr &&entity) override + EntityPtr operator()(entity::EntityPtr&& entity) override { using namespace observation; using namespace mtconnect::validation::observations; auto obs = std::dynamic_pointer_cast(entity); - auto &value = obs->getValue(); + auto& value = obs->getValue(); bool valid = true; auto di = obs->getDataItem(); @@ -62,7 +62,7 @@ namespace mtconnect::pipeline { if (vocab != ControlledVocabularies.end()) { auto sv = std::get_if(&value); - auto &lits = vocab->second; + auto& lits = vocab->second; if (lits.size() != 0 && sv != nullptr) { auto lit = lits.find(*sv); @@ -105,7 +105,7 @@ namespace mtconnect::pipeline { { obs->setProperty("quality", std::string("INVALID")); // Log once - auto &id = di->getId(); + auto& id = di->getId(); if (m_logOnce.count(id) < 1) { LOG(warning) << "DataItem '" << id << "': Invalid value for '" << obs->getName() << "': '" @@ -128,7 +128,7 @@ namespace mtconnect::pipeline { protected: // Logging Context std::set m_logOnce; - PipelineContract *m_contract; + PipelineContract* m_contract; std::unordered_map m_dataItemMap; }; } // namespace mtconnect::pipeline diff --git a/src/mtconnect/printer/json_printer.cpp b/src/mtconnect/printer/json_printer.cpp index 3f8d5c75..bb4284f8 100644 --- a/src/mtconnect/printer/json_printer.cpp +++ b/src/mtconnect/printer/json_printer.cpp @@ -59,13 +59,14 @@ namespace mtconnect::printer { } template - inline void header(AutoJsonObject &obj, const string &version, const string &hostname, + inline void header(AutoJsonObject& obj, const string& version, const string& hostname, const uint64_t instanceId, const unsigned int bufferSize, - const string &schemaVersion, const string modelChangeTime, bool validation, - const std::optional &requestId) + const string& schemaVersion, const string modelChangeTime, bool validation, + const std::optional& requestId) { - obj.AddPairs("version", version, "creationTime", getCurrentTime(GMT_UV_SEC), "testIndicator", false, - "instanceId", instanceId, "sender", hostname, "schemaVersion", schemaVersion); + obj.AddPairs("version", version, "creationTime", getCurrentTime(GMT_UV_SEC), "testIndicator", + false, "instanceId", instanceId, "sender", hostname, "schemaVersion", + schemaVersion); if (IntSchemaVersion(schemaVersion) >= SCHEMA_VERSION(1, 7)) obj.AddPairs("deviceModelChangeTime", modelChangeTime); @@ -78,12 +79,12 @@ namespace mtconnect::printer { } template - inline void probeAssetHeader(AutoJsonObject &obj, const string &version, - const string &hostname, const uint64_t instanceId, + inline void probeAssetHeader(AutoJsonObject& obj, const string& version, + const string& hostname, const uint64_t instanceId, const unsigned int bufferSize, const unsigned int assetBufferSize, - const unsigned int assetCount, const string &schemaVersion, + const unsigned int assetCount, const string& schemaVersion, const string modelChangeTime, const bool validation, - const std::optional &requestId) + const std::optional& requestId) { header(obj, version, hostname, instanceId, bufferSize, schemaVersion, modelChangeTime, validation, requestId); @@ -91,12 +92,12 @@ namespace mtconnect::printer { } template - inline void streamHeader(AutoJsonObject &obj, const string &version, const string &hostname, + inline void streamHeader(AutoJsonObject& obj, const string& version, const string& hostname, const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSequence, const uint64_t firstSequence, - const uint64_t lastSequence, const string &schemaVersion, + const uint64_t lastSequence, const string& schemaVersion, const string modelChangeTime, const bool validation, - const std::optional &requestId) + const std::optional& requestId) { header(obj, version, hostname, instanceId, bufferSize, schemaVersion, modelChangeTime, validation, requestId); @@ -105,12 +106,12 @@ namespace mtconnect::printer { } template - inline void toJson(T1 &writer, const string &collection, T2 &list) + inline void toJson(T1& writer, const string& collection, T2& list) { if (!list.empty()) { AutoJsonArray ary(writer, collection); - for (auto &item : list) + for (auto& item : list) { // items.emplace_back(toJson(item)); } @@ -118,7 +119,7 @@ namespace mtconnect::printer { } std::string JsonPrinter::printErrors(const uint64_t instanceId, const unsigned int bufferSize, - const uint64_t nextSeq, const entity::EntityList &list, + const uint64_t nextSeq, const entity::EntityList& list, bool pretty, const std::optional requestId) const { @@ -126,7 +127,7 @@ namespace mtconnect::printer { auto version = IntSchemaVersion(*m_schemaVersion); StringBuffer output; - RenderJson(output, m_pretty || pretty, [&](auto &writer) { + RenderJson(output, m_pretty || pretty, [&](auto& writer) { entity::JsonPrinter printer(writer, m_jsonVersion); AutoJsonObject obj(writer); @@ -150,7 +151,7 @@ namespace mtconnect::printer { entity::EntityList errors; if (version < SCHEMA_VERSION(2, 6)) { - for (auto &err : list) + for (auto& err : list) { auto re = dynamic_pointer_cast(err); errors.emplace_back(re->makeLegacyError()); @@ -169,15 +170,15 @@ namespace mtconnect::printer { std::string JsonPrinter::printProbe(const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, const unsigned int assetBufferSize, const unsigned int assetCount, - const std::list &devices, - const std::map *count, + const std::list& devices, + const std::map* count, bool includeHidden, bool pretty, const std::optional requestId) const { defaultSchemaVersion(); StringBuffer output; - RenderJson(output, m_pretty || pretty, [&](auto &writer) { + RenderJson(output, m_pretty || pretty, [&](auto& writer) { entity::JsonPrinter printer(writer, m_jsonVersion, includeHidden); AutoJsonObject top(writer); @@ -204,14 +205,14 @@ namespace mtconnect::printer { } std::string JsonPrinter::printAssets(const uint64_t instanceId, const unsigned int bufferSize, - const unsigned int assetCount, const asset::AssetList &asset, + const unsigned int assetCount, const asset::AssetList& asset, bool pretty, const std::optional requestId) const { defaultSchemaVersion(); StringBuffer output; - RenderJson(output, m_pretty || pretty, [&](auto &writer) { + RenderJson(output, m_pretty || pretty, [&](auto& writer) { entity::JsonPrinter printer(writer, m_jsonVersion); AutoJsonObject top(writer); @@ -245,7 +246,7 @@ namespace mtconnect::printer { /// Caches the data item, component, category, and device associated with the observation struct ObservationRef { - ObservationRef(const ObservationPtr &obs) : m_observation(obs) + ObservationRef(const ObservationPtr& obs) : m_observation(obs) { m_dataItem = obs->getDataItem(); m_category = m_dataItem->getCategory(); @@ -277,7 +278,7 @@ namespace mtconnect::printer { const_mem_fun>>>>; template - void printSampleVersion1(T &writer, uint32_t jsonVersion, ObservationMap &observations) + void printSampleVersion1(T& writer, uint32_t jsonVersion, ObservationMap& observations) { using WriterType = decltype(writer); using StackType = JsonStack; @@ -291,7 +292,7 @@ namespace mtconnect::printer { std::string_view componentId; int32_t category = -1; - for (auto &ref : observations) + for (auto& ref : observations) { if (ref.getDeviceId() != deviceId) { @@ -338,7 +339,7 @@ namespace mtconnect::printer { } template - void printSampleVersion2(T &writer, uint32_t jsonVersion, ObservationMap &observations) + void printSampleVersion2(T& writer, uint32_t jsonVersion, ObservationMap& observations) { using WriterType = decltype(writer); using StackType = JsonStack; @@ -353,7 +354,7 @@ namespace mtconnect::printer { int32_t category = -1; std::string_view obsType; - for (auto &ref : observations) + for (auto& ref : observations) { if (ref.getDeviceId() != deviceId) { @@ -411,14 +412,14 @@ namespace mtconnect::printer { std::string JsonPrinter::printSample(const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, const uint64_t firstSeq, - const uint64_t lastSeq, ObservationList &observations, + const uint64_t lastSeq, ObservationList& observations, bool pretty, const std::optional requestId) const { defaultSchemaVersion(); StringBuffer output; - RenderJson(output, m_pretty || pretty, [&](auto &writer) { + RenderJson(output, m_pretty || pretty, [&](auto& writer) { AutoJsonObject top(writer); if (m_streamsSchema) top.AddPairs("$schema", *m_streamsSchema); @@ -439,7 +440,7 @@ namespace mtconnect::printer { { // Order the observations by Device, Component, Category, Observation Type, and Sequence ObservationMap obs; - for (const auto &o : observations) + for (const auto& o : observations) { if (!o->isOrphan()) obs.emplace(o); diff --git a/src/mtconnect/printer/json_printer.hpp b/src/mtconnect/printer/json_printer.hpp index 43af03c7..961cc224 100644 --- a/src/mtconnect/printer/json_printer.hpp +++ b/src/mtconnect/printer/json_printer.hpp @@ -32,24 +32,24 @@ namespace mtconnect::printer { std::string printErrors( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, - const entity::EntityList &list, bool pretty = false, + const entity::EntityList& list, bool pretty = false, const std::optional requestId = std::nullopt) const override; std::string printProbe( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, const unsigned int assetBufferSize, const unsigned int assetCount, - const std::list &devices, const std::map *count = nullptr, + const std::list& devices, const std::map* count = nullptr, bool includeHidden = false, bool pretty = false, const std::optional requestId = std::nullopt) const override; std::string printSample( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, - const uint64_t firstSeq, const uint64_t lastSeq, observation::ObservationList &results, + const uint64_t firstSeq, const uint64_t lastSeq, observation::ObservationList& results, bool pretty = false, const std::optional requestId = std::nullopt) const override; std::string printAssets( const uint64_t anInstanceId, const unsigned int bufferSize, const unsigned int assetCount, - const asset::AssetList &asset, bool pretty = false, + const asset::AssetList& asset, bool pretty = false, const std::optional requestId = std::nullopt) const override; std::string mimeType() const override { return "application/mtconnect+json"; } @@ -57,36 +57,36 @@ namespace mtconnect::printer { /// @brief Add JSON Schema location for Devices Document /// @param url The url referencing the schema - void setDevicesSchema(const std::string &url) { m_devicesSchema = url; } + void setDevicesSchema(const std::string& url) { m_devicesSchema = url; } /// @brief Add JSON Schema location for Streams Document /// @param url The url referencing the schema - void setStreamsSchema(const std::string &url) { m_streamsSchema = url; } + void setStreamsSchema(const std::string& url) { m_streamsSchema = url; } /// @brief Add JSON Schema location for Assets Document /// @param url The url referencing the schema - void setAssetsSchema(const std::string &url) { m_assetsSchema = url; } + void setAssetsSchema(const std::string& url) { m_assetsSchema = url; } /// @brief Add JSON Schema location for Errors Document /// @param url The url referencing the schema /// @param location the file location of the schema file - void setErrorSchema(const std::string &url) { m_errorSchema = url; } + void setErrorSchema(const std::string& url) { m_errorSchema = url; } /// @brief Get the JSON Schema url for the Devices Document /// @returns The url if the schema is set, otherwise `std::nullopt` - const auto &getDevicesSchema() const { return m_devicesSchema; } + const auto& getDevicesSchema() const { return m_devicesSchema; } /// @brief Get the JSON Schema url for the Streams Document /// @returns The url if the schema is set, otherwise `std::nullopt` - const auto &getStreamsSchema() const { return m_streamsSchema; } + const auto& getStreamsSchema() const { return m_streamsSchema; } /// @brief Get the JSON Schema url for the Assets Document /// @returns The url if the schema is set, otherwise `std::nullopt` - const auto &getAssetsSchema() const { return m_assetsSchema; } + const auto& getAssetsSchema() const { return m_assetsSchema; } /// @brief Get the JSON Schema url for the Error Document /// @returns The url if the schema is set, otherwise `std::nullopt` - const auto &getErrorSchema() const { return m_errorSchema; } + const auto& getErrorSchema() const { return m_errorSchema; } protected: std::optional m_devicesSchema; diff --git a/src/mtconnect/printer/json_printer_helper.hpp b/src/mtconnect/printer/json_printer_helper.hpp index 79692cfa..3b6b5258 100644 --- a/src/mtconnect/printer/json_printer_helper.hpp +++ b/src/mtconnect/printer/json_printer_helper.hpp @@ -38,20 +38,20 @@ namespace mtconnect::printer { public: /// @brief Create a helper using a writer /// @param[in] writer a reference to the writer - JsonHelper(T &writer) : m_writer(writer) {} + JsonHelper(T& writer) : m_writer(writer) {} /// @name Key methods /// @{ /// @brief Wrapper around the rapidjson Key writer methods /// @param[in] s string for the key - void Key(const char *s) { m_writer.Key(s); } + void Key(const char* s) { m_writer.Key(s); } /// @brief Wrapper around the rapidjson Key writer methods /// @param[in] s string for the key - void Key(const std::string &s) { m_writer.Key(s.data(), rapidjson::SizeType(s.size())); } + void Key(const std::string& s) { m_writer.Key(s.data(), rapidjson::SizeType(s.size())); } /// @brief Wrapper around the rapidjson Key writer methods /// @param[in] s string for the key - void Key(const std::string_view &s) { m_writer.Key(s.data(), rapidjson::SizeType(s.size())); } + void Key(const std::string_view& s) { m_writer.Key(s.data(), rapidjson::SizeType(s.size())); } /// @} /// @name Object methods @@ -107,16 +107,16 @@ namespace mtconnect::printer { void Add(uint64_t i) { m_writer.Uint64(i); } /// @brief Add a string /// @param[in] s a null terminated string - void Add(const char *s) { m_writer.String(s); } + void Add(const char* s) { m_writer.String(s); } /// @brief Add a string view /// @param[in] s a string - void Add(const std::string_view &s) + void Add(const std::string_view& s) { m_writer.String(s.data(), rapidjson::SizeType(s.size())); } /// @brief Add a string /// @param[in] s a string - void Add(const std::string &s) { m_writer.String(s.data(), rapidjson::SizeType(s.size())); } + void Add(const std::string& s) { m_writer.String(s.data(), rapidjson::SizeType(s.size())); } /// @} /// @brief Add pairs of values @@ -133,7 +133,7 @@ namespace mtconnect::printer { /// @tparam T2 Value type /// @tparam R parameter pack for the rest of the values template - void AddPairs(const T1 &key, const T2 &value, R... rest) + void AddPairs(const T1& key, const T2& value, R... rest) { Key(key); Add(value); @@ -153,7 +153,7 @@ namespace mtconnect::printer { /// @tparam T1 Key type /// @tparam T2 Value type template - void AddPairs(const T1 &v1, const T2 &v2) + void AddPairs(const T1& v1, const T2& v2) { Key(v1); Add(v2); @@ -161,7 +161,7 @@ namespace mtconnect::printer { protected: /// @brief The rapidjson writer - T &m_writer; + T& m_writer; }; /// @brief Provides rapidjson automatic StartObject and EndObject when the object goes out of @@ -177,7 +177,7 @@ namespace mtconnect::printer { /// @brief Start an object as part of another objecy where this object is the value of `key` /// @param[in] writer the rapidjson writer /// @param[in] key the parent objects key - AutoJsonObject(T &writer, const char *key) : base(writer) + AutoJsonObject(T& writer, const char* key) : base(writer) { base::Key(key); base::StartObject(); @@ -186,7 +186,7 @@ namespace mtconnect::printer { /// @brief Create a object, but only start it if `start` is true /// @param[in] writer the rapidjson writer /// @param[in] start flag to start the array - AutoJsonObject(T &writer, bool start = true) : base(writer) + AutoJsonObject(T& writer, bool start = true) : base(writer) { if (start) base::StartObject(); @@ -197,7 +197,7 @@ namespace mtconnect::printer { /// @brief Start an object as part of another objecy where this object is the value of `key` /// @param[in] writer the rapidjson writer /// @param[in] key the parent objects key - AutoJsonObject(T &writer, const std::string_view key) : base(writer) + AutoJsonObject(T& writer, const std::string_view key) : base(writer) { base::Key(key.data()); base::StartObject(); @@ -217,13 +217,13 @@ namespace mtconnect::printer { /// @brief Check if the key has changed /// @param[in] key key to check - bool check(const std::string_view &key) { return m_key != key; } + bool check(const std::string_view& key) { return m_key != key; } /// @brief Check if the key has changed and end an open object and start a new one /// @param[in] key key to check /// @param[in] addKey if `true`, add an object as the value of the parent object using key as /// the key - bool reset(const std::string_view &key, bool addKey = true) + bool reset(const std::string_view& key, bool addKey = true) { if (m_key != key) { @@ -276,7 +276,7 @@ namespace mtconnect::printer { /// @brief Create a array, but only start it if `start` is true /// @param[in] writer the rapidjson writer /// @param[in] start flag to start the array - AutoJsonArray(T &writer, bool start = true) : base(writer) + AutoJsonArray(T& writer, bool start = true) : base(writer) { if (start) base::StartArray(); @@ -287,7 +287,7 @@ namespace mtconnect::printer { /// @brief Start an array as part of another objecy where this object is the value of `key` /// @param[in] writer the rapidjson writer /// @param[in] key the parent objects key - AutoJsonArray(T &writer, const char *key) : base(writer) + AutoJsonArray(T& writer, const char* key) : base(writer) { base::Key(key); base::StartArray(); @@ -296,7 +296,7 @@ namespace mtconnect::printer { /// @brief Start an array as part of another objecy where this object is the value of `key` /// @param[in] writer the rapidjson writer /// @param[in] key the parent objects key - AutoJsonArray(T &writer, const std::string_view key) : base(writer) + AutoJsonArray(T& writer, const std::string_view key) : base(writer) { base::Key(key.data()); base::StartArray(); @@ -342,7 +342,7 @@ namespace mtconnect::printer { /// @tparam T the type of the output buffer /// @tparam T2 the type of the lambda template - inline void RenderJson(T &output, bool pretty, T2 &&func) + inline void RenderJson(T& output, bool pretty, T2&& func) { if (pretty) { @@ -390,7 +390,7 @@ namespace mtconnect::printer { /// @brief Create a stack for a rapidjson writer /// @param[in] writer the rapidjson writer - JsonStack(W &writer) : base(writer) {} + JsonStack(W& writer) : base(writer) {} /// @brief Add a new object to the stack /// @param[in] key optional key for the parent object @@ -399,7 +399,7 @@ namespace mtconnect::printer { if (!key.empty()) base::Key(key); - auto &member = m_stack.emplace_back(); + auto& member = m_stack.emplace_back(); member.m_object.emplace(base::m_writer); } @@ -410,7 +410,7 @@ namespace mtconnect::printer { if (!key.empty()) base::Key(key); - auto &member = m_stack.emplace_back(); + auto& member = m_stack.emplace_back(); member.m_array.emplace(base::m_writer); } diff --git a/src/mtconnect/printer/printer.hpp b/src/mtconnect/printer/printer.hpp index 15f0b27e..3e28f4e5 100644 --- a/src/mtconnect/printer/printer.hpp +++ b/src/mtconnect/printer/printer.hpp @@ -80,7 +80,7 @@ namespace mtconnect { /// @return the MTConnect Error document virtual std::string printErrors( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, - const entity::EntityList &list, bool pretty = false, + const entity::EntityList& list, bool pretty = false, const std::optional requestId = std::nullopt) const = 0; /// @brief Generate an MTConnect Devices document /// @param[in] instanceId the instance id @@ -94,7 +94,7 @@ namespace mtconnect { virtual std::string printProbe( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, const unsigned int assetBufferSize, const unsigned int assetCount, - const std::list &devices, const std::map *count = nullptr, + const std::list& devices, const std::map* count = nullptr, bool includeHidden = false, bool pretty = false, const std::optional requestId = std::nullopt) const = 0; /// @brief Print a MTConnect Streams document @@ -107,7 +107,7 @@ namespace mtconnect { /// @return the MTConnect Streams document virtual std::string printSample( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, - const uint64_t firstSeq, const uint64_t lastSeq, observation::ObservationList &results, + const uint64_t firstSeq, const uint64_t lastSeq, observation::ObservationList& results, bool pretty = false, const std::optional requestId = std::nullopt) const = 0; /// @brief Generate an MTConnect Assets document /// @param[in] anInstanceId the instance id @@ -117,32 +117,32 @@ namespace mtconnect { /// @return the MTConnect Assets document virtual std::string printAssets( const uint64_t anInstanceId, const unsigned int bufferSize, const unsigned int assetCount, - asset::AssetList const &asset, bool pretty = false, + asset::AssetList const& asset, bool pretty = false, const std::optional requestId = std::nullopt) const = 0; /// @brief get the mime type for the documents /// @return the mime type virtual std::string mimeType() const = 0; /// @brief Set the last model change time /// @param t the time - void setModelChangeTime(const std::string &t) { m_modelChangeTime = t; } + void setModelChangeTime(const std::string& t) { m_modelChangeTime = t; } /// @brief Get the last model change time /// @return the time - const std::string &getModelChangeTime() { return m_modelChangeTime; } + const std::string& getModelChangeTime() { return m_modelChangeTime; } /// @brief set the schema version we are generating /// @param s the version - void setSchemaVersion(const std::string &s) { m_schemaVersion = s; } + void setSchemaVersion(const std::string& s) { m_schemaVersion = s; } /// @brief Get the schema version /// @return the schema version - const auto &getSchemaVersion() const { return m_schemaVersion; } + const auto& getSchemaVersion() const { return m_schemaVersion; } /// @brief sets the sener name for the header /// @param name the name of the sender - void setSenderName(const std::string &s) { m_senderName = s; } + void setSenderName(const std::string& s) { m_senderName = s; } /// @brief gets the sender name /// @returns the name of the sender in the header - const auto &getSenderName() const { return m_senderName; } + const auto& getSenderName() const { return m_senderName; } /// @brief Use the agent version to default the schema version void defaultSchemaVersion() const @@ -151,7 +151,7 @@ namespace mtconnect { { std::string ver = std::to_string(AGENT_VERSION_MAJOR) + "." + std::to_string(AGENT_VERSION_MINOR); - const_cast(this)->m_schemaVersion.emplace(ver); + const_cast(this)->m_schemaVersion.emplace(ver); } } diff --git a/src/mtconnect/printer/xml_printer.cpp b/src/mtconnect/printer/xml_printer.cpp index dc44bcd7..467d2b23 100644 --- a/src/mtconnect/printer/xml_printer.cpp +++ b/src/mtconnect/printer/xml_printer.cpp @@ -51,8 +51,8 @@ namespace mtconnect::printer { NAMED_SCOPE("xml.printer"); } - void XmlPrinter::addDevicesNamespace(const std::string &urn, const std::string &location, - const std::string &prefix) + void XmlPrinter::addDevicesNamespace(const std::string& urn, const std::string& location, + const std::string& prefix) { pair item; item.second.mUrn = urn; @@ -66,7 +66,7 @@ namespace mtconnect::printer { void XmlPrinter::clearDevicesNamespaces() { m_devicesNamespaces.clear(); } - string XmlPrinter::getDevicesUrn(const std::string &prefix) + string XmlPrinter::getDevicesUrn(const std::string& prefix) { auto ns = m_devicesNamespaces.find(prefix); if (ns != m_devicesNamespaces.end()) @@ -75,7 +75,7 @@ namespace mtconnect::printer { return ""; } - string XmlPrinter::getDevicesLocation(const std::string &prefix) + string XmlPrinter::getDevicesLocation(const std::string& prefix) { auto ns = m_devicesNamespaces.find(prefix); if (ns != m_devicesNamespaces.end()) @@ -84,8 +84,8 @@ namespace mtconnect::printer { return ""; } - void XmlPrinter::addErrorNamespace(const std::string &urn, const std::string &location, - const std::string &prefix) + void XmlPrinter::addErrorNamespace(const std::string& urn, const std::string& location, + const std::string& prefix) { pair item; item.second.mUrn = urn; @@ -99,7 +99,7 @@ namespace mtconnect::printer { void XmlPrinter::clearErrorNamespaces() { m_errorNamespaces.clear(); } - string XmlPrinter::getErrorUrn(const std::string &prefix) + string XmlPrinter::getErrorUrn(const std::string& prefix) { auto ns = m_errorNamespaces.find(prefix); if (ns != m_errorNamespaces.end()) @@ -108,7 +108,7 @@ namespace mtconnect::printer { return ""; } - string XmlPrinter::getErrorLocation(const std::string &prefix) + string XmlPrinter::getErrorLocation(const std::string& prefix) { auto ns = m_errorNamespaces.find(prefix); if (ns != m_errorNamespaces.end()) @@ -117,8 +117,8 @@ namespace mtconnect::printer { return ""; } - void XmlPrinter::addStreamsNamespace(const std::string &urn, const std::string &location, - const std::string &prefix) + void XmlPrinter::addStreamsNamespace(const std::string& urn, const std::string& location, + const std::string& prefix) { pair item; item.second.mUrn = urn; @@ -132,7 +132,7 @@ namespace mtconnect::printer { void XmlPrinter::clearStreamsNamespaces() { m_streamsNamespaces.clear(); } - string XmlPrinter::getStreamsUrn(const std::string &prefix) + string XmlPrinter::getStreamsUrn(const std::string& prefix) { auto ns = m_streamsNamespaces.find(prefix); if (ns != m_streamsNamespaces.end()) @@ -141,7 +141,7 @@ namespace mtconnect::printer { return ""; } - string XmlPrinter::getStreamsLocation(const std::string &prefix) + string XmlPrinter::getStreamsLocation(const std::string& prefix) { auto ns = m_streamsNamespaces.find(prefix); if (ns != m_streamsNamespaces.end()) @@ -150,8 +150,8 @@ namespace mtconnect::printer { return ""; } - void XmlPrinter::addAssetsNamespace(const std::string &urn, const std::string &location, - const std::string &prefix) + void XmlPrinter::addAssetsNamespace(const std::string& urn, const std::string& location, + const std::string& prefix) { pair item; item.second.mUrn = urn; @@ -165,7 +165,7 @@ namespace mtconnect::printer { void XmlPrinter::clearAssetsNamespaces() { m_assetNamespaces.clear(); } - string XmlPrinter::getAssetsUrn(const std::string &prefix) + string XmlPrinter::getAssetsUrn(const std::string& prefix) { auto ns = m_assetNamespaces.find(prefix); if (ns != m_assetNamespaces.end()) @@ -174,7 +174,7 @@ namespace mtconnect::printer { return ""; } - string XmlPrinter::getAssetsLocation(const std::string &prefix) + string XmlPrinter::getAssetsLocation(const std::string& prefix) { auto ns = m_assetNamespaces.find(prefix); if (ns != m_assetNamespaces.end()) @@ -183,16 +183,16 @@ namespace mtconnect::printer { return ""; } - void XmlPrinter::setStreamStyle(const std::string &style) { m_streamsStyle = style; } + void XmlPrinter::setStreamStyle(const std::string& style) { m_streamsStyle = style; } - void XmlPrinter::setDevicesStyle(const std::string &style) { m_devicesStyle = style; } + void XmlPrinter::setDevicesStyle(const std::string& style) { m_devicesStyle = style; } - void XmlPrinter::setErrorStyle(const std::string &style) { m_errorStyle = style; } + void XmlPrinter::setErrorStyle(const std::string& style) { m_errorStyle = style; } - void XmlPrinter::setAssetsStyle(const std::string &style) { m_assetStyle = style; } + void XmlPrinter::setAssetsStyle(const std::string& style) { m_assetStyle = style; } std::string XmlPrinter::printErrors(const uint64_t instanceId, const unsigned int bufferSize, - const uint64_t nextSeq, const entity::EntityList &list, + const uint64_t nextSeq, const entity::EntityList& list, bool pretty, const std::optional requestId) const { string ret; @@ -209,7 +209,7 @@ namespace mtconnect::printer { entity::XmlPrinter printer; auto version = IntSchemaVersion(*m_schemaVersion); - for (auto &e : list) + for (auto& e : list) { entity::EntityPtr err {e}; if (version < SCHEMA_VERSION(2, 6)) @@ -225,7 +225,7 @@ namespace mtconnect::printer { // Cleanup ret = writer.getContent(); } - catch (const XmlError &error) + catch (const XmlError& error) { LOG(error) << "printError: " << error.what(); } @@ -239,8 +239,8 @@ namespace mtconnect::printer { string XmlPrinter::printProbe(const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, const unsigned int assetBufferSize, - const unsigned int assetCount, const list &deviceList, - const std::map *count, bool includeHidden, + const unsigned int assetCount, const list& deviceList, + const std::map* count, bool includeHidden, bool pretty, const std::optional requestId) const { string ret; @@ -256,14 +256,14 @@ namespace mtconnect::printer { AutoElement devices(writer, "Devices"); entity::XmlPrinter printer(includeHidden); - for (auto &device : deviceList) + for (auto& device : deviceList) printer.print(writer, device, m_deviceNsSet); } closeElement(writer); // MTConnectDevices ret = writer.getContent(); } - catch (const XmlError &error) + catch (const XmlError& error) { LOG(error) << "printProbe: " << error.what(); } @@ -287,7 +287,7 @@ namespace mtconnect::printer { ret = writer.getContent(); } - catch (const XmlError &error) + catch (const XmlError& error) { LOG(error) << "printProbe: " << error.what(); } @@ -301,7 +301,7 @@ namespace mtconnect::printer { string XmlPrinter::printSample(const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, const uint64_t firstSeq, - const uint64_t lastSeq, ObservationList &observations, bool pretty, + const uint64_t lastSeq, ObservationList& observations, bool pretty, const std::optional requestId) const { string ret; @@ -326,13 +326,13 @@ namespace mtconnect::printer { { AutoElement categoryElement(writer); - for (auto &observation : observations) + for (auto& observation : observations) { if (!observation->isOrphan()) { - const auto &dataItem = observation->getDataItem(); - const auto &component = dataItem->getComponent(); - const auto &device = component->getDevice(); + const auto& dataItem = observation->getDataItem(); + const auto& component = dataItem->getComponent(); + const auto& device = component->getDevice(); if (deviceElement.key() != device->getId()) { @@ -369,7 +369,7 @@ namespace mtconnect::printer { ret = writer.getContent(); } - catch (const XmlError &error) + catch (const XmlError& error) { LOG(error) << "printSample: " << error.what(); } @@ -382,7 +382,7 @@ namespace mtconnect::printer { } string XmlPrinter::printAssets(const uint64_t instanceId, const unsigned int bufferSize, - const unsigned int assetCount, const AssetList &asset, bool pretty, + const unsigned int assetCount, const AssetList& asset, bool pretty, const std::optional requestId) const { string ret; @@ -396,7 +396,7 @@ namespace mtconnect::printer { AutoElement ele(writer, "Assets"); entity::XmlPrinter printer; - for (const auto &asset : asset) + for (const auto& asset : asset) { printer.print(writer, asset, m_assetNsSet); } @@ -404,7 +404,7 @@ namespace mtconnect::printer { ret = writer.getContent(); } - catch (const XmlError &error) + catch (const XmlError& error) { LOG(error) << "printAssets: " << error.what(); } @@ -426,7 +426,7 @@ namespace mtconnect::printer { const uint64_t instanceId, const unsigned int bufferSize, const unsigned int assetBufferSize, const unsigned int assetCount, const uint64_t nextSeq, const uint64_t firstSeq, - const uint64_t lastSeq, const map *count, + const uint64_t lastSeq, const map* count, const std::optional requestId) const { THROW_IF_XML2_ERROR(xmlTextWriterStartDocument(writer, nullptr, "UTF-8", nullptr)); @@ -434,7 +434,7 @@ namespace mtconnect::printer { // TODO: Cache the locations and header attributes. // Write the root element string xmlType, style; - const map *namespaces; + const map* namespaces; switch (aType) { @@ -494,7 +494,7 @@ namespace mtconnect::printer { string mtcLocation; // Add in the other namespaces if they exist - for (const auto &ns : *namespaces) + for (const auto& ns : *namespaces) { // Skip the mtconnect ns (always m) if (ns.first != "m") @@ -584,7 +584,7 @@ namespace mtconnect::printer { { AutoElement ele(writer, "AssetCounts"); - for (const auto &pair : *count) + for (const auto& pair : *count) { addSimpleElement(writer, "AssetCount", to_string(pair.second), {{"assetType", pair.first}}); } diff --git a/src/mtconnect/printer/xml_printer.hpp b/src/mtconnect/printer/xml_printer.hpp index 5424b669..fda430ec 100644 --- a/src/mtconnect/printer/xml_printer.hpp +++ b/src/mtconnect/printer/xml_printer.hpp @@ -27,7 +27,7 @@ extern "C" { using xmlTextWriter = struct _xmlTextWriter; - using xmlTextWriterPtr = xmlTextWriter *; + using xmlTextWriterPtr = xmlTextWriter*; } namespace mtconnect { @@ -45,24 +45,24 @@ namespace mtconnect { std::string printErrors( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, - const entity::EntityList &list, bool pretty = false, + const entity::EntityList& list, bool pretty = false, const std::optional requestId = std::nullopt) const override; std::string printProbe( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, const unsigned int assetBufferSize, const unsigned int assetCount, - const std::list &devices, const std::map *count = nullptr, + const std::list& devices, const std::map* count = nullptr, bool includeHidden = false, bool pretty = false, const std::optional requestId = std::nullopt) const override; std::string printSample( const uint64_t instanceId, const unsigned int bufferSize, const uint64_t nextSeq, - const uint64_t firstSeq, const uint64_t lastSeq, observation::ObservationList &results, + const uint64_t firstSeq, const uint64_t lastSeq, observation::ObservationList& results, bool pretty = false, const std::optional requestId = std::nullopt) const override; std::string printAssets( const uint64_t anInstanceId, const unsigned int bufferSize, const unsigned int assetCount, - const asset::AssetList &asset, bool pretty = false, + const asset::AssetList& asset, bool pretty = false, const std::optional requestId = std::nullopt) const override; std::string mimeType() const override { return "application/xml"; } @@ -75,39 +75,39 @@ namespace mtconnect { /// @param urn the namespace URN /// @param location the location of the schema file /// @param prefix the namespace prefix - void addDevicesNamespace(const std::string &urn, const std::string &location, - const std::string &prefix); + void addDevicesNamespace(const std::string& urn, const std::string& location, + const std::string& prefix); /// @brief Add a Error XML device namespace /// @param urn the namespace URN /// @param location the location of the schema file /// @param prefix the namespace prefix - void addErrorNamespace(const std::string &urn, const std::string &location, - const std::string &prefix); + void addErrorNamespace(const std::string& urn, const std::string& location, + const std::string& prefix); /// @brief Add a Streams XML device namespace /// @param urn the namespace URN /// @param location the location of the schema file /// @param prefix the namespace prefix - void addStreamsNamespace(const std::string &urn, const std::string &location, - const std::string &prefix); + void addStreamsNamespace(const std::string& urn, const std::string& location, + const std::string& prefix); /// @brief Add a Assets XML device namespace /// @param urn the namespace URN /// @param location the location of the schema file /// @param prefix the namespace prefix - void addAssetsNamespace(const std::string &urn, const std::string &location, - const std::string &prefix); + void addAssetsNamespace(const std::string& urn, const std::string& location, + const std::string& prefix); /// @brief Set the Devices style sheet to add as a processing instruction /// @param style the stype sheet - void setDevicesStyle(const std::string &style); + void setDevicesStyle(const std::string& style); /// @brief Set the Streams style sheet to add as a processing instruction /// @param style the stype sheet - void setStreamStyle(const std::string &style); + void setStreamStyle(const std::string& style); /// @brief Set the Assets style sheet to add as a processing instruction /// @param style the stype sheet - void setAssetsStyle(const std::string &style); + void setAssetsStyle(const std::string& style); /// @brief Set the Error style sheet to add as a processing instruction /// @param style the stype sheet - void setErrorStyle(const std::string &style); + void setErrorStyle(const std::string& style); /// @name For testing ///@{ @@ -125,36 +125,36 @@ namespace mtconnect { /// @brief Get the Devices URN for a prefix /// @param[in] prefix the prefix /// @return the URN - std::string getDevicesUrn(const std::string &prefix); + std::string getDevicesUrn(const std::string& prefix); /// @brief Get the Error URN for a prefix /// @param[in] prefix the prefix /// @return the URN - std::string getErrorUrn(const std::string &prefix); + std::string getErrorUrn(const std::string& prefix); /// @brief Get the Streams URN for a prefix /// @param[in] prefix the prefix /// @return the URN - std::string getStreamsUrn(const std::string &prefix); + std::string getStreamsUrn(const std::string& prefix); /// @brief Get the Assets URN for a prefix /// @param[in] prefix the prefix /// @return the URN - std::string getAssetsUrn(const std::string &prefix); + std::string getAssetsUrn(const std::string& prefix); /// @brief Get the Devices location for a prefix /// @param[in] prefix the prefix /// @return the location - std::string getDevicesLocation(const std::string &prefix); + std::string getDevicesLocation(const std::string& prefix); /// @brief Get the Error location for a prefix /// @param[in] prefix the prefix /// @return the location - std::string getErrorLocation(const std::string &prefix); + std::string getErrorLocation(const std::string& prefix); /// @brief Get the Streams location for a prefix /// @param[in] prefix the prefix /// @return the location - std::string getStreamsLocation(const std::string &prefix); + std::string getStreamsLocation(const std::string& prefix); /// @brief Get the Assets location for a prefix /// @param[in] prefix the prefix /// @return the location - std::string getAssetsLocation(const std::string &prefix); + std::string getAssetsLocation(const std::string& prefix); protected: enum EDocumentType @@ -176,12 +176,12 @@ namespace mtconnect { const unsigned int bufferSize, const unsigned int assetBufferSize, const unsigned int assetCount, const uint64_t nextSeq, const uint64_t firstSeq = 0, const uint64_t lastSeq = 0, - const std::map *counts = nullptr, + const std::map* counts = nullptr, const std::optional requestId = std::nullopt) const; // Helper to print individual components and details void printProbeHelper(xmlTextWriterPtr writer, device_model::ComponentPtr component, - const char *name) const; + const char* name) const; void printDataItem(xmlTextWriterPtr writer, DataItemPtr dataItem) const; void addObservation(xmlTextWriterPtr writer, observation::ObservationPtr result) const; diff --git a/src/mtconnect/printer/xml_printer_helper.hpp b/src/mtconnect/printer/xml_printer_helper.hpp index 297ef80a..79b17c98 100644 --- a/src/mtconnect/printer/xml_printer_helper.hpp +++ b/src/mtconnect/printer/xml_printer_helper.hpp @@ -74,7 +74,7 @@ namespace mtconnect::printer { xmlFreeTextWriter(m_writer); m_writer = nullptr; } - return std::string((char *)xmlBufferContent(m_buf), xmlBufferLength(m_buf)); + return std::string((char*)xmlBufferContent(m_buf), xmlBufferLength(m_buf)); } protected: @@ -85,7 +85,7 @@ namespace mtconnect::printer { /// @brief Wrapper to create an XML open element /// @param writer the writer /// @param name the name of the element - static inline void openElement(xmlTextWriterPtr writer, const char *name) + static inline void openElement(xmlTextWriterPtr writer, const char* name) { THROW_IF_XML2_ERROR(xmlTextWriterStartElement(writer, BAD_CAST name)); } @@ -108,7 +108,7 @@ namespace mtconnect::printer { /// @param writer the writer /// @param name name of the element /// @param key optional key if the for closing an element and reopening another element - AutoElement(xmlTextWriterPtr writer, const char *name, std::string key = "") + AutoElement(xmlTextWriterPtr writer, const char* name, std::string key = "") : m_writer(writer), m_name(name), m_key(std::move(key)) { openElement(writer, name); @@ -117,7 +117,7 @@ namespace mtconnect::printer { /// @param writer the writer /// @param name name of the element /// @param key optional key if the for closing an element and reopening another element - AutoElement(xmlTextWriterPtr writer, const std::string &name, std::string key = "") + AutoElement(xmlTextWriterPtr writer, const std::string& name, std::string key = "") : m_writer(writer), m_name(name), m_key(std::move(key)) { openElement(writer, name.c_str()); @@ -126,7 +126,7 @@ namespace mtconnect::printer { /// @param name of the element /// @param key optional key if the for closing an element and reopening another element /// @return `true` if the element was closed and reopened - bool reset(const std::string &name, const std::string &key = "") + bool reset(const std::string& name, const std::string& key = "") { if (name != m_name || m_key != key) { @@ -152,10 +152,10 @@ namespace mtconnect::printer { /// @brief get the key /// @return the key - const std::string &key() const { return m_key; } + const std::string& key() const { return m_key; } /// @brief return the name /// @return the name - const std::string &name() const { return m_name; } + const std::string& name() const { return m_name; } protected: xmlTextWriterPtr m_writer; @@ -166,8 +166,8 @@ namespace mtconnect::printer { /// @param writer the writer /// @param key the attribute name /// @param value the attribute value (empty strings are skipped) - static inline void addAttribute(xmlTextWriterPtr writer, const char *key, - const std::string &value) + static inline void addAttribute(xmlTextWriterPtr writer, const char* key, + const std::string& value) { if (!value.empty()) THROW_IF_XML2_ERROR( @@ -180,7 +180,7 @@ namespace mtconnect::printer { /// @param value the integral value template requires std::integral static inline void addAttribute(xmlTextWriterPtr writer, - const char *key, T value) + const char* key, T value) { auto str = std::format("{}", value); THROW_IF_XML2_ERROR(xmlTextWriterWriteAttribute(writer, BAD_CAST key, BAD_CAST str.c_str())); @@ -190,9 +190,9 @@ namespace mtconnect::printer { /// @param writer the writer /// @param attributes map of key-value attribute pairs static inline void addAttributes(xmlTextWriterPtr writer, - const std::map &attributes) + const std::map& attributes) { - for (const auto &attr : attributes) + for (const auto& attr : attributes) { if (!attr.second.empty()) { @@ -208,9 +208,9 @@ namespace mtconnect::printer { /// @param body text content of the element /// @param attributes optional map of attributes /// @param raw if true, body is written without XML encoding - static inline void addSimpleElement(xmlTextWriterPtr writer, const std::string &element, - const std::string &body, - const std::map &attributes = {}, + static inline void addSimpleElement(xmlTextWriterPtr writer, const std::string& element, + const std::string& body, + const std::map& attributes = {}, bool raw = false) { AutoElement ele(writer, element); @@ -220,7 +220,7 @@ namespace mtconnect::printer { if (!body.empty()) { - xmlChar *text = nullptr; + xmlChar* text = nullptr; if (!raw) text = xmlEncodeEntitiesReentrant(nullptr, BAD_CAST body.c_str()); else diff --git a/src/mtconnect/ruby/embedded.cpp b/src/mtconnect/ruby/embedded.cpp index 97f308d5..e023eec1 100644 --- a/src/mtconnect/ruby/embedded.cpp +++ b/src/mtconnect/ruby/embedded.cpp @@ -64,14 +64,14 @@ namespace mtconnect::ruby { using namespace std::literals; using namespace observation; - RClass *RubyObservation::m_eventClass; - RClass *RubyObservation::m_sampleClass; - RClass *RubyObservation::m_conditionClass; + RClass* RubyObservation::m_eventClass; + RClass* RubyObservation::m_sampleClass; + RClass* RubyObservation::m_conditionClass; std::recursive_mutex RubyVM::m_mutex; - RubyVM *RubyVM::m_vm = nullptr; + RubyVM* RubyVM::m_vm = nullptr; - static mrb_value LoadModule(mrb_state *mrb, mrb_value &filename) + static mrb_value LoadModule(mrb_state* mrb, mrb_value& filename) { auto fname = RSTRING_CSTR(mrb, filename); int ai = mrb_gc_arena_save(mrb); @@ -119,8 +119,8 @@ namespace mtconnect::ruby { } } - Embedded::Embedded(mtconnect::configuration::AgentConfiguration *config, - const ConfigOptions &options) + Embedded::Embedded(mtconnect::configuration::AgentConfiguration* config, + const ConfigOptions& options) : m_agent(config->getAgent()), m_options(options) { using namespace std::filesystem; @@ -173,14 +173,14 @@ namespace mtconnect::ruby { else { LOG(info) << "Resolved module path: " << file; - FILE *fp = nullptr; + FILE* fp = nullptr; try { int save = mrb_gc_arena_save(mrb); mrb_value file = mrb_str_new_cstr(mrb, modulePath->string().c_str()); mrb_bool state = false; mrb_value res = mrb_protect( - mrb, [](mrb_state *mrb, mrb_value filename) { return LoadModule(mrb, filename); }, + mrb, [](mrb_state* mrb, mrb_value filename) { return LoadModule(mrb, filename); }, file, &state); mrb_gc_arena_restore(mrb, save); if (mrb_false_p(res)) diff --git a/src/mtconnect/ruby/embedded.hpp b/src/mtconnect/ruby/embedded.hpp index 906e529e..175c9f99 100644 --- a/src/mtconnect/ruby/embedded.hpp +++ b/src/mtconnect/ruby/embedded.hpp @@ -37,13 +37,13 @@ namespace mtconnect { { public: /// @brief Create an embedded mruby instance - Embedded(configuration::AgentConfiguration *config, const ConfigOptions &options); + Embedded(configuration::AgentConfiguration* config, const ConfigOptions& options); ~Embedded(); protected: - Agent *m_agent; + Agent* m_agent; ConfigOptions m_options; - boost::asio::io_context *m_context = nullptr; + boost::asio::io_context* m_context = nullptr; std::unique_ptr m_rubyVM; }; } // namespace ruby diff --git a/src/mtconnect/ruby/ruby_agent.hpp b/src/mtconnect/ruby/ruby_agent.hpp index ca7de547..3073eecd 100644 --- a/src/mtconnect/ruby/ruby_agent.hpp +++ b/src/mtconnect/ruby/ruby_agent.hpp @@ -33,7 +33,7 @@ namespace mtconnect::ruby { /// @param[in] mrb The ruby state /// @param[in] module Module to instantiate agent class /// @param[in] agent The agent - static void initialize(mrb_state *mrb, RClass *module, Agent *agent) + static void initialize(mrb_state* mrb, RClass* module, Agent* agent) { using namespace std; @@ -47,7 +47,7 @@ namespace mtconnect::ruby { mrb_define_class_method( mrb, module, "agent", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto ivar = mrb_intern_cstr(mrb, "@agent"); return mrb_iv_get(mrb, self, ivar); }, @@ -61,7 +61,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, sourceClass, "name", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto source = MRubySharedPtr::unwrap(mrb, self); return mrb_str_new_cstr(mrb, source->getName().c_str()); }, @@ -69,7 +69,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, sourceClass, "pipeline", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto source = MRubySharedPtr::unwrap(mrb, self); return MRubyPtr::wrap(mrb, "Pipeline", source->getPipeline()); }, @@ -77,11 +77,11 @@ namespace mtconnect::ruby { mrb_define_method( mrb, agentClass, "sources", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto agent = MRubyPtr::unwrap(mrb, self); auto sources = mrb_ary_new(mrb); - for (auto &source : agent->getSources()) + for (auto& source : agent->getSources()) { auto obj = MRubySharedPtr::wrap(mrb, "Source", source); mrb_ary_push(mrb, sources, obj); @@ -93,11 +93,11 @@ namespace mtconnect::ruby { mrb_define_method( mrb, agentClass, "sinks", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto agent = MRubyPtr::unwrap(mrb, self); auto sinks = mrb_ary_new(mrb); - for (auto &sink : agent->getSinks()) + for (auto& sink : agent->getSinks()) { auto obj = MRubySharedPtr::wrap(mrb, "Sink", sink); mrb_ary_push(mrb, sinks, obj); @@ -109,14 +109,14 @@ namespace mtconnect::ruby { mrb_define_method( mrb, agentClass, "devices", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto agent = MRubyPtr::unwrap(mrb, self); auto devices = mrb_ary_new(mrb); auto mod = mrb_module_get(mrb, "MTConnect"); auto klass = mrb_class_get_under(mrb, mod, "Device"); - for (auto &device : agent->getDevices()) + for (auto& device : agent->getDevices()) { auto obj = MRubySharedPtr::wrap(mrb, klass, device); mrb_ary_push(mrb, devices, obj); @@ -128,7 +128,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, agentClass, "default_device", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto agent = MRubyPtr::unwrap(mrb, self); auto dev = agent->getDefaultDevice(); @@ -144,7 +144,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, agentClass, "data_item_for_device", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto agent = MRubyPtr::unwrap(mrb, self); const char *name, *device; mrb_get_args(mrb, "zz", &device, &name); @@ -166,9 +166,9 @@ namespace mtconnect::ruby { mrb_define_method( mrb, agentClass, "device", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto agent = MRubyPtr::unwrap(mrb, self); - const char *name; + const char* name; mrb_get_args(mrb, "z", &name); auto device = agent->findDeviceByUUIDorName(name); if (device) diff --git a/src/mtconnect/ruby/ruby_entity.hpp b/src/mtconnect/ruby/ruby_entity.hpp index 40db08ad..1529ae48 100644 --- a/src/mtconnect/ruby/ruby_entity.hpp +++ b/src/mtconnect/ruby/ruby_entity.hpp @@ -43,12 +43,12 @@ namespace mtconnect::ruby { /// @param[in] mrb the mruby state /// @param[in] value the data set value /// @returns an mruby value - inline mrb_value toRuby(mrb_state *mrb, const TableCellValue &value) + inline mrb_value toRuby(mrb_state* mrb, const TableCellValue& value) { mrb_value rv; - rv = visit(overloaded {[](const std::monostate &v) -> mrb_value { return mrb_nil_value(); }, - [mrb](const std::string &v) -> mrb_value { + rv = visit(overloaded {[](const std::monostate& v) -> mrb_value { return mrb_nil_value(); }, + [mrb](const std::string& v) -> mrb_value { return mrb_str_new_cstr(mrb, v.c_str()); }, [mrb](const int64_t v) -> mrb_value { return mrb_int_value(mrb, v); }, @@ -65,12 +65,12 @@ namespace mtconnect::ruby { /// @param[in] mrb the mruby state /// @param[in] value the data set /// @returns an mruby value - inline mrb_value toRuby(mrb_state *mrb, const TableRow &set) + inline mrb_value toRuby(mrb_state* mrb, const TableRow& set) { mrb_value hash = mrb_hash_new(mrb); - for (const auto &entry : set) + for (const auto& entry : set) { - const auto &value = (entry.m_value); + const auto& value = (entry.m_value); mrb_sym k = mrb_intern_cstr(mrb, entry.m_key.c_str()); mrb_value v = toRuby(mrb, value); @@ -85,15 +85,15 @@ namespace mtconnect::ruby { /// @param[in] mrb the mruby state /// @param[in] value the data set value /// @returns an mruby value - inline mrb_value toRuby(mrb_state *mrb, const DataSetValue &value) + inline mrb_value toRuby(mrb_state* mrb, const DataSetValue& value) { mrb_value rv; - rv = visit(overloaded {[](const std::monostate &v) -> mrb_value { return mrb_nil_value(); }, - [mrb](const std::string &v) -> mrb_value { + rv = visit(overloaded {[](const std::monostate& v) -> mrb_value { return mrb_nil_value(); }, + [mrb](const std::string& v) -> mrb_value { return mrb_str_new_cstr(mrb, v.c_str()); }, - [mrb](const entity::TableRow &v) -> mrb_value { return toRuby(mrb, v); }, + [mrb](const entity::TableRow& v) -> mrb_value { return toRuby(mrb, v); }, [mrb](const int64_t v) -> mrb_value { return mrb_int_value(mrb, v); }, [mrb](const double v) -> mrb_value { return mrb_float_value(mrb, v); }}, value); @@ -108,12 +108,12 @@ namespace mtconnect::ruby { /// @param[in] mrb the mruby state /// @param[in] value the data set /// @returns an mruby value - inline mrb_value toRuby(mrb_state *mrb, const DataSet &set) + inline mrb_value toRuby(mrb_state* mrb, const DataSet& set) { mrb_value hash = mrb_hash_new(mrb); - for (const auto &entry : set) + for (const auto& entry : set) { - const auto &value = (entry.m_value); + const auto& value = (entry.m_value); mrb_sym k = mrb_intern_cstr(mrb, entry.m_key.c_str()); mrb_value v = toRuby(mrb, value); @@ -128,7 +128,7 @@ namespace mtconnect::ruby { /// @param[in] mrb mruby state /// @param[in] value the hash value to convert /// @returns true if succesful - inline bool tableRowCellValueFromRuby(mrb_state *mrb, mrb_value value, TableCellValue &tcv) + inline bool tableRowCellValueFromRuby(mrb_state* mrb, mrb_value value, TableCellValue& tcv) { using namespace std; @@ -160,15 +160,15 @@ namespace mtconnect::ruby { } /// @brief convert a ruby hash table to a table row - inline void tableRowFromRuby(mrb_state *mrb, mrb_value value, TableRow &row) + inline void tableRowFromRuby(mrb_state* mrb, mrb_value value, TableRow& row) { using namespace std; auto hash = mrb_hash_ptr(value); mrb_hash_foreach( mrb, hash, - [](mrb_state *mrb, mrb_value key, mrb_value val, void *data) { - TableRow *row = static_cast(data); + [](mrb_state* mrb, mrb_value key, mrb_value val, void* data) { + TableRow* row = static_cast(data); string k = stringFromRuby(mrb, key); TableCellValue tcv; if (tableRowCellValueFromRuby(mrb, val, tcv)) @@ -183,7 +183,7 @@ namespace mtconnect::ruby { /// @param[in] mrb mruby state /// @param[in] value the hash value to convert /// @returns true if succesful - inline bool dataSetValueFromRuby(mrb_state *mrb, mrb_value value, DataSetValue &dsv) + inline bool dataSetValueFromRuby(mrb_state* mrb, mrb_value value, DataSetValue& dsv) { using namespace std; @@ -226,14 +226,14 @@ namespace mtconnect::ruby { /// @param[in] mrb mruby state /// @param[in] value the hash value to convert /// @param[out] dataSet the data set to populate - inline void dataSetFromRuby(mrb_state *mrb, mrb_value value, DataSet &dataSet) + inline void dataSetFromRuby(mrb_state* mrb, mrb_value value, DataSet& dataSet) { using namespace std; auto hash = mrb_hash_ptr(value); mrb_hash_foreach( mrb, hash, - [](mrb_state *mrb, mrb_value key, mrb_value val, void *data) { - DataSet *dataSet = static_cast(data); + [](mrb_state* mrb, mrb_value key, mrb_value val, void* data) { + DataSet* dataSet = static_cast(data); string k = stringFromRuby(mrb, key); DataSetValue dsv; if (dataSetValueFromRuby(mrb, val, dsv)) @@ -248,7 +248,7 @@ namespace mtconnect::ruby { /// @param[in] mrb mruby state /// @param[in] value the mruby typed value /// @returns an Entity Value - inline Value valueFromRuby(mrb_state *mrb, mrb_value value) + inline Value valueFromRuby(mrb_state* mrb, mrb_value value) { Value res; @@ -302,11 +302,11 @@ namespace mtconnect::ruby { if (mrb_type(values[0]) == MRB_TT_FIXNUM || mrb_type(values[0]) == MRB_TT_FLOAT) { res.emplace(); - Vector &out = get(res); + Vector& out = get(res); for (int i = 0; i < size; i++) { - mrb_value &v = values[i]; + mrb_value& v = values[i]; auto t = mrb_type(v); if (t == MRB_TT_FIXNUM) out.emplace_back((double)mrb_integer(v)); @@ -325,10 +325,10 @@ namespace mtconnect::ruby { auto klass = mrb_class_get_under(mrb, mod, "Entity"); res.emplace(); - EntityList &list = get(res); + EntityList& list = get(res); for (int i = 0; i < size; i++) { - mrb_value &v = values[i]; + mrb_value& v = values[i]; if (mrb_type(v) == MRB_TT_DATA) { if (mrb_obj_is_kind_of(mrb, value, klass)) @@ -380,36 +380,38 @@ namespace mtconnect::ruby { /// @param[in] mrb MRuby state /// @param[in] value Value to convert /// @return MRuby value - inline mrb_value toRuby(mrb_state *mrb, const Value &value) + inline mrb_value toRuby(mrb_state* mrb, const Value& value) { mrb_value res = visit( overloaded { - [](const std::monostate &) -> mrb_value { return mrb_nil_value(); }, - [](const std::nullptr_t &) -> mrb_value { return mrb_nil_value(); }, + [](const std::monostate&) -> mrb_value { return mrb_nil_value(); }, + [](const std::nullptr_t&) -> mrb_value { return mrb_nil_value(); }, // Not handled yet - [mrb](const EntityPtr &entity) -> mrb_value { + [mrb](const EntityPtr& entity) -> mrb_value { return MRubySharedPtr::wrap(mrb, "Entity", entity); }, - [mrb](const EntityList &list) -> mrb_value { + [mrb](const EntityList& list) -> mrb_value { mrb_value ary = mrb_ary_new_capa(mrb, list.size()); - for (auto &e : list) + for (auto& e : list) mrb_ary_push(mrb, ary, MRubySharedPtr::wrap(mrb, "Entity", e)); return ary; }, - [mrb](const entity::DataSet &v) -> mrb_value { return toRuby(mrb, v); }, + [mrb](const entity::DataSet& v) -> mrb_value { return toRuby(mrb, v); }, // Handled types - [mrb](const entity::Vector &v) -> mrb_value { + [mrb](const entity::Vector& v) -> mrb_value { mrb_value ary = mrb_ary_new_capa(mrb, v.size()); - for (auto &f : v) + for (auto& f : v) mrb_ary_push(mrb, ary, mrb_float_value(mrb, f)); return ary; }, - [mrb](const Timestamp &v) -> mrb_value { return toRuby(mrb, v); }, - [mrb](const std::string &arg) -> mrb_value { return mrb_str_new_cstr(mrb, arg.c_str()); }, + [mrb](const Timestamp& v) -> mrb_value { return toRuby(mrb, v); }, + [mrb](const std::string& arg) -> mrb_value { + return mrb_str_new_cstr(mrb, arg.c_str()); + }, [](const bool arg) -> mrb_value { return mrb_bool_value(static_cast(arg)); }, [mrb](const double arg) -> mrb_value { return mrb_float_value(mrb, arg); }, [mrb](const int64_t arg) -> mrb_value { return mrb_int_value(mrb, arg); }}, @@ -424,7 +426,7 @@ namespace mtconnect::ruby { /// If Hash, then convert to MTConnect properties, otherwise set the Properties VALUE /// @param[out] props converted properties /// @return `true` if successful - inline bool fromRuby(mrb_state *mrb, mrb_value value, Properties &props) + inline bool fromRuby(mrb_state* mrb, mrb_value value, Properties& props) { if (mrb_type(value) != MRB_TT_HASH) { @@ -436,8 +438,8 @@ namespace mtconnect::ruby { auto hash = mrb_hash_ptr(value); mrb_hash_foreach( mrb, hash, - [](mrb_state *mrb, mrb_value key, mrb_value val, void *data) { - Properties *props = static_cast(data); + [](mrb_state* mrb, mrb_value key, mrb_value val, void* data) { + Properties* props = static_cast(data); std::string k = stringFromRuby(mrb, key); auto v = valueFromRuby(mrb, val); @@ -455,10 +457,10 @@ namespace mtconnect::ruby { /// @param[in] mrb MRuby state /// @param[in] props properties /// @return mruby Hash representing the properties - inline mrb_value toRuby(mrb_state *mrb, const Properties &props) + inline mrb_value toRuby(mrb_state* mrb, const Properties& props) { mrb_value hash = mrb_hash_new(mrb); - for (auto &[key, value] : props) + for (auto& [key, value] : props) { mrb_sym k = mrb_intern_cstr(mrb, key.c_str()); mrb_value v = toRuby(mrb, value); @@ -473,15 +475,15 @@ namespace mtconnect::ruby { struct RubyEntity { /// @brief Create Ruby Entity class and method wrappers - static void initialize(mrb_state *mrb, RClass *module) + static void initialize(mrb_state* mrb, RClass* module) { auto entityClass = mrb_define_class_under(mrb, module, "Entity", mrb->object_class); MRB_SET_INSTANCE_TT(entityClass, MRB_TT_DATA); mrb_define_method( mrb, entityClass, "initialize", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; mrb_value properties; mrb_get_args(mrb, "zo", &name, &properties); @@ -497,28 +499,28 @@ namespace mtconnect::ruby { mrb_define_method( mrb, entityClass, "name", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto entity = MRubySharedPtr::unwrap(self); return mrb_str_new_cstr(mrb, entity->getName().c_str()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, entityClass, "hash", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto entity = MRubySharedPtr::unwrap(self); return mrb_str_new_cstr(mrb, entity->hash().c_str()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, entityClass, "value", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto entity = MRubySharedPtr::unwrap(self); return toRuby(mrb, entity->getValue()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, entityClass, "value=", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto entity = MRubySharedPtr::unwrap(self); mrb_value value; mrb_get_args(mrb, "o", &value); @@ -529,7 +531,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, entityClass, "properties", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto entity = MRubySharedPtr::unwrap(self); auto props = entity->getProperties(); @@ -538,9 +540,9 @@ namespace mtconnect::ruby { MRB_ARGS_NONE()); mrb_define_method( mrb, entityClass, "[]", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto entity = MRubySharedPtr::unwrap(self); - const char *key; + const char* key; mrb_get_args(mrb, "z", &key); @@ -554,9 +556,9 @@ namespace mtconnect::ruby { MRB_ARGS_REQ(1)); mrb_define_method( mrb, entityClass, "[]=", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto entity = MRubySharedPtr::unwrap(self); - const char *key; + const char* key; mrb_value value; mrb_get_args(mrb, "zo", &key, &value); @@ -571,16 +573,16 @@ namespace mtconnect::ruby { mrb_define_method( mrb, componentClass, "children", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto comp = MRubySharedPtr::unwrap(mrb, self); mrb_value ary = mrb_ary_new(mrb); - const auto &list = comp->getChildren(); + const auto& list = comp->getChildren(); if (list) { auto mod = mrb_module_get(mrb, "MTConnect"); auto klass = mrb_class_get_under(mrb, mod, "Component"); - for (const auto &c : *list) + for (const auto& c : *list) { ComponentPtr cmp = dynamic_pointer_cast(c); if (cmp) @@ -593,16 +595,16 @@ namespace mtconnect::ruby { MRB_ARGS_NONE()); mrb_define_method( mrb, componentClass, "data_items", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto comp = MRubySharedPtr::unwrap(mrb, self); mrb_value ary = mrb_ary_new(mrb); - const auto &list = comp->getDataItems(); + const auto& list = comp->getDataItems(); if (list) { auto mod = mrb_module_get(mrb, "MTConnect"); auto klass = mrb_class_get_under(mrb, mod, "DataItem"); - for (const auto &c : *list) + for (const auto& c : *list) { DataItemPtr di = dynamic_pointer_cast(c); if (di) @@ -616,9 +618,9 @@ namespace mtconnect::ruby { mrb_define_method( mrb, componentClass, "uuid", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto comp = MRubySharedPtr::unwrap(mrb, self); - auto &uuid = comp->getUuid(); + auto& uuid = comp->getUuid(); if (uuid) return mrb_str_new_cstr(mrb, uuid->c_str()); else @@ -631,9 +633,9 @@ namespace mtconnect::ruby { mrb_define_method( mrb, deviceClass, "data_item", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto dev = MRubySharedPtr::unwrap(mrb, self); - const char *name; + const char* name; mrb_get_args(mrb, "z", &name); auto di = dev->getDeviceDataItem(name); @@ -649,7 +651,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, dataItemClass, "name", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto di = MRubySharedPtr::unwrap(mrb, self); if (di->getName()) return mrb_str_new_cstr(mrb, (*di->getName()).c_str()); @@ -659,44 +661,44 @@ namespace mtconnect::ruby { MRB_ARGS_NONE()); mrb_define_method( mrb, dataItemClass, "observation_name", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto di = MRubySharedPtr::unwrap(mrb, self); return mrb_str_new_cstr(mrb, di->getObservationName().c_str()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, dataItemClass, "id", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto di = MRubySharedPtr::unwrap(mrb, self); return mrb_str_new_cstr(mrb, di->getId().c_str()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, dataItemClass, "type", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto di = MRubySharedPtr::unwrap(mrb, self); return mrb_str_new_cstr(mrb, di->getType().c_str()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, dataItemClass, "sub_type", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto di = MRubySharedPtr::unwrap(mrb, self); return mrb_str_new_cstr(mrb, di->getSubType().c_str()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, dataItemClass, "topic", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto di = MRubySharedPtr::unwrap(mrb, self); return mrb_str_new_cstr(mrb, di->getTopic().c_str()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, dataItemClass, "topic=", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto di = MRubySharedPtr::unwrap(mrb, self); - char *val; + char* val; mrb_get_args(mrb, "z", &val); di->setTopic(val); @@ -709,8 +711,8 @@ namespace mtconnect::ruby { MRB_SET_INSTANCE_TT(tokensClass, MRB_TT_DATA); mrb_define_method( mrb, tokensClass, "initialize", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; mrb_value properties; mrb_get_args(mrb, "zo", &name, &properties); @@ -726,11 +728,11 @@ namespace mtconnect::ruby { mrb_define_method( mrb, tokensClass, "tokens", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto tokens = MRubySharedPtr::unwrap(mrb, self); mrb_value ary = mrb_ary_new(mrb); - for (auto &token : tokens->m_tokens) + for (auto& token : tokens->m_tokens) { mrb_ary_push(mrb, ary, mrb_str_new_cstr(mrb, token.c_str())); } @@ -740,7 +742,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, tokensClass, "tokens=", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto tokens = MRubySharedPtr::unwrap(mrb, self); mrb_value ary; mrb_get_args(mrb, "A", &ary); @@ -762,8 +764,8 @@ namespace mtconnect::ruby { MRB_SET_INSTANCE_TT(timestampedClass, MRB_TT_DATA); mrb_define_method( mrb, timestampedClass, "initialize", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; mrb_value properties; mrb_get_args(mrb, "zo", &name, &properties); @@ -779,7 +781,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, tokensClass, "timestamp", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto ts = MRubySharedPtr::unwrap(mrb, self); return toRuby(mrb, ts->m_timestamp); @@ -788,7 +790,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, tokensClass, "timestamp=", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto ts = MRubySharedPtr::unwrap(mrb, self); mrb_value val; mrb_get_args(mrb, "o", &val); @@ -801,7 +803,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, tokensClass, "duration", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto ts = MRubySharedPtr::unwrap(mrb, self); if (ts->m_duration) return mrb_float_value(mrb, *(ts->m_duration)); @@ -812,7 +814,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, tokensClass, "duration=", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto ts = MRubySharedPtr::unwrap(mrb, self); mrb_float val; mrb_get_args(mrb, "f", &val); diff --git a/src/mtconnect/ruby/ruby_observation.hpp b/src/mtconnect/ruby/ruby_observation.hpp index 46970839..68edf957 100644 --- a/src/mtconnect/ruby/ruby_observation.hpp +++ b/src/mtconnect/ruby/ruby_observation.hpp @@ -27,11 +27,11 @@ namespace mtconnect::ruby { struct RubyObservation { - static RClass *m_eventClass; - static RClass *m_sampleClass; - static RClass *m_conditionClass; + static RClass* m_eventClass; + static RClass* m_sampleClass; + static RClass* m_conditionClass; - static void initialize(mrb_state *mrb, RClass *module) + static void initialize(mrb_state* mrb, RClass* module) { using namespace std; auto entityClass = mrb_class_get_under(mrb, module, "Entity"); @@ -49,7 +49,7 @@ namespace mtconnect::ruby { mrb_define_class_method( mrb, observationClass, "make", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { using namespace device_model::data_item; mrb_value di; @@ -65,7 +65,7 @@ namespace mtconnect::ruby { ts = toRuby(mrb, time); } - struct RClass *klass; + struct RClass* klass; switch (dataItem->getCategory()) { case DataItem::SAMPLE: @@ -90,7 +90,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, observationClass, "initialize", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { using namespace device_model::data_item; mrb_value di; @@ -116,7 +116,7 @@ namespace mtconnect::ruby { if (errors.size() > 0) { ostringstream str; - for (auto &e : errors) + for (auto& e : errors) { str << e->what() << ", "; } @@ -132,9 +132,9 @@ namespace mtconnect::ruby { mrb_define_method( mrb, observationClass, "dup", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { ObservationPtr old = MRubySharedPtr::unwrap(mrb, self); - RClass *klass = mrb_class(mrb, self); + RClass* klass = mrb_class(mrb, self); auto dup = old->copy(); return MRubySharedPtr::wrap(mrb, klass, dup); @@ -144,7 +144,7 @@ namespace mtconnect::ruby { mrb_intern_lit(mrb, "dup")); mrb_define_method( mrb, observationClass, "data_item", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { ObservationPtr obs = MRubySharedPtr::unwrap(mrb, self); if (obs->isOrphan()) return mrb_nil_value(); @@ -155,7 +155,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, observationClass, "timestamp", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { ObservationPtr obs = MRubySharedPtr::unwrap(mrb, self); return toRuby(mrb, obs->getTimestamp()); }, @@ -163,7 +163,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, m_conditionClass, "level", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { ObservationPtr obs = MRubySharedPtr::unwrap(mrb, self); auto cond = std::dynamic_pointer_cast(obs); mrb_value level; @@ -192,10 +192,10 @@ namespace mtconnect::ruby { mrb_define_method( mrb, m_conditionClass, "level=", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { ObservationPtr obs = MRubySharedPtr::unwrap(mrb, self); auto cond = std::dynamic_pointer_cast(obs); - const char *arg = nullptr; + const char* arg = nullptr; mrb_get_args(mrb, "z!", &arg); if (arg == nullptr) return mrb_nil_value(); diff --git a/src/mtconnect/ruby/ruby_pipeline.hpp b/src/mtconnect/ruby/ruby_pipeline.hpp index 234f5ee8..e8ec1aed 100644 --- a/src/mtconnect/ruby/ruby_pipeline.hpp +++ b/src/mtconnect/ruby/ruby_pipeline.hpp @@ -30,7 +30,7 @@ namespace mtconnect::ruby { struct RubyPipeline { - static void initialize(mrb_state *mrb, RClass *module) + static void initialize(mrb_state* mrb, RClass* module) { using namespace std; @@ -42,15 +42,15 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "find", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; TransformPtr transform; auto pipeline = MRubyPtr::unwrap(self); mrb_get_args(mrb, "z", &name); auto transforms = pipeline->find(name); mrb_value ary = mrb_ary_new_capa(mrb, transforms.size()); - for (auto &trans : transforms) + for (auto& trans : transforms) { mrb_ary_push(mrb, ary, MRubySharedPtr::wrap(mrb, "Transform", trans.second)); @@ -62,8 +62,8 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "splice_before", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; TransformPtr transform; mrb_value trans; @@ -86,8 +86,8 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "splice_after", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; mrb_value trans; auto pipeline = MRubyPtr::unwrap(self); @@ -109,8 +109,8 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "first_after", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; mrb_value trans; auto pipeline = MRubyPtr::unwrap(self); @@ -132,8 +132,8 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "last_after", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; mrb_value trans; auto pipeline = MRubyPtr::unwrap(self); @@ -155,8 +155,8 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "remove", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; auto pipeline = MRubyPtr::unwrap(self); mrb_get_args(mrb, "z", &name); @@ -170,8 +170,8 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "replace", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; mrb_value trans; auto pipeline = MRubyPtr::unwrap(self); @@ -192,8 +192,8 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "run", - [](mrb_state *mrb, mrb_value self) { - EntityPtr *entity; + [](mrb_state* mrb, mrb_value self) { + EntityPtr* entity; auto pipeline = MRubyPtr::unwrap(self); mrb_get_args(mrb, "d", &entity, MRubySharedPtr::type()); @@ -206,7 +206,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "context", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto pipeline = MRubyPtr::unwrap(self); return MRubySharedPtr::wrap(mrb, "PipelineContext", pipeline->getContext()); @@ -223,7 +223,7 @@ namespace mtconnect::ruby { mrb_define_method( mrb, pipelineClass, "context", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto pipeline = MRubyPtr::unwrap(self); return MRubySharedPtr::wrap(mrb, "PipelineContext", pipeline->getContext()); diff --git a/src/mtconnect/ruby/ruby_smart_ptr.hpp b/src/mtconnect/ruby/ruby_smart_ptr.hpp index 83ad2fb2..5d52f969 100644 --- a/src/mtconnect/ruby/ruby_smart_ptr.hpp +++ b/src/mtconnect/ruby/ruby_smart_ptr.hpp @@ -25,15 +25,15 @@ namespace mtconnect::ruby { { using SharedPtr = std::shared_ptr; - AGENT_SYMBOL_VISIBLE static mrb_data_type *type() + AGENT_SYMBOL_VISIBLE static mrb_data_type* type() { static mrb_data_type s_type {nullptr, nullptr}; if (s_type.struct_name == nullptr) { mruby_type = &s_type; s_type.struct_name = typeid(T).name(); - s_type.dfree = [](mrb_state *mrb, void *p) { - auto sp = static_cast(p); + s_type.dfree = [](mrb_state* mrb, void* p) { + auto sp = static_cast(p); delete sp; }; } @@ -41,7 +41,7 @@ namespace mtconnect::ruby { return &s_type; } - static mrb_value wrap(mrb_state *mrb, const char *name, SharedPtr obj) + static mrb_value wrap(mrb_state* mrb, const char* name, SharedPtr obj) { if (!obj) return mrb_nil_value(); @@ -54,7 +54,7 @@ namespace mtconnect::ruby { return mrb_obj_value(wrapper); } - static mrb_value wrap(mrb_state *mrb, RClass *klass, SharedPtr obj) + static mrb_value wrap(mrb_state* mrb, RClass* klass, SharedPtr obj) { if (!obj) return mrb_nil_value(); @@ -64,9 +64,9 @@ namespace mtconnect::ruby { return mrb_obj_value(wrapper); } - static void replace(mrb_state *mrb, mrb_value self, SharedPtr obj) + static void replace(mrb_state* mrb, mrb_value self, SharedPtr obj) { - auto selfp = static_cast(DATA_PTR(self)); + auto selfp = static_cast(DATA_PTR(self)); if (selfp) { delete selfp; @@ -74,22 +74,22 @@ namespace mtconnect::ruby { mrb_data_init(self, new SharedPtr(obj), type()); } - static SharedPtr unwrap(mrb_state *mrb, mrb_value value) + static SharedPtr unwrap(mrb_state* mrb, mrb_value value) { - void *dp = mrb_data_get_ptr(mrb, value, type()); + void* dp = mrb_data_get_ptr(mrb, value, type()); if (dp != nullptr) - return *static_cast(dp); + return *static_cast(dp); else return nullptr; } template - static std::shared_ptr unwrap(mrb_state *mrb, mrb_value value) + static std::shared_ptr unwrap(mrb_state* mrb, mrb_value value) { - void *dp = mrb_data_get_ptr(mrb, value, type()); + void* dp = mrb_data_get_ptr(mrb, value, type()); if (dp != nullptr) { - SharedPtr ptr(*static_cast(dp)); + SharedPtr ptr(*static_cast(dp)); return std::dynamic_pointer_cast(ptr); } else @@ -98,9 +98,9 @@ namespace mtconnect::ruby { static SharedPtr unwrap(mrb_value value) { - void *dp = DATA_PTR(value); + void* dp = DATA_PTR(value); if (dp != nullptr) - return *static_cast(dp); + return *static_cast(dp); else return nullptr; } @@ -108,10 +108,10 @@ namespace mtconnect::ruby { template static SharedPtr unwrap(mrb_value value) { - void *dp = DATA_PTR(value); + void* dp = DATA_PTR(value); if (dp != nullptr) { - std::shared_ptr ptr(*static_cast(dp)); + std::shared_ptr ptr(*static_cast(dp)); return std::dynamic_pointer_cast(ptr); } else @@ -119,18 +119,18 @@ namespace mtconnect::ruby { } private: - static mrb_data_type *mruby_type; + static mrb_data_type* mruby_type; }; template - mrb_data_type *MRubySharedPtr::mruby_type = nullptr; + mrb_data_type* MRubySharedPtr::mruby_type = nullptr; template struct MRubyPtr { - using Ptr = T *; + using Ptr = T*; - AGENT_SYMBOL_VISIBLE static mrb_data_type *type() + AGENT_SYMBOL_VISIBLE static mrb_data_type* type() { static mrb_data_type s_type {nullptr, nullptr}; @@ -143,7 +143,7 @@ namespace mtconnect::ruby { return &s_type; } - static mrb_value wrap(mrb_state *mrb, const char *name, Ptr obj) + static mrb_value wrap(mrb_state* mrb, const char* name, Ptr obj) { if (obj == nullptr) return mrb_nil_value(); @@ -155,7 +155,7 @@ namespace mtconnect::ruby { return mrb_obj_value(wrapper); } - static mrb_value wrap(mrb_state *mrb, RClass *klass, Ptr obj) + static mrb_value wrap(mrb_state* mrb, RClass* klass, Ptr obj) { if (obj == nullptr) return mrb_nil_value(); @@ -164,12 +164,12 @@ namespace mtconnect::ruby { return mrb_obj_value(wrapper); } - static Ptr unwrap(mrb_state *mrb, mrb_value value) + static Ptr unwrap(mrb_state* mrb, mrb_value value) { return static_cast(mrb_data_get_ptr(mrb, value, type())); } - static void replace(mrb_state *mrb, mrb_value self, Ptr obj) + static void replace(mrb_state* mrb, mrb_value self, Ptr obj) { mrb_data_init(self, obj, type()); } @@ -177,26 +177,26 @@ namespace mtconnect::ruby { static Ptr unwrap(mrb_value value) { return static_cast(DATA_PTR(value)); } private: - static mrb_data_type *mruby_type; + static mrb_data_type* mruby_type; }; template - mrb_data_type *MRubyPtr::mruby_type = nullptr; + mrb_data_type* MRubyPtr::mruby_type = nullptr; template struct MRubyUniquePtr { using UniquePtr = std::unique_ptr; - AGENT_SYMBOL_VISIBLE static mrb_data_type *type() + AGENT_SYMBOL_VISIBLE static mrb_data_type* type() { static mrb_data_type s_type {nullptr, nullptr}; if (s_type.struct_name == nullptr) { mruby_type = &s_type; s_type.struct_name = typeid(T).name(); - s_type.dfree = [](mrb_state *mrb, void *p) { - auto sp = static_cast(p); + s_type.dfree = [](mrb_state* mrb, void* p) { + auto sp = static_cast(p); delete sp; }; } @@ -204,7 +204,7 @@ namespace mtconnect::ruby { return &s_type; } - static mrb_value wrap(mrb_state *mrb, const char *name, T *obj) + static mrb_value wrap(mrb_state* mrb, const char* name, T* obj) { if (!obj) return mrb_nil_value(); @@ -217,7 +217,7 @@ namespace mtconnect::ruby { return mrb_obj_value(wrapper); } - static mrb_value wrap(mrb_state *mrb, RClass *klass, T *obj) + static mrb_value wrap(mrb_state* mrb, RClass* klass, T* obj) { if (!obj) return mrb_nil_value(); @@ -227,9 +227,9 @@ namespace mtconnect::ruby { return mrb_obj_value(wrapper); } - static void replace(mrb_state *mrb, mrb_value self, UniquePtr obj) + static void replace(mrb_state* mrb, mrb_value self, UniquePtr obj) { - auto selfp = static_cast(DATA_PTR(self)); + auto selfp = static_cast(DATA_PTR(self)); if (selfp) { delete selfp; @@ -237,23 +237,23 @@ namespace mtconnect::ruby { mrb_data_init(self, new UniquePtr(obj), type()); } - static T *unwrap(mrb_state *mrb, mrb_value value) + static T* unwrap(mrb_state* mrb, mrb_value value) { - UniquePtr *ptr = static_cast(mrb_data_get_ptr(mrb, value, type())); + UniquePtr* ptr = static_cast(mrb_data_get_ptr(mrb, value, type())); return ptr->get(); } - static T *unwrap(mrb_value value) + static T* unwrap(mrb_value value) { - UniquePtr *ptr = static_cast(DATA_PTR(value)); + UniquePtr* ptr = static_cast(DATA_PTR(value)); return ptr->get(); } private: - static mrb_data_type *mruby_type; + static mrb_data_type* mruby_type; }; template - mrb_data_type *MRubyUniquePtr::mruby_type = nullptr; + mrb_data_type* MRubyUniquePtr::mruby_type = nullptr; } // namespace mtconnect::ruby diff --git a/src/mtconnect/ruby/ruby_transform.hpp b/src/mtconnect/ruby/ruby_transform.hpp index 7f4ce494..1990b568 100644 --- a/src/mtconnect/ruby/ruby_transform.hpp +++ b/src/mtconnect/ruby/ruby_transform.hpp @@ -34,7 +34,7 @@ namespace mtconnect::ruby { class AGENT_LIB_API RubyTransform : public pipeline::Transform { public: - static void initialize(mrb_state *mrb, RClass *module) + static void initialize(mrb_state* mrb, RClass* module) { using namespace std; @@ -47,10 +47,10 @@ namespace mtconnect::ruby { mrb_define_method( mrb, transClass, "transform", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto trans = MRubySharedPtr::unwrap(mrb, self); - EntityPtr *ent; + EntityPtr* ent; mrb_get_args(mrb, "d", &ent, MRubySharedPtr::type()); auto r = (*trans)(std::move(*ent)); return MRubySharedPtr::wrap(mrb, "Entity", r); @@ -62,8 +62,8 @@ namespace mtconnect::ruby { mrb_define_method( mrb, rubyTrans, "initialize", - [](mrb_state *mrb, mrb_value self) { - const char *name; + [](mrb_state* mrb, mrb_value self) { + const char* name; mrb_value gv, block = mrb_nil_value(); string guard; @@ -87,10 +87,10 @@ namespace mtconnect::ruby { mrb_define_method( mrb, rubyTrans, "forward", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto trans = MRubySharedPtr::unwrap(mrb, self); - EntityPtr *ent; + EntityPtr* ent; mrb_get_args(mrb, "d", &ent, MRubySharedPtr::type()); auto nxt = trans->next(std::move(*ent)); return MRubySharedPtr::wrap(mrb, "Entity", nxt); @@ -99,10 +99,10 @@ namespace mtconnect::ruby { mrb_define_method( mrb, rubyTrans, "bind", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto trans = MRubySharedPtr::unwrap(mrb, self); - TransformPtr *to; + TransformPtr* to; mrb_get_args(mrb, "d", &to, MRubySharedPtr::type()); auto nxt = trans->bind(*to); return MRubySharedPtr::wrap(mrb, "Transform", nxt); @@ -111,9 +111,9 @@ namespace mtconnect::ruby { mrb_define_method( mrb, rubyTrans, "guard=", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto trans = MRubySharedPtr::unwrap(mrb, self); - const char *guard; + const char* guard; if (mrb_get_args(mrb, "z", &guard) > 0) { trans->m_guardString = guard; @@ -127,9 +127,9 @@ namespace mtconnect::ruby { mrb_define_method( mrb, rubyTrans, "guard", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { auto trans = MRubySharedPtr::unwrap(mrb, self); - const char *guard; + const char* guard; mrb_value block = mrb_nil_value(); if (mrb_block_given_p(mrb)) { @@ -152,7 +152,7 @@ namespace mtconnect::ruby { MRB_ARGS_OPT(1) | MRB_ARGS_BLOCK()); } - RubyTransform(mrb_state *mrb, mrb_value self, const std::string &name, const std::string &guard) + RubyTransform(mrb_state* mrb, mrb_value self, const std::string& name, const std::string& guard) : Transform(name), m_self(self), m_method(mrb_intern_lit(mrb, "transform")), @@ -187,7 +187,7 @@ namespace mtconnect::ruby { { if (!mrb_nil_p(m_guardBlock)) { - m_guard = [this, old = m_guard](const entity::Entity *entity) -> GuardAction { + m_guard = [this, old = m_guard](const entity::Entity* entity) -> GuardAction { using namespace entity; using namespace observation; std::lock_guard guard(RubyVM::rubyVM()); @@ -203,7 +203,7 @@ namespace mtconnect::ruby { mrb_value data = mrb_ary_new_from_values(mrb, 2, values); mrb_value rv = mrb_protect( mrb, - [](mrb_state *mrb, mrb_value data) { + [](mrb_state* mrb, mrb_value data) { mrb_value block = mrb_ary_ref(mrb, data, 0); mrb_value ev = mrb_ary_ref(mrb, data, 1); @@ -250,9 +250,9 @@ namespace mtconnect::ruby { m_guard = GuardCls(RUN); } - using calldata = std::pair; + using calldata = std::pair; - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { NAMED_SCOPE("RubyTransform::operator()"); @@ -268,10 +268,10 @@ namespace mtconnect::ruby { try { mrb_value ev; - const char *klass = "Entity"; - Entity *ptr = entity.get(); - Observation *obs; - if (obs = dynamic_cast(ptr); obs != nullptr) + const char* klass = "Entity"; + Entity* ptr = entity.get(); + Observation* obs; + if (obs = dynamic_cast(ptr); obs != nullptr) { switch (obs->getDataItem()->getCategory()) { @@ -286,9 +286,9 @@ namespace mtconnect::ruby { break; } } - else if (dynamic_cast(ptr) != nullptr) + else if (dynamic_cast(ptr) != nullptr) klass = "Timestamped"; - else if (dynamic_cast(ptr) != nullptr) + else if (dynamic_cast(ptr) != nullptr) klass = "Tokens"; ev = MRubySharedPtr::wrap(mrb, klass, entity); @@ -301,7 +301,7 @@ namespace mtconnect::ruby { mrb_value data = mrb_ary_new_from_values(mrb, 3, values); rv = mrb_protect( mrb, - [](mrb_state *mrb, mrb_value data) { + [](mrb_state* mrb, mrb_value data) { mrb_value self = mrb_ary_ref(mrb, data, 0); mrb_value block = mrb_ary_ref(mrb, data, 1); mrb_value ev = mrb_ary_ref(mrb, data, 2); @@ -315,7 +315,7 @@ namespace mtconnect::ruby { mrb_value data = mrb_ary_new_from_values(mrb, 3, values); rv = mrb_protect( mrb, - [](mrb_state *mrb, mrb_value data) { + [](mrb_state* mrb, mrb_value data) { mrb_value self = mrb_ary_ref(mrb, data, 0); mrb_sym method = mrb_symbol(mrb_ary_ref(mrb, data, 1)); mrb_value ev = mrb_ary_ref(mrb, data, 2); @@ -351,11 +351,11 @@ namespace mtconnect::ruby { return res; } - auto &object() { return m_self; } + auto& object() { return m_self; } void setObject(mrb_value obj) { m_self = obj; } protected: - PipelineContract *m_contract; + PipelineContract* m_contract; mrb_value m_self; mrb_sym m_method; mrb_value m_block; diff --git a/src/mtconnect/ruby/ruby_type.hpp b/src/mtconnect/ruby/ruby_type.hpp index 1326b87b..96adffbc 100644 --- a/src/mtconnect/ruby/ruby_type.hpp +++ b/src/mtconnect/ruby/ruby_type.hpp @@ -31,7 +31,7 @@ namespace mtconnect::ruby { using namespace data_item; using namespace entity; - inline std::string stringFromRuby(mrb_state *mrb, mrb_value value) + inline std::string stringFromRuby(mrb_state* mrb, mrb_value value) { using namespace std; if (mrb_string_p(value)) @@ -48,7 +48,7 @@ namespace mtconnect::ruby { } } - inline mrb_value toRuby(mrb_state *mrb, const std::string &str) + inline mrb_value toRuby(mrb_state* mrb, const std::string& str) { return mrb_str_new_cstr(mrb, str.c_str()); } @@ -61,7 +61,7 @@ namespace mtconnect::ruby { struct tm datetime; }; - inline Timestamp timestampFromRuby(mrb_state *mrb, mrb_value value) + inline Timestamp timestampFromRuby(mrb_state* mrb, mrb_value value) { using namespace std::chrono; if (mrb_string_p(value)) @@ -78,7 +78,7 @@ namespace mtconnect::ruby { auto dp = DATA_TYPE(value); if (strncmp(dp->struct_name, "Time", 4) == 0) { - auto tm = static_cast(DATA_PTR(value)); + auto tm = static_cast(DATA_PTR(value)); auto dur = duration_cast(seconds {tm->sec} + microseconds {tm->usec}); return time_point {duration_cast(dur)}; } @@ -89,7 +89,7 @@ namespace mtconnect::ruby { } } - inline mrb_value toRuby(mrb_state *mrb, const Timestamp &ts) + inline mrb_value toRuby(mrb_state* mrb, const Timestamp& ts) { using namespace std::chrono; diff --git a/src/mtconnect/ruby/ruby_vm.hpp b/src/mtconnect/ruby/ruby_vm.hpp index be6b1862..c552b280 100644 --- a/src/mtconnect/ruby/ruby_vm.hpp +++ b/src/mtconnect/ruby/ruby_vm.hpp @@ -56,18 +56,18 @@ namespace mtconnect::ruby { void unlock() { m_mutex.unlock(); } [[nodiscard]] bool try_lock() { return m_mutex.try_lock(); } - static auto &rubyVM() { return *m_vm; } + static auto& rubyVM() { return *m_vm; } static bool hasVM() { return m_vm != nullptr; } protected: void createModule() { m_module = mrb_define_module(m_mrb, "MTConnect"); } template - static inline void log(L level, mrb_state *mrb) + static inline void log(L level, mrb_state* mrb) { mrb_value msg; mrb_get_args(mrb, "S", &msg); - BOOST_LOG_SEV(agent_logger::get(), level) << mrb_str_to_cstr(mrb, msg); + BOOST_LOG_SEV(agent_logger::get(), level) << mrb_str_to_cstr(mrb, msg); } void defineLogger() @@ -76,42 +76,42 @@ namespace mtconnect::ruby { auto logger = mrb_define_module_under(m_mrb, m_module, "Logger"); mrb_define_class_method( m_mrb, logger, "debug", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { log(::boost::log::trivial::debug, mrb); return mrb_nil_value(); }, MRB_ARGS_REQ(1)); mrb_define_class_method( m_mrb, logger, "trace", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { log(::boost::log::trivial::trace, mrb); return mrb_nil_value(); }, MRB_ARGS_REQ(1)); mrb_define_class_method( m_mrb, logger, "info", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { log(::boost::log::trivial::info, mrb); return mrb_nil_value(); }, MRB_ARGS_REQ(1)); mrb_define_class_method( m_mrb, logger, "warning", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { log(::boost::log::trivial::warning, mrb); return mrb_nil_value(); }, MRB_ARGS_REQ(1)); mrb_define_class_method( m_mrb, logger, "error", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { log(::boost::log::trivial::error, mrb); return mrb_nil_value(); }, MRB_ARGS_REQ(1)); mrb_define_class_method( m_mrb, logger, "fatal", - [](mrb_state *mrb, mrb_value self) { + [](mrb_state* mrb, mrb_value self) { log(::boost::log::trivial::fatal, mrb); return mrb_nil_value(); }, @@ -119,10 +119,10 @@ namespace mtconnect::ruby { } protected: - Agent *m_agent; - RClass *m_module = nullptr; - mrb_state *m_mrb = nullptr; + Agent* m_agent; + RClass* m_module = nullptr; + mrb_state* m_mrb = nullptr; static std::recursive_mutex m_mutex; - static RubyVM *m_vm; + static RubyVM* m_vm; }; } // namespace mtconnect::ruby diff --git a/src/mtconnect/sink/mqtt_entity_sink/mqtt_entity_sink.cpp b/src/mtconnect/sink/mqtt_entity_sink/mqtt_entity_sink.cpp index 8fe697cf..d9875068 100644 --- a/src/mtconnect/sink/mqtt_entity_sink/mqtt_entity_sink.cpp +++ b/src/mtconnect/sink/mqtt_entity_sink/mqtt_entity_sink.cpp @@ -590,5 +590,5 @@ namespace mtconnect { } } // namespace mqtt_entity_sink - } // namespace sink + } // namespace sink } // namespace mtconnect diff --git a/src/mtconnect/sink/mqtt_entity_sink/mqtt_entity_sink.hpp b/src/mtconnect/sink/mqtt_entity_sink/mqtt_entity_sink.hpp index 3d1e6f34..760e3057 100644 --- a/src/mtconnect/sink/mqtt_entity_sink/mqtt_entity_sink.hpp +++ b/src/mtconnect/sink/mqtt_entity_sink/mqtt_entity_sink.hpp @@ -129,5 +129,5 @@ namespace mtconnect { std::mutex m_queueMutex; }; } // namespace mqtt_entity_sink - } // namespace sink + } // namespace sink } // namespace mtconnect diff --git a/src/mtconnect/sink/mqtt_sink/mqtt_service.cpp b/src/mtconnect/sink/mqtt_sink/mqtt_service.cpp index c6264d34..bad39019 100644 --- a/src/mtconnect/sink/mqtt_sink/mqtt_service.cpp +++ b/src/mtconnect/sink/mqtt_sink/mqtt_service.cpp @@ -44,8 +44,8 @@ namespace mtconnect { // create a json printer // call print - MqttService::MqttService(boost::asio::io_context &context, sink::SinkContractPtr &&contract, - const ConfigOptions &options, const ptree &config) + MqttService::MqttService(boost::asio::io_context& context, sink::SinkContractPtr&& contract, + const ConfigOptions& options, const ptree& config) : Sink("MqttService", std::move(contract)), m_context(context), m_strand(context), @@ -55,7 +55,7 @@ namespace mtconnect { // Unique id number for agent instance m_instanceId = getCurrentTimeInSec(); - auto jsonPrinter = dynamic_cast(m_sinkContract->getPrinter("json")); + auto jsonPrinter = dynamic_cast(m_sinkContract->getPrinter("json")); m_jsonPrinter = make_unique(jsonPrinter->getJsonVersion()); @@ -105,7 +105,7 @@ namespace mtconnect { auto clientHandler = make_unique(); clientHandler->m_connected = [this](shared_ptr client) { // Publish latest devices, assets, and observations - auto &circ = m_sinkContract->getCircularBuffer(); + auto& circ = m_sinkContract->getCircularBuffer(); std::lock_guard lock(circ); client->connectComplete(); @@ -142,8 +142,8 @@ namespace mtconnect { struct AsyncSample : public observation::AsyncObserver { - AsyncSample(boost::asio::io_context::strand &strand, - mtconnect::buffer::CircularBuffer &buffer, FilterSet &&filter, + AsyncSample(boost::asio::io_context::strand& strand, + mtconnect::buffer::CircularBuffer& buffer, FilterSet&& filter, std::chrono::milliseconds interval, std::chrono::milliseconds heartbeat, std::shared_ptr client, DevicePtr device) : observation::AsyncObserver(strand, buffer, std::move(filter), interval, heartbeat), @@ -151,7 +151,7 @@ namespace mtconnect { m_client(client) {} - void fail(boost::beast::http::status status, const std::string &message) override + void fail(boost::beast::http::status status, const std::string& message) override { LOG(error) << "MQTT Sample Failed: " << message; } @@ -176,20 +176,20 @@ namespace mtconnect { void MqttService::pubishInitialContent() { using std::placeholders::_1; - for (auto &dev : m_sinkContract->getDevices()) + for (auto& dev : m_sinkContract->getDevices()) { publish(dev); AssetList list; m_sinkContract->getAssetStorage()->getAssets(list, 100000, true, *(dev->getUuid())); - for (auto &asset : list) + for (auto& asset : list) { publish(asset); } } auto seq = publishCurrent(boost::system::error_code {}); - for (auto &dev : m_sinkContract->getDevices()) + for (auto& dev : m_sinkContract->getDevices()) { FilterSet filterSet = filterForDevice(dev); auto sampler = @@ -197,7 +197,7 @@ namespace mtconnect { std::move(filterSet), m_sampleInterval, 600s, m_client, dev); sampler->m_sink = getptr(); sampler->m_handler = boost::bind(&MqttService::publishSample, this, _1); - sampler->observe(seq, [this](const std::string &id) { + sampler->observe(seq, [this](const std::string& id) { return m_sinkContract->getDataItemById(id).get(); }); publishSample(sampler); @@ -218,7 +218,7 @@ namespace mtconnect { SequenceNumber_t firstSeq, lastSeq; { - auto &buffer = m_sinkContract->getCircularBuffer(); + auto& buffer = m_sinkContract->getCircularBuffer(); std::lock_guard lock(buffer); lastSeq = buffer.getSequence() - 1; @@ -261,7 +261,7 @@ namespace mtconnect { return 0; } - for (auto &device : m_sinkContract->getDevices()) + for (auto& device : m_sinkContract->getDevices()) { auto topic = formatTopic(m_currentTopic, device); LOG(debug) << "Publishing current for: " << topic; @@ -270,7 +270,7 @@ namespace mtconnect { auto filterSet = filterForDevice(device); { - auto &buffer = m_sinkContract->getCircularBuffer(); + auto& buffer = m_sinkContract->getCircularBuffer(); std::lock_guard lock(buffer); firstSeq = buffer.getFirstSequence(); @@ -294,7 +294,7 @@ namespace mtconnect { return seq; } - bool MqttService::publish(observation::ObservationPtr &observation) + bool MqttService::publish(observation::ObservationPtr& observation) { // Since we are doing periodic publishing, there is nothing to do here. return true; @@ -342,16 +342,16 @@ namespace mtconnect { } // Register the service with the sink factory - void MqttService::registerFactory(SinkFactory &factory) + void MqttService::registerFactory(SinkFactory& factory) { factory.registerFactory( "MqttService", - [](const std::string &name, boost::asio::io_context &io, SinkContractPtr &&contract, - const ConfigOptions &options, const boost::property_tree::ptree &block) -> SinkPtr { + [](const std::string& name, boost::asio::io_context& io, SinkContractPtr&& contract, + const ConfigOptions& options, const boost::property_tree::ptree& block) -> SinkPtr { auto sink = std::make_shared(io, std::move(contract), options, block); return sink; }); } } // namespace mqtt_sink - } // namespace sink + } // namespace sink } // namespace mtconnect diff --git a/src/mtconnect/sink/mqtt_sink/mqtt_service.hpp b/src/mtconnect/sink/mqtt_sink/mqtt_service.hpp index ad014042..e4f57f26 100644 --- a/src/mtconnect/sink/mqtt_sink/mqtt_service.hpp +++ b/src/mtconnect/sink/mqtt_sink/mqtt_service.hpp @@ -53,8 +53,8 @@ namespace mtconnect { /// @param contract the Sink Contract from the agent /// @param options configuration options /// @param config additional configuration options if specified directly as a sink - MqttService(boost::asio::io_context &context, sink::SinkContractPtr &&contract, - const ConfigOptions &options, const boost::property_tree::ptree &config); + MqttService(boost::asio::io_context& context, sink::SinkContractPtr&& contract, + const ConfigOptions& options, const boost::property_tree::ptree& config); ~MqttService() = default; @@ -71,7 +71,7 @@ namespace mtconnect { /// /// @param observation shared pointer to the observation /// @return `true` if the publishing was successful - bool publish(observation::ObservationPtr &observation) override; + bool publish(observation::ObservationPtr& observation) override; /// @brief Receive an asset /// @param asset shared point to the asset @@ -94,7 +94,7 @@ namespace mtconnect { /// @brief Register the Sink factory to create this sink /// @param factory - static void registerFactory(SinkFactory &factory); + static void registerFactory(SinkFactory& factory); /// @brief gets a Mqtt Client /// @return MqttClient @@ -105,15 +105,15 @@ namespace mtconnect { bool isConnected() { return m_client && m_client->isConnected(); } protected: - const FilterSet &filterForDevice(const DevicePtr &device) + const FilterSet& filterForDevice(const DevicePtr& device) { auto filter = m_filters.find(*(device->getUuid())); if (filter == m_filters.end()) { auto pos = m_filters.emplace(*(device->getUuid()), FilterSet()); filter = pos.first; - auto &set = filter->second; - for (const auto &wdi : device->getDeviceDataItems()) + auto& set = filter->second; + for (const auto& wdi : device->getDeviceDataItems()) { const auto di = wdi.lock(); if (di) @@ -123,7 +123,7 @@ namespace mtconnect { return filter->second; } - std::string formatTopic(const std::string &topic, const DevicePtr device, + std::string formatTopic(const std::string& topic, const DevicePtr device, const std::string defaultUuid = "Unknown") { std::string uuid; @@ -152,7 +152,7 @@ namespace mtconnect { return formatted; } - std::string getTopic(const std::string &option, int maxTopicDepth) + std::string getTopic(const std::string& option, int maxTopicDepth) { auto topic {std::get(m_options[option])}; auto depth = std::count(topic.begin(), topic.end(), '/'); @@ -176,7 +176,7 @@ namespace mtconnect { uint64_t m_instanceId; - boost::asio::io_context &m_context; + boost::asio::io_context& m_context; boost::asio::io_context::strand m_strand; ConfigOptions m_options; @@ -192,5 +192,5 @@ namespace mtconnect { std::map> m_samplers; }; } // namespace mqtt_sink - } // namespace sink + } // namespace sink } // namespace mtconnect diff --git a/src/mtconnect/sink/rest_sink/cached_file.hpp b/src/mtconnect/sink/rest_sink/cached_file.hpp index 6f5c3bdc..92b4e082 100644 --- a/src/mtconnect/sink/rest_sink/cached_file.hpp +++ b/src/mtconnect/sink/rest_sink/cached_file.hpp @@ -49,7 +49,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Create a cached file from another file specifying the mime type /// @param file the file to copy /// @param mime the new mime type - CachedFile(const CachedFile &file, const std::string &mime) + CachedFile(const CachedFile& file, const std::string& mime) : m_size(file.m_size), m_mimeType(mime), m_path(file.m_path), @@ -67,7 +67,7 @@ namespace mtconnect::sink::rest_sink { /// @param buffer a pointer to the buffer /// @param size the buffer size /// @param mime the mime type - CachedFile(const char *buffer, size_t size, const std::string &mime) + CachedFile(const char* buffer, size_t size, const std::string& mime) : m_buffer(nullptr), m_size(size), m_mimeType(mime) { allocate(m_size); @@ -83,7 +83,7 @@ namespace mtconnect::sink::rest_sink { /// @param mime the mime type of the file /// @param cached `true` if the buffer should be allocated /// @param size optional size; if 0, size of will be determined from the operating system - CachedFile(const std::filesystem::path &path, const std::string &mime, bool cached = true, + CachedFile(const std::filesystem::path& path, const std::string& mime, bool cached = true, size_t size = 0) : m_buffer(nullptr), m_mimeType(mime), m_path(path), m_cached(cached) { @@ -109,7 +109,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Clone a CachedFile /// @param file the file /// @return this - CachedFile &operator=(const CachedFile &file) + CachedFile& operator=(const CachedFile& file) { m_cached = file.m_cached; m_path = file.m_path; @@ -128,11 +128,11 @@ namespace mtconnect::sink::rest_sink { if (m_buffer != nullptr) free(m_buffer); m_size = size; - m_buffer = static_cast(malloc(m_size + 1)); + m_buffer = static_cast(malloc(m_size + 1)); memset(m_buffer, 0, m_size + 1); } - char *m_buffer {nullptr}; + char* m_buffer {nullptr}; size_t m_size {0}; std::string m_mimeType; std::filesystem::path m_path; diff --git a/src/mtconnect/sink/rest_sink/error.hpp b/src/mtconnect/sink/rest_sink/error.hpp index 2b225c42..dc8c156b 100644 --- a/src/mtconnect/sink/rest_sink/error.hpp +++ b/src/mtconnect/sink/rest_sink/error.hpp @@ -52,12 +52,12 @@ namespace mtconnect::sink::rest_sink { INVALID_QUERY_PARAMETER }; - Error(const std::string &name, const entity::Properties &props) : entity::Entity(name, props) {} + Error(const std::string& name, const entity::Properties& props) : entity::Entity(name, props) {} ~Error() override = default; - void setURI(const std::string &uri) { setProperty("URI", uri); } - void setRequest(const std::string &request) { setProperty("Request", request); } - void setErrorMessage(const std::string &message) { setProperty("ErrorMessage", message); } + void setURI(const std::string& uri) { setProperty("URI", uri); } + void setRequest(const std::string& request) { setProperty("Request", request); } + void setErrorMessage(const std::string& message) { setProperty("ErrorMessage", message); } /// @brief get the static error factory /// @return shared pointer to the factory @@ -66,7 +66,7 @@ namespace mtconnect::sink::rest_sink { static auto error = std::make_shared( entity::Requirements { {"errorCode", false}, {"URI", false}, {"Request", false}, {"ErrorMessage", false}}, - [](const std::string &name, entity::Properties &props) -> entity::EntityPtr { + [](const std::string& name, entity::Properties& props) -> entity::EntityPtr { return std::make_shared(name, props); }); @@ -113,8 +113,8 @@ namespace mtconnect::sink::rest_sink { class AGENT_LIB_API QueryParameter : public entity::Entity { public: - QueryParameter(const entity::Properties &props) : entity::Entity("QueryParameter", props) {} - QueryParameter(const std::string &name, const entity::Properties &props) + QueryParameter(const entity::Properties& props) : entity::Entity("QueryParameter", props) {} + QueryParameter(const std::string& name, const entity::Properties& props) : entity::Entity(name, props) {} @@ -129,7 +129,7 @@ namespace mtconnect::sink::rest_sink { {"Format", false}, {"Minimum", entity::ValueType::INTEGER, false}, {"Maximum", entity::ValueType::INTEGER, false}}, - [](const std::string &name, entity::Properties &props) -> entity::EntityPtr { + [](const std::string& name, entity::Properties& props) -> entity::EntityPtr { return std::make_shared(name, props); }); @@ -138,7 +138,7 @@ namespace mtconnect::sink::rest_sink { /// @brief static factory method /// @param properties the properties for the QueryParameter - static entity::EntityPtr make(const entity::Properties &properties) + static entity::EntityPtr make(const entity::Properties& properties) { return std::make_shared(properties); } @@ -149,9 +149,9 @@ namespace mtconnect::sink::rest_sink { class AGENT_LIB_API InvalidParameterValue : public Error { public: - InvalidParameterValue(const entity::Properties &props) : Error("InvalidParameterValue", props) + InvalidParameterValue(const entity::Properties& props) : Error("InvalidParameterValue", props) {} - InvalidParameterValue(const std::string &name, const entity::Properties &props) + InvalidParameterValue(const std::string& name, const entity::Properties& props) : Error(name, props) {} ~InvalidParameterValue() override = default; @@ -168,7 +168,7 @@ namespace mtconnect::sink::rest_sink { entity::Requirements {{"InvalidParameterValue", entity::ValueType::ENTITY, QueryParameter::getFactory(), true}}); factory->setFunction( - [](const std::string &name, entity::Properties &props) -> entity::EntityPtr { + [](const std::string& name, entity::Properties& props) -> entity::EntityPtr { return std::make_shared(name, props); }); } @@ -182,8 +182,8 @@ namespace mtconnect::sink::rest_sink { /// @param format the format of the parameter /// @param errorMessage optional error message /// @param request optional request string - static entity::EntityPtr make(const std::string &name, const std::string &value, - const std::string &type, const std::string &format, + static entity::EntityPtr make(const std::string& name, const std::string& value, + const std::string& type, const std::string& format, std::optional errorMessage = std::nullopt, std::optional request = std::nullopt) { @@ -209,8 +209,8 @@ namespace mtconnect::sink::rest_sink { class AGENT_LIB_API OutOfRange : public Error { public: - OutOfRange(const entity::Properties &props) : Error("OutOfRange", props) {} - OutOfRange(const std::string &name, const entity::Properties &props) : Error(name, props) {} + OutOfRange(const entity::Properties& props) : Error("OutOfRange", props) {} + OutOfRange(const std::string& name, const entity::Properties& props) : Error(name, props) {} ~OutOfRange() override = default; /// @brief get the static error factory @@ -224,7 +224,7 @@ namespace mtconnect::sink::rest_sink { factory->addRequirements(entity::Requirements { {"QueryParameters", entity::ValueType::ENTITY, QueryParameter::getFactory(), true}}); factory->setFunction( - [](const std::string &name, entity::Properties &props) -> entity::EntityPtr { + [](const std::string& name, entity::Properties& props) -> entity::EntityPtr { return std::make_shared(name, props); }); } @@ -238,7 +238,7 @@ namespace mtconnect::sink::rest_sink { /// @param max the maximum value of the parameter /// @param errorMessage optional error message /// @param request optional request string - static entity::EntityPtr make(const std::string &name, int64_t value, int64_t min, int64_t max, + static entity::EntityPtr make(const std::string& name, int64_t value, int64_t min, int64_t max, std::optional errorMessage = std::nullopt, std::optional request = std::nullopt) { @@ -262,8 +262,8 @@ namespace mtconnect::sink::rest_sink { class AGENT_LIB_API AssetNotFound : public Error { public: - AssetNotFound(const entity::Properties &props) : Error("AssetNotFound", props) {} - AssetNotFound(const std::string &name, const entity::Properties &props) : Error(name, props) {} + AssetNotFound(const entity::Properties& props) : Error("AssetNotFound", props) {} + AssetNotFound(const std::string& name, const entity::Properties& props) : Error(name, props) {} ~AssetNotFound() override = default; /// @brief get the static error factory @@ -276,7 +276,7 @@ namespace mtconnect::sink::rest_sink { factory = std::make_shared(*Error::getFactory()); factory->addRequirements(entity::Requirements {{"AssetId", true}}); factory->setFunction( - [](const std::string &name, entity::Properties &props) -> entity::EntityPtr { + [](const std::string& name, entity::Properties& props) -> entity::EntityPtr { return std::make_shared(name, props); }); } @@ -287,7 +287,7 @@ namespace mtconnect::sink::rest_sink { /// @param assetId the asset ID that was not found /// @param errorMessage optional error message /// @param request optional request string - static entity::EntityPtr make(const std::string &assetId, + static entity::EntityPtr make(const std::string& assetId, std::optional errorMessage = std::nullopt, std::optional request = std::nullopt) { @@ -328,7 +328,7 @@ namespace mtconnect::sink::rest_sink { /// @param accepts the accepted mime types, defaults to application/xml /// @param status the HTTP status code, defaults to 400 Bad Request /// @param format optional format for the error - RestError(entity::EntityList &errors, std::string accepts = "application/xml", + RestError(entity::EntityList& errors, std::string accepts = "application/xml", status st = status::bad_request, std::optional format = std::nullopt, std::optional requestId = std::nullopt) : m_errors(errors), m_accepts(accepts), m_status(st), m_format(format), m_requestId(requestId) @@ -339,7 +339,7 @@ namespace mtconnect::sink::rest_sink { /// @param printer the printer to generate the error document /// @param status the HTTP status code, defaults to 400 Bad Request /// @param format optional format for the error - RestError(entity::EntityPtr error, const printer::Printer *printer = nullptr, + RestError(entity::EntityPtr error, const printer::Printer* printer = nullptr, status st = status::bad_request, std::optional format = std::nullopt, std::optional requestId = std::nullopt) : m_errors({error}), @@ -355,45 +355,45 @@ namespace mtconnect::sink::rest_sink { /// @param printer the printer to generate the error document /// @param status the HTTP status code, defaults to 400 Bad Request /// @param format optional format for the error - RestError(entity::EntityList &errors, const printer::Printer *printer = nullptr, + RestError(entity::EntityList& errors, const printer::Printer* printer = nullptr, status st = status::bad_request, std::optional format = std::nullopt, std::optional requestId = std::nullopt) : m_errors(errors), m_status(st), m_format(format), m_requestId(requestId), m_printer(printer) {} ~RestError() = default; - RestError(const RestError &o) = default; + RestError(const RestError& o) = default; /// @brief set the URI for all errors /// @param uri the URI - void setUri(const std::string &uri) + void setUri(const std::string& uri) { - for (auto &e : m_errors) + for (auto& e : m_errors) e->setProperty("URI", uri); } /// @brief set the Request ID for the websocket responses /// @param requestId the Request ID - void setRequestId(const std::string &requestId) { m_requestId = requestId; } - const auto &getRequestId() const { return m_requestId; } + void setRequestId(const std::string& requestId) { m_requestId = requestId; } + const auto& getRequestId() const { return m_requestId; } /// @brief The response document type for the request (e.g. MTConnectDevices) /// @param request the Request - void setRequest(const std::string &request) + void setRequest(const std::string& request) { - for (auto &e : m_errors) + for (auto& e : m_errors) e->setProperty("Request", request); } - const auto &getErrors() const { return m_errors; } + const auto& getErrors() const { return m_errors; } void setStatus(status st) { m_status = st; } - const auto &getStatus() const { return m_status; } + const auto& getStatus() const { return m_status; } - void setFormat(const std::string &format) { m_format = format; } - const auto &getFormat() const { return m_format; } + void setFormat(const std::string& format) { m_format = format; } + const auto& getFormat() const { return m_format; } - const auto &getAccepts() const { return m_accepts; } + const auto& getAccepts() const { return m_accepts; } auto getPrinter() const { return m_printer; } @@ -402,7 +402,7 @@ namespace mtconnect::sink::rest_sink { std::string what() const { std::stringstream ss; - for (const auto &e : m_errors) + for (const auto& e : m_errors) { ss << e->getName() << ": "; auto message = e->maybeGet("ErrorMessage"); @@ -421,7 +421,7 @@ namespace mtconnect::sink::rest_sink { status m_status; ///< The HTTP status code std::optional m_format; ///< The format for the error response overriding accepts std::optional m_requestId; ///< The request id for the response - const printer::Printer *m_printer { + const printer::Printer* m_printer { nullptr}; ///< The printer to use for the response. If the printer is not specified it will ///< be inferred from the accepts or format. }; diff --git a/src/mtconnect/sink/rest_sink/file_cache.cpp b/src/mtconnect/sink/rest_sink/file_cache.cpp index 5b4f3205..2a7d5a43 100644 --- a/src/mtconnect/sink/rest_sink/file_cache.cpp +++ b/src/mtconnect/sink/rest_sink/file_cache.cpp @@ -60,8 +60,8 @@ namespace mtconnect::sink::rest_sink { namespace fs = std::filesystem; // Register a file - MTConnectSchemaList FileCache::registerDirectory(const string &uri, const fs::path &pathName, - const string &version) + MTConnectSchemaList FileCache::registerDirectory(const string& uri, const fs::path& pathName, + const string& version) { MTConnectSchemaList namespaces; @@ -84,7 +84,7 @@ namespace mtconnect::sink::rest_sink { { fs::path baseUri(uri, fs::path::format::generic_format); - for (auto &file : fs::directory_iterator(path)) + for (auto& file : fs::directory_iterator(path)) { string name = (file.path().filename()).string(); fs::path uri = baseUri / name; @@ -103,9 +103,9 @@ namespace mtconnect::sink::rest_sink { return namespaces; } - std::optional FileCache::registerFile(const std::string &uri, - const fs::path &path, - const std::string &version) + std::optional FileCache::registerFile(const std::string& uri, + const fs::path& path, + const std::string& version) { optional ns; @@ -149,9 +149,9 @@ namespace mtconnect::sink::rest_sink { return ns; } - CachedFilePtr FileCache::redirect(const std::string &name, const Directory &dir) + CachedFilePtr FileCache::redirect(const std::string& name, const Directory& dir) { - static const char *body = R"( + static const char* body = R"( 301 Moved Permanently

301 Moved Permanently

@@ -166,7 +166,7 @@ namespace mtconnect::sink::rest_sink { return file; } - void FileCache::compressFile(CachedFilePtr file, boost::asio::io_context *context) + void FileCache::compressFile(CachedFilePtr file, boost::asio::io_context* context) { NAMED_SCOPE("FileCache::compressFile") @@ -222,7 +222,7 @@ namespace mtconnect::sink::rest_sink { if (future.get()) file->m_pathGz.emplace(zipped); } - catch (std::runtime_error &e) + catch (std::runtime_error& e) { LOG(error) << "Error occurred compressing: " << e.what(); } @@ -247,11 +247,11 @@ namespace mtconnect::sink::rest_sink { } } - CachedFilePtr FileCache::findFileInDirectories(const std::string &name) + CachedFilePtr FileCache::findFileInDirectories(const std::string& name) { namespace fs = std::filesystem; - for (const auto &dir : m_directories) + for (const auto& dir : m_directories) { if (name.starts_with(dir.first)) { @@ -291,9 +291,9 @@ namespace mtconnect::sink::rest_sink { return nullptr; } - CachedFilePtr FileCache::getFile(const std::string &name, + CachedFilePtr FileCache::getFile(const std::string& name, const std::optional acceptEncoding, - boost::asio::io_context *context) + boost::asio::io_context* context) { namespace fs = std::filesystem; @@ -365,8 +365,8 @@ namespace mtconnect::sink::rest_sink { return nullptr; } - void FileCache::addDirectory(const std::string &uri, const std::string &pathName, - const std::string &index) + void FileCache::addDirectory(const std::string& uri, const std::string& pathName, + const std::string& index) { fs::path path(pathName); if (fs::exists(path)) diff --git a/src/mtconnect/sink/rest_sink/file_cache.hpp b/src/mtconnect/sink/rest_sink/file_cache.hpp index 3c306248..9c03a61f 100644 --- a/src/mtconnect/sink/rest_sink/file_cache.hpp +++ b/src/mtconnect/sink/rest_sink/file_cache.hpp @@ -43,7 +43,7 @@ namespace mtconnect::sink::rest_sink { std::string m_uri; std::string m_doc; - MTConnectSchema(SchemaType type, const std::string &uri, const std::string &doc) + MTConnectSchema(SchemaType type, const std::string& uri, const std::string& doc) : m_type(type), m_uri(uri), m_doc(doc) {} }; @@ -65,8 +65,8 @@ namespace mtconnect::sink::rest_sink { /// @param path the path on the file system /// @param version schema version when registering MTConnect files /// @return A namespace list associated with the files - MTConnectSchemaList registerFiles(const std::string &uri, const std::filesystem::path &path, - const std::string &version) + MTConnectSchemaList registerFiles(const std::string& uri, const std::filesystem::path& path, + const std::string& version) { return registerDirectory(uri, path, version); } @@ -75,35 +75,35 @@ namespace mtconnect::sink::rest_sink { /// @param path the path on the file system /// @param version schema version when registering MTConnect files /// @return A namespace list associated with the files - MTConnectSchemaList registerDirectory(const std::string &uri, const std::filesystem::path &path, - const std::string &version); + MTConnectSchemaList registerDirectory(const std::string& uri, const std::filesystem::path& path, + const std::string& version); /// @brief Register a single file /// @param uri the uri for the file /// @param pathName the std filesystem path of file /// @param version the schema version when registering MTConnect files /// @return an optional XmlNamespace if successful - std::optional registerFile(const std::string &uri, - const std::filesystem::path &path, - const std::string &version); + std::optional registerFile(const std::string& uri, + const std::filesystem::path& path, + const std::string& version); /// @brief get a cached file given a filename and optional encoding /// @param name the name of the file from the server /// @param acceptEncoding optional accepted encodings /// @param context optional context to perform async io /// @return shared pointer to the cached file - CachedFilePtr getFile(const std::string &name, + CachedFilePtr getFile(const std::string& name, const std::optional acceptEncoding = std::nullopt, - boost::asio::io_context *context = nullptr); + boost::asio::io_context* context = nullptr); /// @brief check if the file is cached /// @param name the name of the file from the server /// @return `true` if the file is cached - bool hasFile(const std::string &name) const + bool hasFile(const std::string& name) const { return (m_fileCache.count(name) > 0) || (m_fileMap.count(name) > 0); } /// @brief Register an file name extension with a mime type /// @param ext the extension (will insert a leading dot if one is not provided) /// @param type the mime type - void addMimeType(const std::string &ext, const std::string &type) + void addMimeType(const std::string& ext, const std::string& type) { std::string s(ext); if (s[0] != '.') @@ -116,7 +116,7 @@ namespace mtconnect::sink::rest_sink { /// @param path the path on the files system /// @param index the default file to return for the directory if one is not given. For example, /// `index.html` - void addDirectory(const std::string &uri, const std::string &path, const std::string &index); + void addDirectory(const std::string& uri, const std::string& path, const std::string& index); /// @brief Set the maximum size of the cache /// @param s the maximum size @@ -141,8 +141,8 @@ namespace mtconnect::sink::rest_sink { void clear() { m_fileCache.clear(); } ///@} protected: - CachedFilePtr findFileInDirectories(const std::string &name); - const std::string &getMimeType(std::string ext) + CachedFilePtr findFileInDirectories(const std::string& name); + const std::string& getMimeType(std::string ext) { static std::string octStream("application/octet-stream"); auto mt = m_mimeTypes.find(ext); @@ -152,8 +152,8 @@ namespace mtconnect::sink::rest_sink { return octStream; } - CachedFilePtr redirect(const std::string &name, const Directory &directory); - void compressFile(CachedFilePtr file, boost::asio::io_context *context); + CachedFilePtr redirect(const std::string& name, const Directory& directory); + void compressFile(CachedFilePtr file, boost::asio::io_context* context); protected: std::map> m_directories; diff --git a/src/mtconnect/sink/rest_sink/parameter.hpp b/src/mtconnect/sink/rest_sink/parameter.hpp index c1cc4b57..e275ef73 100644 --- a/src/mtconnect/sink/rest_sink/parameter.hpp +++ b/src/mtconnect/sink/rest_sink/parameter.hpp @@ -61,16 +61,16 @@ namespace mtconnect::sink::rest_sink { /// @param n the name of the parameter /// @param t the parameter type. defaults to STRING /// @param p path or query portion of the URI - Parameter(const std::string &n, ParameterType t = STRING, UrlPart p = PATH) + Parameter(const std::string& n, ParameterType t = STRING, UrlPart p = PATH) : m_name(n), m_type(t), m_part(p) {} - Parameter(const std::string_view &n, ParameterType t = STRING, UrlPart p = PATH) + Parameter(const std::string_view& n, ParameterType t = STRING, UrlPart p = PATH) : m_name(n), m_type(t), m_part(p) {} - Parameter(const Parameter &o) = default; + Parameter(const Parameter& o) = default; /// @brief to support std::set interface - bool operator<(const Parameter &o) const { return m_name < o.m_name; } + bool operator<(const Parameter& o) const { return m_name < o.m_name; } const std::string getTypeName() const { @@ -125,11 +125,11 @@ namespace mtconnect::sink::rest_sink { } /// @brief Helper to convert a ParameterValue to a string - static std::string toString(const ParameterValue &v) + static std::string toString(const ParameterValue& v) { using namespace std::string_literals; - return std::visit(overloaded {[](const std::monostate &) { return "none"s; }, - [](const std::string &s) { return s; }, + return std::visit(overloaded {[](const std::monostate&) { return "none"s; }, + [](const std::string& s) { return s; }, [](int32_t i) { return std::to_string(i); }, [](uint64_t i) { return std::to_string(i); }, [](double d) { return std::to_string(d); }, @@ -154,7 +154,7 @@ namespace mtconnect::sink::rest_sink { /// @param[in] part part of the URL: `PATH` or `QUERY` /// @param[in] summary brief description of the parameter /// @param[in] description detailed description of the parameter - ParameterDoc(const std::string &name, UrlPart part, + ParameterDoc(const std::string& name, UrlPart part, const std::optional description) : m_name(name), m_part(part), m_description(description) {} diff --git a/src/mtconnect/sink/rest_sink/request.hpp b/src/mtconnect/sink/rest_sink/request.hpp index b44b22ed..8087578c 100644 --- a/src/mtconnect/sink/rest_sink/request.hpp +++ b/src/mtconnect/sink/rest_sink/request.hpp @@ -36,7 +36,7 @@ namespace mtconnect::sink::rest_sink { struct Request { Request() = default; - Request(const Request &request) = default; + Request(const Request& request) = default; boost::beast::http::verb m_verb; ///< GET, PUT, POST, or DELETE std::string m_body; ///< The body of the request @@ -64,7 +64,7 @@ namespace mtconnect::sink::rest_sink { /// @param s the name of the parameter /// @return an option type `T` if the parameter is found template - std::optional parameter(const std::string &s) const + std::optional parameter(const std::string& s) const { auto v = m_parameters.find(s); if (v == m_parameters.end()) @@ -82,7 +82,7 @@ namespace mtconnect::sink::rest_sink { { std::stringstream uri; uri << m_path << '/' << *m_command << '?'; - for (auto &p : m_parameters) + for (auto& p : m_parameters) { uri << p.first << '=' << Parameter::toString(p.second) << '&'; } @@ -93,7 +93,7 @@ namespace mtconnect::sink::rest_sink { { std::stringstream uri; uri << m_path << '?'; - for (auto &q : m_query) + for (auto& q : m_query) uri << q.first << '=' << q.second << '&'; s = uri.str(); s.erase(s.length() - 1); diff --git a/src/mtconnect/sink/rest_sink/response.hpp b/src/mtconnect/sink/rest_sink/response.hpp index b5ac7ea9..bbeb78c9 100644 --- a/src/mtconnect/sink/rest_sink/response.hpp +++ b/src/mtconnect/sink/rest_sink/response.hpp @@ -44,8 +44,8 @@ namespace mtconnect { /// @param[in] status the status /// @param[in] body the body of the response /// @param[in] mimeType the mime type of the response - Response(status status = status::ok, const std::string &body = "", - const std::string &mimeType = "text/xml") + Response(status status = status::ok, const std::string& body = "", + const std::string& mimeType = "text/xml") : m_status(status), m_body(body), m_mimeType(mimeType), m_expires(0) {} /// @brief Create a response with a status and a cached file diff --git a/src/mtconnect/sink/rest_sink/rest_service.cpp b/src/mtconnect/sink/rest_sink/rest_service.cpp index 043df948..5160026b 100644 --- a/src/mtconnect/sink/rest_sink/rest_service.cpp +++ b/src/mtconnect/sink/rest_sink/rest_service.cpp @@ -43,8 +43,8 @@ namespace mtconnect { using namespace buffer; namespace sink::rest_sink { - RestService::RestService(asio::io_context &context, SinkContractPtr &&contract, - const ConfigOptions &options, const ptree &config) + RestService::RestService(asio::io_context& context, SinkContractPtr&& contract, + const ConfigOptions& options, const ptree& config) : Sink("RestService", std::move(contract)), m_context(context), m_strand(context), @@ -88,8 +88,8 @@ namespace mtconnect { m_baseUrl = *base; m_server->setBaseUrl(m_baseUrl); - auto xmlPrinter = dynamic_cast(m_sinkContract->getPrinter("xml")); - auto jsonPrinter = dynamic_cast(m_sinkContract->getPrinter("json")); + auto xmlPrinter = dynamic_cast(m_sinkContract->getPrinter("xml")); + auto jsonPrinter = dynamic_cast(m_sinkContract->getPrinter("json")); // Files served by the Agent... allows schema files to be served by // agent. @@ -150,12 +150,12 @@ namespace mtconnect { } // Register the service with the sink factory - void RestService::registerFactory(SinkFactory &factory) + void RestService::registerFactory(SinkFactory& factory) { factory.registerFactory( "RestService", - [](const std::string &name, boost::asio::io_context &io, SinkContractPtr &&contract, - const ConfigOptions &options, const boost::property_tree::ptree &block) -> SinkPtr { + [](const std::string& name, boost::asio::io_context& io, SinkContractPtr&& contract, + const ConfigOptions& options, const boost::property_tree::ptree& block) -> SinkPtr { auto sink = std::make_shared(io, std::move(contract), options, block); return sink; }); @@ -166,14 +166,14 @@ namespace mtconnect { void RestService::stop() { m_server->stop(); } // Configuration - void RestService::loadNamespace(const ptree &tree, const char *namespaceType, - XmlPrinter *xmlPrinter, NamespaceFunction callback) + void RestService::loadNamespace(const ptree& tree, const char* namespaceType, + XmlPrinter* xmlPrinter, NamespaceFunction callback) { // Load namespaces, allow for local file system serving as well. auto ns = tree.get_child_optional(namespaceType); if (ns) { - for (const auto &block : *ns) + for (const auto& block : *ns) { auto urn = block.second.get_optional("Urn"); if (block.first != "m" && !urn) @@ -200,8 +200,8 @@ namespace mtconnect { } // Configuration - void RestService::loadJsonSchema(const ptree &tree, const char *schemaType, - JsonPrinter *jsonPrinter, SchemaFunction callback) + void RestService::loadJsonSchema(const ptree& tree, const char* schemaType, + JsonPrinter* jsonPrinter, SchemaFunction callback) { // Load namespaces, allow for local file system serving as well. auto schema = tree.get_child_optional(schemaType); @@ -232,12 +232,12 @@ namespace mtconnect { } } - void RestService::loadFiles(XmlPrinter *xmlPrinter, JsonPrinter *jsonPrinter, const ptree &tree) + void RestService::loadFiles(XmlPrinter* xmlPrinter, JsonPrinter* jsonPrinter, const ptree& tree) { auto files = tree.get_child_optional("Files"); if (files) { - for (const auto &file : *files) + for (const auto& file : *files) { auto location = file.second.get_optional("Location"); auto path = file.second.get_optional("Path"); @@ -257,7 +257,7 @@ namespace mtconnect { else { auto namespaces = m_fileCache.registerFiles(*location, *resolved, m_schemaVersion); - for (auto &ns : namespaces) + for (auto& ns : namespaces) { string urn = "urn:mtconnect.org:MTConnect" + ns.m_doc + ":" + m_schemaVersion; if (ns.m_doc == "Devices") @@ -297,7 +297,7 @@ namespace mtconnect { auto dirs = tree.get_child_optional("Directories"); if (dirs) { - for (const auto &dir : *dirs) + for (const auto& dir : *dirs) { auto location = dir.second.get_optional("Location"); auto path = dir.second.get_optional("Path"); @@ -325,13 +325,13 @@ namespace mtconnect { } } - void RestService::loadHttpHeaders(const ptree &tree) + void RestService::loadHttpHeaders(const ptree& tree) { auto headers = tree.get_child_optional(config::HttpHeaders); if (headers) { StringList fields; - for (auto &f : *headers) + for (auto& f : *headers) { fields.emplace_back(f.first + ": " + f.second.data()); } @@ -340,7 +340,7 @@ namespace mtconnect { } } - void RestService::loadStyle(const ptree &tree, const char *styleName, XmlPrinter *xmlPrinter, + void RestService::loadStyle(const ptree& tree, const char* styleName, XmlPrinter* xmlPrinter, StyleFunction styleFunction) { namespace fs = std::filesystem; @@ -407,12 +407,12 @@ namespace mtconnect { } } - void RestService::loadTypes(const ptree &tree) + void RestService::loadTypes(const ptree& tree) { auto types = tree.get_child_optional("MimeTypes"); if (types) { - for (const auto &type : *types) + for (const auto& type : *types) { m_fileCache.addMimeType(type.first, type.second.data()); } @@ -449,9 +449,9 @@ namespace mtconnect { } else { - for (const auto &res : results) + for (const auto& res : results) { - const auto &a = res.endpoint().address(); + const auto& a = res.endpoint().address(); if (!a.is_multicast() && !a.is_unspecified()) { m_server->allowPutFrom(a.to_string()); @@ -499,7 +499,7 @@ namespace mtconnect { // Request Routings // ----------------------------------------------------------- - static inline void respond(rest_sink::SessionPtr session, rest_sink::ResponsePtr &&response, + static inline void respond(rest_sink::SessionPtr session, rest_sink::ResponsePtr&& response, std::optional id = std::nullopt) { response->m_requestId = id; @@ -704,9 +704,9 @@ namespace mtconnect { return true; }; - for (const auto &asset : list {"asset", "assets"}) + for (const auto& asset : list {"asset", "assets"}) { - for (const auto &t : list {boost::beast::http::verb::put, + for (const auto& t : list {boost::beast::http::verb::put, boost::beast::http::verb::post}) { m_server @@ -924,16 +924,16 @@ namespace mtconnect { // Observation Add Method // ---------------------------------------------------- - bool RestService::publish(ObservationPtr &observation) { return true; } + bool RestService::publish(ObservationPtr& observation) { return true; } // ------------------------------------------- // ReST API Requests // ------------------------------------------- - ResponsePtr RestService::probeRequest(const Printer *printer, - const std::optional &device, bool pretty, - const std::optional &deviceType, - const std::optional &requestId) + ResponsePtr RestService::probeRequest(const Printer* printer, + const std::optional& device, bool pretty, + const std::optional& deviceType, + const std::optional& requestId) { NAMED_SCOPE("RestService::probeRequest"); @@ -950,7 +950,7 @@ namespace mtconnect { if (deviceType) { deviceList.remove_if( - [&deviceType](const DevicePtr &dev) { return dev->getName() != *deviceType; }); + [&deviceType](const DevicePtr& dev) { return dev->getName() != *deviceType; }); } } @@ -966,12 +966,12 @@ namespace mtconnect { printer->mimeType()); } - ResponsePtr RestService::currentRequest(const Printer *printer, - const std::optional &device, - const std::optional &at, - const std::optional &path, bool pretty, - const std::optional &deviceType, - const std::optional &requestId) + ResponsePtr RestService::currentRequest(const Printer* printer, + const std::optional& device, + const std::optional& at, + const std::optional& path, bool pretty, + const std::optional& deviceType, + const std::optional& requestId) { using namespace rest_sink; DevicePtr dev {nullptr}; @@ -992,13 +992,13 @@ namespace mtconnect { printer->mimeType()); } - ResponsePtr RestService::sampleRequest(const Printer *printer, const int count, - const std::optional &device, - const std::optional &from, - const std::optional &to, - const std::optional &path, bool pretty, - const std::optional &deviceType, - const std::optional &requestId) + ResponsePtr RestService::sampleRequest(const Printer* printer, const int count, + const std::optional& device, + const std::optional& from, + const std::optional& to, + const std::optional& path, bool pretty, + const std::optional& deviceType, + const std::optional& requestId) { using namespace rest_sink; DevicePtr dev {nullptr}; @@ -1025,15 +1025,15 @@ namespace mtconnect { struct AsyncSampleResponse : public observation::AsyncObserver { - AsyncSampleResponse(boost::asio::io_context::strand &strand, - mtconnect::buffer::CircularBuffer &buffer, FilterSet &&filter, + AsyncSampleResponse(boost::asio::io_context::strand& strand, + mtconnect::buffer::CircularBuffer& buffer, FilterSet&& filter, std::chrono::milliseconds interval, std::chrono::milliseconds heartbeat, - rest_sink::SessionPtr &session) + rest_sink::SessionPtr& session) : observation::AsyncObserver(strand, buffer, std::move(filter), interval, heartbeat), m_session(session) {} - void fail(boost::beast::http::status status, const std::string &message) override + void fail(boost::beast::http::status status, const std::string& message) override { auto sink = m_sink.lock(); if (sink && isRunning()) @@ -1050,7 +1050,7 @@ namespace mtconnect { bool isRunning() override { auto sink = m_sink.lock(); - Server *server {nullptr}; + Server* server {nullptr}; if (sink) { server = dynamic_pointer_cast(sink)->getServer(); @@ -1076,20 +1076,20 @@ namespace mtconnect { std::weak_ptr m_sink; //! weak shared pointer to the sink. handles shutdown timer race int m_count {0}; - const Printer *m_printer {nullptr}; + const Printer* m_printer {nullptr}; bool m_logStreamData {false}; rest_sink::SessionPtr m_session; ofstream m_log; bool m_pretty {false}; }; - void RestService::streamSampleRequest(rest_sink::SessionPtr session, const Printer *printer, + void RestService::streamSampleRequest(rest_sink::SessionPtr session, const Printer* printer, const int interval, const int heartbeatIn, - const int count, const std::optional &device, - const std::optional &from, - const std::optional &path, bool pretty, - const std::optional &deviceType, - const std::optional &requestId) + const int count, const std::optional& device, + const std::optional& from, + const std::optional& path, bool pretty, + const std::optional& deviceType, + const std::optional& requestId) { NAMED_SCOPE("RestService::streamSampleRequest"); @@ -1134,7 +1134,7 @@ namespace mtconnect { } asyncResponse->m_logStreamData = m_logStreamData; - asyncResponse->observe(from, [this](const std::string &id) { + asyncResponse->observe(from, [this](const std::string& id) { return m_sinkContract->getDataItemById(id).get(); }); asyncResponse->m_handler = boost::bind(&RestService::streamNextSampleChunk, this, _1); @@ -1184,7 +1184,7 @@ namespace mtconnect { return end; } - catch (RestError &re) + catch (RestError& re) { LOG(error) << asyncResponse->m_session->getRemote().address() << ": Error processing request: " << re.what(); @@ -1210,7 +1210,7 @@ namespace mtconnect { struct AsyncCurrentResponse : public AsyncResponse { - AsyncCurrentResponse(rest_sink::SessionPtr session, asio::io_context &context, + AsyncCurrentResponse(rest_sink::SessionPtr session, asio::io_context& context, chrono::milliseconds interval) : AsyncResponse(interval), m_session(session), m_timer(context) {} @@ -1228,18 +1228,18 @@ namespace mtconnect { std::weak_ptr m_service; rest_sink::SessionPtr m_session; - const Printer *m_printer {nullptr}; + const Printer* m_printer {nullptr}; FilterSetOpt m_filter; boost::asio::steady_timer m_timer; bool m_pretty {false}; }; - void RestService::streamCurrentRequest(SessionPtr session, const Printer *printer, + void RestService::streamCurrentRequest(SessionPtr session, const Printer* printer, const int interval, - const std::optional &device, - const std::optional &path, bool pretty, - const std::optional &deviceType, - const std::optional &requestId) + const std::optional& device, + const std::optional& path, bool pretty, + const std::optional& deviceType, + const std::optional& requestId) { checkRange(printer, interval, 0, numeric_limits().max(), "interval"); DevicePtr dev {nullptr}; @@ -1317,7 +1317,7 @@ namespace mtconnect { asyncResponse->getRequestId()); } } - catch (RestError &re) + catch (RestError& re) { LOG(error) << asyncResponse->m_session->getRemote().address() << ": Error processing request: " << re.what(); @@ -1342,11 +1342,11 @@ namespace mtconnect { } } - ResponsePtr RestService::assetRequest(const Printer *printer, const int32_t count, + ResponsePtr RestService::assetRequest(const Printer* printer, const int32_t count, const bool removed, - const std::optional &type, - const std::optional &device, bool pretty, - const std::optional &requestId) + const std::optional& type, + const std::optional& device, bool pretty, + const std::optional& requestId) { using namespace rest_sink; @@ -1368,9 +1368,9 @@ namespace mtconnect { printer->mimeType()); } - ResponsePtr RestService::assetIdsRequest(const Printer *printer, - const std::list &ids, bool pretty, - const std::optional &requestId) + ResponsePtr RestService::assetIdsRequest(const Printer* printer, + const std::list& ids, bool pretty, + const std::optional& requestId) { using namespace rest_sink; @@ -1378,7 +1378,7 @@ namespace mtconnect { if (m_sinkContract->getAssetStorage()->getAssets(list, ids) == 0) { entity::EntityList errors; - for (auto &id : ids) + for (auto& id : ids) errors.emplace_back(AssetNotFound::make(id, "Cannot find asset: " + id)); throw RestError(errors, printer, status::not_found, std::nullopt, requestId); } @@ -1393,10 +1393,10 @@ namespace mtconnect { } } - ResponsePtr RestService::putAssetRequest(const Printer *printer, const std::string &asset, - const std::optional &type, - const std::optional &device, - const std::optional &uuid) + ResponsePtr RestService::putAssetRequest(const Printer* printer, const std::string& asset, + const std::optional& type, + const std::optional& device, + const std::optional& uuid) { using namespace rest_sink; @@ -1417,7 +1417,7 @@ namespace mtconnect { else errorList.emplace_back( Error::make(Error::ErrorCode::INVALID_REQUEST, "Asset parsed with errors.")); - for (auto &e : errors) + for (auto& e : errors) { errorList.emplace_back(Error::make(Error::ErrorCode::INVALID_REQUEST, e->what())); } @@ -1434,8 +1434,8 @@ namespace mtconnect { printer->mimeType()); } - ResponsePtr RestService::deleteAssetRequest(const Printer *printer, - const std::list &ids) + ResponsePtr RestService::deleteAssetRequest(const Printer* printer, + const std::list& ids) { using namespace rest_sink; AssetList list; @@ -1456,15 +1456,15 @@ namespace mtconnect { else { entity::EntityList errors; - for (auto &id : ids) + for (auto& id : ids) errors.emplace_back(AssetNotFound::make(id, "Cannot find asset: " + id)); throw RestError(errors, printer, status::not_found); } } - ResponsePtr RestService::deleteAllAssetsRequest(const Printer *printer, - const std::optional &device, - const std::optional &type) + ResponsePtr RestService::deleteAllAssetsRequest(const Printer* printer, + const std::optional& device, + const std::optional& type) { AssetList list; if (m_sinkContract->getAssetStorage()->getAssets(list, std::numeric_limits().max(), @@ -1485,10 +1485,10 @@ namespace mtconnect { } } - ResponsePtr RestService::putObservationRequest(const Printer *printer, - const std::string &device, + ResponsePtr RestService::putObservationRequest(const Printer* printer, + const std::string& device, const rest_sink::QueryMap observations, - const std::optional &time) + const std::optional& time) { using namespace rest_sink; @@ -1505,7 +1505,7 @@ namespace mtconnect { auto dev = checkDevice(printer, device); entity::EntityList errors; - for (auto &qp : observations) + for (auto& qp : observations) { auto di = dev->getDeviceDataItem(qp.first); if (di == nullptr) @@ -1544,13 +1544,13 @@ namespace mtconnect { void RestService::setLogStreamData(bool log) { m_logStreamData = log; } // Get the printer for a type - const std::string RestService::acceptFormat(const std::string &accepts) const + const std::string RestService::acceptFormat(const std::string& accepts) const { std::stringstream list(accepts); std::string accept; while (std::getline(list, accept, ',')) { - for (const auto &p : m_sinkContract->getPrinters()) + for (const auto& p : m_sinkContract->getPrinters()) { if (accept.ends_with(p.first)) return p.first; @@ -1564,8 +1564,8 @@ namespace mtconnect { // ----------------------------------------------- template - void RestService::checkRange(const Printer *printer, const T value, const T min, const T max, - const string ¶m, bool notZero) const + void RestService::checkRange(const Printer* printer, const T value, const T min, const T max, + const string& param, bool notZero) const { stringstream str; if (value <= min) @@ -1587,15 +1587,15 @@ namespace mtconnect { } } - void RestService::checkPath(const Printer *printer, const std::optional &path, - const DevicePtr device, FilterSet &filter, - const std::optional &deviceType) const + void RestService::checkPath(const Printer* printer, const std::optional& path, + const DevicePtr device, FilterSet& filter, + const std::optional& deviceType) const { try { m_sinkContract->getDataItemsForPath(device, path, filter, deviceType); } - catch (exception &e) + catch (exception& e) { string msg = "The path could not be parsed. Invalid syntax: "s + e.what(); auto error = Error::make(Error::ErrorCode::INVALID_XPATH, msg); @@ -1610,7 +1610,7 @@ namespace mtconnect { } } - DevicePtr RestService::checkDevice(const Printer *printer, const std::string &uuid) const + DevicePtr RestService::checkDevice(const Printer* printer, const std::string& uuid) const { auto dev = m_sinkContract->findDeviceByUUIDorName(uuid); if (!dev) @@ -1627,9 +1627,9 @@ namespace mtconnect { // Data Collection and Formatting // ------------------------------------------- - string RestService::fetchCurrentData(const Printer *printer, const FilterSetOpt &filterSet, - const optional &at, bool pretty, - const std::optional &requestId) + string RestService::fetchCurrentData(const Printer* printer, const FilterSetOpt& filterSet, + const optional& at, bool pretty, + const std::optional& requestId) { ObservationList observations; SequenceNumber_t firstSeq, seq; @@ -1656,11 +1656,11 @@ namespace mtconnect { seq, firstSeq, seq - 1, observations, pretty, requestId); } - string RestService::fetchSampleData(const Printer *printer, const FilterSetOpt &filterSet, - int count, const std::optional &from, - const std::optional &to, - SequenceNumber_t &end, bool &endOfBuffer, bool pretty, - const std::optional &requestId) + string RestService::fetchSampleData(const Printer* printer, const FilterSetOpt& filterSet, + int count, const std::optional& from, + const std::optional& to, + SequenceNumber_t& end, bool& endOfBuffer, bool pretty, + const std::optional& requestId) { std::unique_ptr observations; SequenceNumber_t firstSeq, lastSeq; diff --git a/src/mtconnect/sink/rest_sink/rest_service.hpp b/src/mtconnect/sink/rest_sink/rest_service.hpp index 361b6ff1..f78bfd53 100644 --- a/src/mtconnect/sink/rest_sink/rest_service.hpp +++ b/src/mtconnect/sink/rest_sink/rest_service.hpp @@ -43,15 +43,14 @@ namespace mtconnect { struct AsyncCurrentResponse; /// @brief Callback fundtion for setting namespaces - using NamespaceFunction = void (printer::XmlPrinter::*)(const std::string &, - const std::string &, - const std::string &); + using NamespaceFunction = void (printer::XmlPrinter::*)(const std::string&, const std::string&, + const std::string&); /// @brief Callback fundtion for setting json schema - using SchemaFunction = void (printer::JsonPrinter::*)(const std::string &); + using SchemaFunction = void (printer::JsonPrinter::*)(const std::string&); /// @brief Callback fundtion for setting stylesheet - using StyleFunction = void (printer::XmlPrinter::*)(const std::string &); + using StyleFunction = void (printer::XmlPrinter::*)(const std::string&); /// @brief The Sink for the MTConnect normative REST Service class AGENT_LIB_API RestService : public Sink @@ -62,14 +61,14 @@ namespace mtconnect { /// @param contract the Sink Contract from the agent /// @param options configuration options /// @param config additional configuration options if specified directly as a sink - RestService(boost::asio::io_context &context, SinkContractPtr &&contract, - const ConfigOptions &options, const boost::property_tree::ptree &config); + RestService(boost::asio::io_context& context, SinkContractPtr&& contract, + const ConfigOptions& options, const boost::property_tree::ptree& config); ~RestService() = default; /// @brief Register the Sink factory to create this sink /// @param factory - static void registerFactory(SinkFactory &factory); + static void registerFactory(SinkFactory& factory); /// @brief Make a loopback source to handle PUT, POST, and DELETE /// @param context the pipeline context @@ -83,7 +82,7 @@ namespace mtconnect { void stop() override; - bool publish(observation::ObservationPtr &observation) override; + bool publish(observation::ObservationPtr& observation) override; bool publish(asset::AssetPtr asset) override { return false; } ///@} @@ -103,11 +102,11 @@ namespace mtconnect { /// @param[in] device optional device name or uuid /// @param[in] pretty `true` to ensure response is formatted /// @return MTConnect Devices response - ResponsePtr probeRequest(const printer::Printer *p, - const std::optional &device = std::nullopt, + ResponsePtr probeRequest(const printer::Printer* p, + const std::optional& device = std::nullopt, bool pretty = false, - const std::optional &deviceType = std::nullopt, - const std::optional &requestId = std::nullopt); + const std::optional& deviceType = std::nullopt, + const std::optional& requestId = std::nullopt); /// @brief Handler for a current request /// @param[in] p printer for doc generation @@ -116,13 +115,13 @@ namespace mtconnect { /// @param[in] path an xpath to filter /// @param[in] pretty `true` to ensure response is formatted /// @return MTConnect Streams response - ResponsePtr currentRequest(const printer::Printer *p, - const std::optional &device = std::nullopt, - const std::optional &at = std::nullopt, - const std::optional &path = std::nullopt, + ResponsePtr currentRequest(const printer::Printer* p, + const std::optional& device = std::nullopt, + const std::optional& at = std::nullopt, + const std::optional& path = std::nullopt, bool pretty = false, - const std::optional &deviceType = std::nullopt, - const std::optional &requestId = std::nullopt); + const std::optional& deviceType = std::nullopt, + const std::optional& requestId = std::nullopt); /// @brief Handler for a sample request /// @param[in] p printer for doc generation @@ -133,14 +132,14 @@ namespace mtconnect { /// @param[in] path an xpath for filtering /// @param[in] pretty `true` to ensure response is formatted /// @return MTConnect Streams response - ResponsePtr sampleRequest(const printer::Printer *p, const int count = 100, - const std::optional &device = std::nullopt, - const std::optional &from = std::nullopt, - const std::optional &to = std::nullopt, - const std::optional &path = std::nullopt, + ResponsePtr sampleRequest(const printer::Printer* p, const int count = 100, + const std::optional& device = std::nullopt, + const std::optional& from = std::nullopt, + const std::optional& to = std::nullopt, + const std::optional& path = std::nullopt, bool pretty = false, - const std::optional &deviceType = std::nullopt, - const std::optional &requestId = std::nullopt); + const std::optional& deviceType = std::nullopt, + const std::optional& requestId = std::nullopt); /// @brief Handler for a streaming sample /// @param[in] session session to stream data to /// @param[in] p printer for doc generation @@ -151,14 +150,14 @@ namespace mtconnect { /// @param[in] from optional starting sequence number /// @param[in] path optional path for filtering /// @param[in] pretty `true` to ensure response is formatted - void streamSampleRequest(SessionPtr session, const printer::Printer *p, const int interval, + void streamSampleRequest(SessionPtr session, const printer::Printer* p, const int interval, const int heartbeat, const int count = 100, - const std::optional &device = std::nullopt, - const std::optional &from = std::nullopt, - const std::optional &path = std::nullopt, + const std::optional& device = std::nullopt, + const std::optional& from = std::nullopt, + const std::optional& path = std::nullopt, bool pretty = false, - const std::optional &deviceType = std::nullopt, - const std::optional &requestId = std::nullopt); + const std::optional& deviceType = std::nullopt, + const std::optional& requestId = std::nullopt); /// @brief Handler for a streaming current /// @param[in] session session to stream data to @@ -167,21 +166,21 @@ namespace mtconnect { /// @param[in] device optional device name or uuid /// @param[in] path optional path for filtering /// @param[in] pretty `true` to ensure response is formatted - void streamCurrentRequest(SessionPtr session, const printer::Printer *p, const int interval, - const std::optional &device = std::nullopt, - const std::optional &path = std::nullopt, + void streamCurrentRequest(SessionPtr session, const printer::Printer* p, const int interval, + const std::optional& device = std::nullopt, + const std::optional& path = std::nullopt, bool pretty = false, - const std::optional &deviceType = std::nullopt, - const std::optional &requestId = std::nullopt); + const std::optional& deviceType = std::nullopt, + const std::optional& requestId = std::nullopt); /// @brief Handler for put/post observation /// @param[in] p printer for response generation /// @param[in] device device /// @param[in] observations key/value pairs for the observations /// @param[in] time optional timestamp /// @return `` if succeeds - ResponsePtr putObservationRequest(const printer::Printer *p, const std::string &device, + ResponsePtr putObservationRequest(const printer::Printer* p, const std::string& device, const QueryMap observations, - const std::optional &time = std::nullopt); + const std::optional& time = std::nullopt); ///@} @@ -212,20 +211,20 @@ namespace mtconnect { /// @param[in] device optional device name or uuid /// @param[in] pretty `true` to ensure response is formatted /// @return MTConnect Assets response document - ResponsePtr assetRequest(const printer::Printer *p, const int32_t count, const bool removed, - const std::optional &type = std::nullopt, - const std::optional &device = std::nullopt, + ResponsePtr assetRequest(const printer::Printer* p, const int32_t count, const bool removed, + const std::optional& type = std::nullopt, + const std::optional& device = std::nullopt, bool pretty = false, - const std::optional &requestId = std::nullopt); + const std::optional& requestId = std::nullopt); /// @brief Asset request handler using a list of asset ids /// @param[in] p printer for the response document /// @param[in] ids list of asset ids /// @param[in] pretty `true` to ensure response is formatted /// @return MTConnect Assets response document - ResponsePtr assetIdsRequest(const printer::Printer *p, const std::list &ids, + ResponsePtr assetIdsRequest(const printer::Printer* p, const std::list& ids, bool pretty = false, - const std::optional &requestId = std::nullopt); + const std::optional& requestId = std::nullopt); /// @brief Asset request handler to update an asset /// @param p printer for the response document @@ -234,23 +233,23 @@ namespace mtconnect { /// @param device option device, if not given will derive from `asset` /// @param uuid optional asset id, if not given will derive from the `asset` /// @return MTConnect Assets response document - ResponsePtr putAssetRequest(const printer::Printer *p, const std::string &asset, - const std::optional &type, - const std::optional &device = std::nullopt, - const std::optional &uuid = std::nullopt); + ResponsePtr putAssetRequest(const printer::Printer* p, const std::string& asset, + const std::optional& type, + const std::optional& device = std::nullopt, + const std::optional& uuid = std::nullopt); /// @brief Asset request handler to delete a a list of asset ids /// @param p printer for the response document /// @param ids the list of ids /// @return MTConnect Assets response document - ResponsePtr deleteAssetRequest(const printer::Printer *p, const std::list &ids); + ResponsePtr deleteAssetRequest(const printer::Printer* p, const std::list& ids); /// @brief Asset request handler to delete all assets by device and/or type /// @param p printer for the response document /// @param device optional device /// @param type optonal type /// @return number of assets removed as response - ResponsePtr deleteAllAssetsRequest(const printer::Printer *p, - const std::optional &device = std::nullopt, - const std::optional &type = std::nullopt); + ResponsePtr deleteAllAssetsRequest(const printer::Printer* p, + const std::optional& device = std::nullopt, + const std::optional& type = std::nullopt); ///@} /// @brief For debugging: turn on stream data logging @@ -260,11 +259,11 @@ namespace mtconnect { /// @brief Check the accepts header for a matching printer key /// @param accepts the accepts header /// @return printer key or `xml` if one is not found - const std::string acceptFormat(const std::string &accepts) const; + const std::string acceptFormat(const std::string& accepts) const; /// @brief get a printer given a list of formats from the Accepts header /// @param accepts the accepts header /// @return pointer to a printer - const printer::Printer *printerForAccepts(const std::string &accepts) const + const printer::Printer* printerForAccepts(const std::string& accepts) const { return m_sinkContract->getPrinter(acceptFormat(accepts)); } @@ -274,10 +273,10 @@ namespace mtconnect { /// @param accepts the accept header of the request /// @param format optional format query param /// @return pointer to a printer - const printer::Printer *getPrinter(const std::string &accepts, + const printer::Printer* getPrinter(const std::string& accepts, std::optional format) const { - const printer::Printer *printer = nullptr; + const printer::Printer* printer = nullptr; if (format) printer = m_sinkContract->getPrinter(*format); if (printer == nullptr) @@ -299,13 +298,13 @@ namespace mtconnect { /// to use. /// @param session the session to write to /// @param error the error to write - void writeErrorResponse(SessionPtr session, const RestError &error) + void writeErrorResponse(SessionPtr session, const RestError& error) { LOG(debug) << "Returning error: " << error.what(); if (m_sinkContract) { - const auto *prnt = error.getPrinter(); + const auto* prnt = error.getPrinter(); if (!prnt) { prnt = getPrinter(error.getAccepts(), error.getFormat()); @@ -324,21 +323,21 @@ namespace mtconnect { } // Configuration - void loadNamespace(const boost::property_tree::ptree &tree, const char *namespaceType, - printer::XmlPrinter *xmlPrinter, NamespaceFunction callback); + void loadNamespace(const boost::property_tree::ptree& tree, const char* namespaceType, + printer::XmlPrinter* xmlPrinter, NamespaceFunction callback); - void loadJsonSchema(const boost::property_tree::ptree &tree, const char *schemaType, - printer::JsonPrinter *jsonPrinter, SchemaFunction callback); + void loadJsonSchema(const boost::property_tree::ptree& tree, const char* schemaType, + printer::JsonPrinter* jsonPrinter, SchemaFunction callback); - void loadFiles(printer::XmlPrinter *xmlPrinter, printer::JsonPrinter *jsonPrinter, - const boost::property_tree::ptree &tree); + void loadFiles(printer::XmlPrinter* xmlPrinter, printer::JsonPrinter* jsonPrinter, + const boost::property_tree::ptree& tree); - void loadHttpHeaders(const boost::property_tree::ptree &tree); + void loadHttpHeaders(const boost::property_tree::ptree& tree); - void loadStyle(const boost::property_tree::ptree &tree, const char *styleName, - printer::XmlPrinter *xmlPrinter, StyleFunction styleFunction); + void loadStyle(const boost::property_tree::ptree& tree, const char* styleName, + printer::XmlPrinter* xmlPrinter, StyleFunction styleFunction); - void loadTypes(const boost::property_tree::ptree &tree); + void loadTypes(const boost::property_tree::ptree& tree); void loadAllowPut(); @@ -356,29 +355,29 @@ namespace mtconnect { void createAssetRoutings(); // Current Data Collection - std::string fetchCurrentData(const printer::Printer *printer, const FilterSetOpt &filterSet, - const std::optional &at, bool pretty = false, - const std::optional &requestId = std::nullopt); + std::string fetchCurrentData(const printer::Printer* printer, const FilterSetOpt& filterSet, + const std::optional& at, bool pretty = false, + const std::optional& requestId = std::nullopt); // Sample data collection - std::string fetchSampleData(const printer::Printer *printer, const FilterSetOpt &filterSet, - int count, const std::optional &from, - const std::optional &to, SequenceNumber_t &end, - bool &endOfBuffer, bool pretty = false, - const std::optional &requestId = std::nullopt); + std::string fetchSampleData(const printer::Printer* printer, const FilterSetOpt& filterSet, + int count, const std::optional& from, + const std::optional& to, SequenceNumber_t& end, + bool& endOfBuffer, bool pretty = false, + const std::optional& requestId = std::nullopt); // Verification methods template - void checkRange(const printer::Printer *printer, const T value, const T min, const T max, - const std::string ¶m, bool notZero = false) const; + void checkRange(const printer::Printer* printer, const T value, const T min, const T max, + const std::string& param, bool notZero = false) const; - void checkPath(const printer::Printer *printer, const std::optional &path, - const DevicePtr device, FilterSet &filter, - const std::optional &deviceType = std::nullopt) const; + void checkPath(const printer::Printer* printer, const std::optional& path, + const DevicePtr device, FilterSet& filter, + const std::optional& deviceType = std::nullopt) const; - DevicePtr checkDevice(const printer::Printer *printer, const std::string &uuid) const; + DevicePtr checkDevice(const printer::Printer* printer, const std::string& uuid) const; - std::string externalUrl(const std::string &url) + std::string externalUrl(const std::string& url) { std::string fullUrl = m_baseUrl; if (!fullUrl.empty() && !url.empty()) @@ -398,7 +397,7 @@ namespace mtconnect { protected: // Loopback - boost::asio::io_context &m_context; + boost::asio::io_context& m_context; boost::asio::io_context::strand m_strand; std::string m_schemaVersion; ConfigOptions m_options; diff --git a/src/mtconnect/sink/rest_sink/routing.hpp b/src/mtconnect/sink/rest_sink/routing.hpp index 2871f0fb..cde62a1d 100644 --- a/src/mtconnect/sink/rest_sink/routing.hpp +++ b/src/mtconnect/sink/rest_sink/routing.hpp @@ -46,7 +46,7 @@ namespace mtconnect::sink::rest_sink { public: using Function = std::function; - Routing(const Routing &r) = default; + Routing(const Routing& r) = default; /// @brief Create a routing with a string /// /// Creates a routing with a regular expression from the string to match against the path @@ -54,7 +54,7 @@ namespace mtconnect::sink::rest_sink { /// @param[in] pattern the URI pattern to parse and match /// @param[in] function the function to call if matches /// @param[in] swagger `true` if swagger related - Routing(boost::beast::http::verb verb, const std::string &pattern, const Function function, + Routing(boost::beast::http::verb verb, const std::string& pattern, const Function function, bool swagger = false, std::optional request = std::nullopt) : m_verb(verb), m_command(request), m_function(function), m_swagger(swagger) { @@ -80,7 +80,7 @@ namespace mtconnect::sink::rest_sink { /// @param[in] pattern the URI pattern to parse and match /// @param[in] function the function to call if matches /// @param[in] swagger `true` if swagger related - Routing(boost::beast::http::verb verb, const std::regex &pattern, const Function function, + Routing(boost::beast::http::verb verb, const std::regex& pattern, const Function function, bool swagger = false, std::optional request = std::nullopt) : m_verb(verb), m_pattern(pattern), @@ -93,7 +93,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Added summary and description to the routing /// @param[in] summary optional summary /// @param[in] description optional description of the routing - Routing &document(std::optional summary, + Routing& document(std::optional summary, std::optional description = std::nullopt) { m_summary = summary; @@ -104,13 +104,13 @@ namespace mtconnect::sink::rest_sink { /// @brief Added summary and description to the routing /// @param[in] summary optional summary /// @param[in] description optional description of the routing - Routing &documentParameter(const std::string &name, UrlPart part, + Routing& documentParameter(const std::string& name, UrlPart part, std::optional description) { - Parameter *param {nullptr}; + Parameter* param {nullptr}; if (part == PATH) { - for (auto &p : m_pathParameters) + for (auto& p : m_pathParameters) { if (p.m_name == name) { @@ -121,11 +121,11 @@ namespace mtconnect::sink::rest_sink { } else { - for (auto &p : m_queryParameters) + for (auto& p : m_queryParameters) { if (p.m_name == name) { - param = const_cast(&p); + param = const_cast(&p); break; } } @@ -139,9 +139,9 @@ namespace mtconnect::sink::rest_sink { /// @brief Document using common parameter documentation /// @param[in] docs common documentation for parameters - Routing &documentParameters(const ParameterDocList &docs) + Routing& documentParameters(const ParameterDocList& docs) { - for (const auto &doc : docs) + for (const auto& doc : docs) { documentParameter(doc.m_name, doc.m_part, doc.m_description); } @@ -150,16 +150,16 @@ namespace mtconnect::sink::rest_sink { /// @brief Get the description of the REST call for Swagger /// @returns optional string if description is givem - const auto &getDescription() const { return m_description; } + const auto& getDescription() const { return m_description; } /// @brief Get the brief summary fo the REST call for Swagger /// @returns optional string if summary is givem - const auto &getSummary() const { return m_summary; } + const auto& getSummary() const { return m_summary; } /// @brief Get the list of path position in order /// @return the parameter list - const ParameterList &getPathParameters() const { return m_pathParameters; } + const ParameterList& getPathParameters() const { return m_pathParameters; } /// @brief get the unordered set of query parameters - const QuerySet &getQueryParameters() const { return m_queryParameters; } + const QuerySet& getQueryParameters() const { return m_queryParameters; } /// @brief run the session's request if this routing matches /// @@ -196,7 +196,7 @@ namespace mtconnect::sink::rest_sink { { auto s = m.begin(); s++; - for (auto &p : m_pathParameters) + for (auto& p : m_pathParameters) { if (s != m.end()) { @@ -207,7 +207,7 @@ namespace mtconnect::sink::rest_sink { } entity::EntityList errors; - for (auto &p : m_queryParameters) + for (auto& p : m_queryParameters) { auto q = request->m_query.find(p.m_name); if (q != request->m_query.end()) @@ -217,7 +217,7 @@ namespace mtconnect::sink::rest_sink { auto v = convertValue(q->second, p.m_type); request->m_parameters.emplace(make_pair(p.m_name, v)); } - catch (ParameterError &e) + catch (ParameterError& e) { std::string msg = std::string("query parameter '") + p.m_name + "': " + e.what(); @@ -254,7 +254,7 @@ namespace mtconnect::sink::rest_sink { { entity::EntityList errors; /// Just validate the types of the parameters - for (auto &p : m_pathParameters) + for (auto& p : m_pathParameters) { auto it = request->m_parameters.find(p.m_name); if (it != request->m_parameters.end()) @@ -271,7 +271,7 @@ namespace mtconnect::sink::rest_sink { } } - for (auto &p : m_queryParameters) + for (auto& p : m_queryParameters) { auto it = request->m_parameters.find(p.m_name); if (it != request->m_parameters.end()) @@ -301,7 +301,7 @@ namespace mtconnect::sink::rest_sink { /// @brief check if the routing's path pattern matches a given path (ignoring verb) /// @param[in] path the request path to test /// @return `true` if the path matches this routing's pattern - bool matchesPath(const std::string &path) const + bool matchesPath(const std::string& path) const { std::smatch m; return std::regex_match(path, m, m_pattern); @@ -312,9 +312,9 @@ namespace mtconnect::sink::rest_sink { auto isSwagger() const { return m_swagger; } /// @brief Get the path component of the routing pattern - const auto &getPath() const { return m_path; } + const auto& getPath() const { return m_path; } /// @brief Get the routing `verb` - const auto &getVerb() const { return m_verb; } + const auto& getVerb() const { return m_verb; } /// @brief Check if the route is a catch-all (every path segment is a parameter) /// @returns `true` if all path segments are parameters (e.g. `/{device}`) @@ -322,11 +322,11 @@ namespace mtconnect::sink::rest_sink { /// @brief Get the optional command associated with the routing /// @returns optional routing - const auto &getCommand() const { return m_command; } + const auto& getCommand() const { return m_command; } /// @brief Sets the command associated with this routing for use with websockets /// @param command the command - auto &command(const std::string &command) + auto& command(const std::string& command) { m_command = command; return *this; @@ -349,7 +349,7 @@ namespace mtconnect::sink::rest_sink { } bool hasLiteral = false; - for (auto &p : parts) + for (auto& p : parts) { auto start = p.begin(); auto end = p.end(); @@ -408,7 +408,7 @@ namespace mtconnect::sink::rest_sink { } } - void getTypeAndDefault(const std::string &type, Parameter &par) + void getTypeAndDefault(const std::string& type, Parameter& par) { std::string t(type); auto dp = t.find_first_of(':'); @@ -446,7 +446,7 @@ namespace mtconnect::sink::rest_sink { } } - ParameterValue convertValue(const std::string &s, ParameterType t) const + ParameterValue convertValue(const std::string& s, ParameterType t) const { switch (t) { @@ -458,8 +458,8 @@ namespace mtconnect::sink::rest_sink { case DOUBLE: { - char *ep = nullptr; - const char *sp = s.c_str(); + char* ep = nullptr; + const char* sp = s.c_str(); double r = strtod(sp, &ep); if (ep == sp) throw ParameterError("cannot convert string '" + s + "' to double"); @@ -468,8 +468,8 @@ namespace mtconnect::sink::rest_sink { case INTEGER: { - char *ep = nullptr; - const char *sp = s.c_str(); + char* ep = nullptr; + const char* sp = s.c_str(); int32_t r = int32_t(strtoll(sp, &ep, 10)); if (ep == sp) throw ParameterError("cannot convert string '" + s + "' to integer"); @@ -479,8 +479,8 @@ namespace mtconnect::sink::rest_sink { case UNSIGNED_INTEGER: { - char *ep = nullptr; - const char *sp = s.c_str(); + char* ep = nullptr; + const char* sp = s.c_str(); uint64_t r = strtoull(sp, &ep, 10); if (ep == sp) throw ParameterError("cannot convert string '" + s + "' to unsigned integer"); @@ -499,7 +499,7 @@ namespace mtconnect::sink::rest_sink { return ParameterValue(); } - bool validateValueType(ParameterType t, ParameterValue &value) + bool validateValueType(ParameterType t, ParameterValue& value) { switch (t) { diff --git a/src/mtconnect/sink/rest_sink/server.cpp b/src/mtconnect/sink/rest_sink/server.cpp index 10d4a4c4..c4fd314b 100644 --- a/src/mtconnect/sink/rest_sink/server.cpp +++ b/src/mtconnect/sink/rest_sink/server.cpp @@ -99,7 +99,7 @@ namespace mtconnect::sink::rest_sink { m_run = true; listen(); } - catch (exception &e) + catch (exception& e) { LOG(fatal) << "Cannot start server: " << e.what(); throw FatalException(e.what()); @@ -156,7 +156,7 @@ namespace mtconnect::sink::rest_sink { beast::bind_front_handler(&Server::accept, this)); } - bool Server::allowPutFrom(const std::string &host) + bool Server::allowPutFrom(const std::string& host) { NAMED_SCOPE("Server::allowPutFrom"); @@ -172,7 +172,7 @@ namespace mtconnect::sink::rest_sink { } // Add the results to the set of allowed hosts - for (auto &addr : results) + for (auto& addr : results) { m_allowPutsFrom.insert(addr.endpoint().address()); } @@ -232,7 +232,7 @@ namespace mtconnect::sink::rest_sink { //------------------------------------------------------------------------------ // Report a failure - void Server::fail(beast::error_code ec, char const *what) + void Server::fail(beast::error_code ec, char const* what) { LOG(error) << " error: " << ec.message(); } @@ -240,7 +240,7 @@ namespace mtconnect::sink::rest_sink { using namespace mtconnect::printer; template - void AddParameter(T &writer, const Parameter ¶m) + void AddParameter(T& writer, const Parameter& param) { AutoJsonObject obj(writer); @@ -278,7 +278,7 @@ namespace mtconnect::sink::rest_sink { { obj.Key("default"); visit( - overloaded {[](const std::monostate &) {}, [&obj](const std::string &s) { obj.Add(s); }, + overloaded {[](const std::monostate&) {}, [&obj](const std::string& s) { obj.Add(s); }, [&obj](int32_t i) { obj.Add(i); }, [&obj](uint64_t i) { obj.Add(i); }, [&obj](double d) { obj.Add(d); }, [&obj](bool b) { obj.Add(b); }}, param.m_default); @@ -289,7 +289,7 @@ namespace mtconnect::sink::rest_sink { } template - void AddRouting(T &writer, const Routing &routing) + void AddRouting(T& writer, const Routing& routing) { string verb {to_string(routing.getVerb())}; boost::to_lower(verb); @@ -305,11 +305,11 @@ namespace mtconnect::sink::rest_sink { if (!routing.getPathParameters().empty() || !routing.getQueryParameters().empty()) { AutoJsonArray ary(writer, "parameters"); - for (const auto ¶m : routing.getPathParameters()) + for (const auto& param : routing.getPathParameters()) { AddParameter(writer, param); } - for (const auto ¶m : routing.getQueryParameters()) + for (const auto& param : routing.getQueryParameters()) { AddParameter(writer, param); } @@ -337,7 +337,7 @@ namespace mtconnect::sink::rest_sink { // Swagger stuff template - const void Server::renderSwaggerResponse(T &writer) + const void Server::renderSwaggerResponse(T& writer) { { AutoJsonObject obj(writer); @@ -377,15 +377,15 @@ namespace mtconnect::sink::rest_sink { { AutoJsonObject obj(writer, "paths"); - multimap routings; - for (const auto &routing : m_routings) + multimap routings; + for (const auto& routing : m_routings) { if (!routing.isSwagger() && routing.getPath()) routings.emplace(make_pair(*routing.getPath(), &routing)); } AutoJsonObject robj(writer, false); - for (const auto &[path, routing] : routings) + for (const auto& [path, routing] : routings) { robj.reset(path); AddRouting(writer, *routing); @@ -405,7 +405,7 @@ namespace mtconnect::sink::rest_sink { auto pretty = *request->parameter("pretty"); StringBuffer output; - RenderJson(output, pretty, [this](auto &writer) { renderSwaggerResponse(writer); }); + RenderJson(output, pretty, [this](auto& writer) { renderSwaggerResponse(writer); }); session->writeResponse( make_unique(status::ok, string(output.GetString()), "application/json")); @@ -442,7 +442,7 @@ namespace mtconnect::sink::rest_sink { using namespace adaptors; set specificVerbs; set catchAllVerbs; - for (const auto &r : m_routings) + for (const auto& r : m_routings) { if (!r.isSwagger() && r.matchesPath(request->m_path)) { @@ -454,7 +454,7 @@ namespace mtconnect::sink::rest_sink { } // If any specific route matched, use only those; otherwise fall back to catch-alls - auto &verbs = specificVerbs.empty() ? catchAllVerbs : specificVerbs; + auto& verbs = specificVerbs.empty() ? catchAllVerbs : specificVerbs; // OPTIONS is always allowed verbs.insert(http::verb::options); diff --git a/src/mtconnect/sink/rest_sink/server.hpp b/src/mtconnect/sink/rest_sink/server.hpp index 13479078..cd14250f 100644 --- a/src/mtconnect/sink/rest_sink/server.hpp +++ b/src/mtconnect/sink/rest_sink/server.hpp @@ -54,7 +54,7 @@ namespace mtconnect::sink::rest_sink { /// - AllowPut, defaults to false /// - ServerIp, defaults to :: /// - HttpHeaders - Server(boost::asio::io_context &context, const ConfigOptions &options = {}) + Server(boost::asio::io_context& context, const ConfigOptions& options = {}) : m_context(context), m_port(GetOption(options, configuration::Port).value_or(5000)), m_options(options), @@ -75,7 +75,7 @@ namespace mtconnect::sink::rest_sink { if (fields) setHttpHeaders(*fields); - m_errorFunction = [](SessionPtr session, const RestError &error) { + m_errorFunction = [](SessionPtr session, const RestError& error) { ResponsePtr response = std::make_unique(error.getStatus(), error.what(), "text/plain"); session->writeFailureResponse(std::move(response)); @@ -105,9 +105,9 @@ namespace mtconnect::sink::rest_sink { /// @brief Add additional HTTP headers /// @param[in] fields the header fields as `: ` - void setHttpHeaders(const StringList &fields) + void setHttpHeaders(const StringList& fields) { - for (auto &f : fields) + for (auto& f : fields) { auto i = f.find(':'); if (i != std::string::npos) @@ -119,7 +119,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Get the list of header fields /// @return header fields - const auto &getHttpHeaders() const { return m_fields; } + const auto& getHttpHeaders() const { return m_fields; } /// @brief get the bind port /// @return the port being bound auto getPort() const { return m_port; } @@ -130,7 +130,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Set the external base URL /// @param[in] url the base URL to set - void setBaseUrl(const std::string &url) { m_baseUrl = url; } + void setBaseUrl(const std::string& url) { m_baseUrl = url; } /// @name PUT and POST handling ///@{ @@ -147,14 +147,14 @@ namespace mtconnect::sink::rest_sink { /// @brief can one put from a particular IP address or host /// @param[in] host the host /// @return `true` if puts are allowed - bool allowPutFrom(const std::string &host); + bool allowPutFrom(const std::string& host); /// @brief sets the allow puts flag /// @param[in] allow void allowPuts(bool allow = true) { m_allowPuts = allow; } /// @brief can one put from an ip address /// @param[in] addr the ip address /// @return `true` if puts are accepted from that address - bool isPutAllowedFrom(boost::asio::ip::address &addr) const + bool isPutAllowedFrom(boost::asio::ip::address& addr) const { return m_allowPutsFrom.find(addr) != m_allowPutsFrom.end(); } @@ -187,7 +187,7 @@ namespace mtconnect::sink::rest_sink { } else { - for (auto &r : m_routings) + for (auto& r : m_routings) { success = r.matches(session, request) && r.run(session, request); if (success) @@ -213,7 +213,7 @@ namespace mtconnect::sink::rest_sink { m_errorFunction(session, re); } } - catch (RestError &re) + catch (RestError& re) { auto uri = request->getUri(); re.setUri(uri); @@ -225,7 +225,7 @@ namespace mtconnect::sink::rest_sink { re.setRequestId(*request->m_requestId); m_errorFunction(session, re); } - catch (std::logic_error &le) + catch (std::logic_error& le) { std::stringstream txt; txt << session->getRemote().address() << ": Logic Error: " << le.what(); @@ -250,13 +250,13 @@ namespace mtconnect::sink::rest_sink { /// @brief Method that generates an MTConnect Error document /// @param[in] ec an error code /// @param[in] what the description why the request failed - void fail(boost::system::error_code ec, char const *what); + void fail(boost::system::error_code ec, char const* what); /// @brief Add a routing to the server /// @param[in] routing the routing - Routing &addRouting(const Routing &routing) + Routing& addRouting(const Routing& routing) { - auto &route = m_routings.emplace_back(routing); + auto& route = m_routings.emplace_back(routing); if (m_parameterDocumentation) route.documentParameters(*m_parameterDocumentation); if (route.getCommand()) @@ -267,7 +267,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Setup commands from routings void addCommands() { - for (auto &route : m_routings) + for (auto& route : m_routings) { if (route.getCommand()) m_commands.emplace(*route.getCommand(), &route); @@ -276,14 +276,14 @@ namespace mtconnect::sink::rest_sink { /// @brief Add common set of documentation for all rest routings /// @param[in] docs Parameter documentation - void addParameterDocumentation(const ParameterDocList &docs) + void addParameterDocumentation(const ParameterDocList& docs) { m_parameterDocumentation.emplace(docs); } /// @brief Set the error function to format the error during failure /// @param func the error function - void setErrorFunction(const ErrorFunction &func) { m_errorFunction = func; } + void setErrorFunction(const ErrorFunction& func) { m_errorFunction = func; } /// @brief get the error funciton /// @return the error function ErrorFunction getErrorFunction() const { return m_errorFunction; } @@ -308,7 +308,7 @@ namespace mtconnect::sink::rest_sink { /// Caches the API document based on the response type requested. Cache cleared whenever a new /// routing is added. template - const void renderSwaggerResponse(T &format); + const void renderSwaggerResponse(T& format); /// @} /// @name CORS Support @@ -322,7 +322,7 @@ namespace mtconnect::sink::rest_sink { /// @} protected: - boost::asio::io_context &m_context; + boost::asio::io_context& m_context; boost::asio::ip::address m_address; unsigned short m_port {5000}; @@ -337,7 +337,7 @@ namespace mtconnect::sink::rest_sink { std::set m_allowPutsFrom; std::list m_routings; - std::map m_commands; + std::map m_commands; std::unique_ptr m_fileCache; ErrorFunction m_errorFunction; FieldList m_fields; diff --git a/src/mtconnect/sink/rest_sink/session.hpp b/src/mtconnect/sink/rest_sink/session.hpp index 4d34d5a8..c0716451 100644 --- a/src/mtconnect/sink/rest_sink/session.hpp +++ b/src/mtconnect/sink/rest_sink/session.hpp @@ -34,7 +34,7 @@ namespace mtconnect::sink::rest_sink { using ResponsePtr = std::unique_ptr; class Session; using SessionPtr = std::shared_ptr; - using ErrorFunction = std::function; + using ErrorFunction = std::function; using Dispatch = std::function; using Complete = std::function; @@ -57,20 +57,20 @@ namespace mtconnect::sink::rest_sink { /// @brief write the response to the client /// @param response the response /// @param complete optional completion callback - virtual void writeResponse(ResponsePtr &&response, Complete complete = nullptr) = 0; + virtual void writeResponse(ResponsePtr&& response, Complete complete = nullptr) = 0; /// @brief write a failure response to the client /// @param response the response /// @param complete optional completion callback - virtual void writeFailureResponse(ResponsePtr &&response, Complete complete = nullptr) = 0; + virtual void writeFailureResponse(ResponsePtr&& response, Complete complete = nullptr) = 0; /// @brief begin streaming data to the client using x-multipart-replace /// @param mimeType the mime type of the response /// @param complete completion callback - virtual void beginStreaming(const std::string &mimeType, Complete complete, + virtual void beginStreaming(const std::string& mimeType, Complete complete, std::optional requestId = std::nullopt) = 0; /// @brief write a chunk for a streaming session /// @param chunk the chunk to write /// @param complete a completion callback - virtual void writeChunk(const std::string &chunk, Complete complete, + virtual void writeChunk(const std::string& chunk, Complete complete, std::optional requestId = std::nullopt) = 0; /// @brief close the session virtual void close() = 0; @@ -80,7 +80,7 @@ namespace mtconnect::sink::rest_sink { /// @param status the HTTP status /// @param message the message /// @param ec an optional error code - virtual void fail(boost::beast::http::status status, const std::string &message, + virtual void fail(boost::beast::http::status status, const std::string& message, boost::system::error_code ec = boost::system::error_code {}) { NAMED_SCOPE("Session::fail"); @@ -105,17 +105,17 @@ namespace mtconnect::sink::rest_sink { /// @brief allow puts from a set of hosts /// @note also sets allow puts to `true` /// @param hosts set of hosts - void allowPutsFrom(std::set &hosts) + void allowPutsFrom(std::set& hosts) { m_allowPuts = true; m_allowPutsFrom = hosts; } /// @brief get the remote endpoint /// @return the asio tcp endpoint - auto &getRemote() const { return m_remote; } + auto& getRemote() const { return m_remote; } /// @brief set the request as unauthorized /// @param msg the rational message - void setUnauthorized(const std::string &msg) + void setUnauthorized(const std::string& msg) { m_message = msg; m_unauthorized = true; @@ -127,9 +127,9 @@ namespace mtconnect::sink::rest_sink { m_observers.push_back(observer); } - bool cancelRequest(const std::string &requestId) + bool cancelRequest(const std::string& requestId) { - for (auto &obs : m_observers) + for (auto& obs : m_observers) { auto pobs = obs.lock(); if (pobs && pobs->getRequestId() == requestId) diff --git a/src/mtconnect/sink/rest_sink/session_impl.cpp b/src/mtconnect/sink/rest_sink/session_impl.cpp index 465ae3c1..3d363276 100644 --- a/src/mtconnect/sink/rest_sink/session_impl.cpp +++ b/src/mtconnect/sink/rest_sink/session_impl.cpp @@ -53,7 +53,7 @@ namespace mtconnect::sink::rest_sink { inline unsigned char hex(unsigned char x) { return x + (x > 9 ? ('A' - 10) : '0'); } - const string urlencode(const string &s) + const string urlencode(const string& s) { ostringstream os; for (const auto ci : s) @@ -114,7 +114,7 @@ namespace mtconnect::sink::rest_sink { return result.str(); } - void parseQueries(string qp, map &queries) + void parseQueries(string qp, map& queries) { vector> toks; algo::split(toks, qp, boost::is_any_of("&")); @@ -132,7 +132,7 @@ namespace mtconnect::sink::rest_sink { } } - string parseUrl(string url, map &queries) + string parseUrl(string url, map& queries) { auto pos = url.find('?'); if (pos != string::npos) @@ -196,8 +196,8 @@ namespace mtconnect::sink::rest_sink { return; } - auto &msg = m_parser->get(); - const auto &remote = m_remote; + auto& msg = m_parser->get(); + const auto& remote = m_remote; // Check for put, post, or delete (allow OPTIONS for CORS preflight) if (msg.method() == http::verb::put || msg.method() == http::verb::post || @@ -294,7 +294,7 @@ namespace mtconnect::sink::rest_sink { } template - void SessionImpl::beginStreaming(const std::string &mimeType, Complete complete, + void SessionImpl::beginStreaming(const std::string& mimeType, Complete complete, std::optional requestId) { NAMED_SCOPE("SessionImpl::beginStreaming"); @@ -321,7 +321,7 @@ namespace mtconnect::sink::rest_sink { res->set(field::content_type, "multipart/mixed;boundary=" + m_boundary); res->set(field::expires, "-1"); res->set(field::cache_control, "no-cache, no-store, max-age=0"); - for (const auto &f : m_fields) + for (const auto& f : m_fields) { res->set(f.first, f.second); } @@ -333,7 +333,7 @@ namespace mtconnect::sink::rest_sink { } template - void SessionImpl::writeChunk(const std::string &body, Complete complete, + void SessionImpl::writeChunk(const std::string& body, Complete complete, std::optional requestId) { NAMED_SCOPE("SessionImpl::writeChunk"); @@ -368,7 +368,7 @@ namespace mtconnect::sink::rest_sink { template template - void SessionImpl::addHeaders(const Response &response, Message &res) + void SessionImpl::addHeaders(const Response& response, Message& res) { res->set(http::field::server, "MTConnectAgent"); auto now = std::chrono::floor(std::chrono::system_clock::now()); @@ -383,7 +383,7 @@ namespace mtconnect::sink::rest_sink { res->set(http::field::cache_control, "no-store, max-age=0"); } res->set(http::field::content_type, response.m_mimeType); - for (const auto &f : m_fields) + for (const auto& f : m_fields) { res->set(f.first, f.second); } @@ -391,14 +391,14 @@ namespace mtconnect::sink::rest_sink { { res->set(http::field::location, *response.m_location); } - for (const auto &f : response.m_fields) + for (const auto& f : response.m_fields) { res->set(f.first, f.second); } } template - void SessionImpl::writeResponse(ResponsePtr &&responsePtr, Complete complete) + void SessionImpl::writeResponse(ResponsePtr&& responsePtr, Complete complete) { NAMED_SCOPE("SessionImpl::writeResponse"); @@ -449,7 +449,7 @@ namespace mtconnect::sink::rest_sink { } else { - const char *bp; + const char* bp; size_t size; if (m_outgoing->m_file) { @@ -478,7 +478,7 @@ namespace mtconnect::sink::rest_sink { } template - void SessionImpl::writeFailureResponse(ResponsePtr &&response, Complete complete) + void SessionImpl::writeFailureResponse(ResponsePtr&& response, Complete complete) { if (m_streaming) { @@ -491,7 +491,7 @@ namespace mtconnect::sink::rest_sink { } } - SessionPtr HttpSession::upgradeToWebsocket(RequestMessage &&msg) + SessionPtr HttpSession::upgradeToWebsocket(RequestMessage&& msg) { return std::make_shared(std::move(m_stream), std::move(m_request), std::move(msg), m_dispatch, m_errorFunction); @@ -508,8 +508,8 @@ namespace mtconnect::sink::rest_sink { /// @param list the header fieldlist /// @param dispatch dispatch function /// @param error error function - HttpsSession(boost::beast::tcp_stream &&socket, boost::asio::ssl::context &context, - boost::beast::flat_buffer &&buffer, const FieldList &list, Dispatch dispatch, + HttpsSession(boost::beast::tcp_stream&& socket, boost::asio::ssl::context& context, + boost::beast::flat_buffer&& buffer, const FieldList& list, Dispatch dispatch, ErrorFunction error) : SessionImpl(std::move(buffer), list, dispatch, error), m_stream(std::move(socket), context) @@ -530,7 +530,7 @@ namespace mtconnect::sink::rest_sink { } /// @brief close this session virtual ~HttpsSession() { close(); } - auto &stream() { return m_stream; } + auto& stream() { return m_stream; } void run() override { @@ -572,7 +572,7 @@ namespace mtconnect::sink::rest_sink { } /// @brief Upgrade the current connection to a websocket connection. - SessionPtr upgradeToWebsocket(RequestMessage &&msg) + SessionPtr upgradeToWebsocket(RequestMessage&& msg) { return std::make_shared(std::move(m_stream), std::move(m_request), std::move(msg), m_dispatch, m_errorFunction); @@ -602,7 +602,7 @@ namespace mtconnect::sink::rest_sink { }; template - void SessionImpl::upgrade(RequestMessage &&msg) + void SessionImpl::upgrade(RequestMessage&& msg) { LOG(debug) << "Upgrading session to websockets"; derived().upgradeToWebsocket(std::move(msg))->run(); diff --git a/src/mtconnect/sink/rest_sink/session_impl.hpp b/src/mtconnect/sink/rest_sink/session_impl.hpp index 7bfd6089..5e018b8e 100644 --- a/src/mtconnect/sink/rest_sink/session_impl.hpp +++ b/src/mtconnect/sink/rest_sink/session_impl.hpp @@ -51,12 +51,12 @@ namespace mtconnect { /// @param list http fields /// @param dispatch dispatch method /// @param error error function - SessionImpl(boost::beast::flat_buffer &&buffer, const FieldList &list, Dispatch dispatch, + SessionImpl(boost::beast::flat_buffer&& buffer, const FieldList& list, Dispatch dispatch, ErrorFunction error) : Session(dispatch, error), m_fields(list), m_buffer(std::move(buffer)) {} /// @brief Sessions cannot be copied - SessionImpl(const SessionImpl &) = delete; + SessionImpl(const SessionImpl&) = delete; virtual ~SessionImpl() {} /// @brief get a shared pointer to this @@ -67,16 +67,16 @@ namespace mtconnect { } /// @brief get this as the `Derived` type /// @return the subclass - Derived &derived() { return static_cast(*this); } + Derived& derived() { return static_cast(*this); } /// @name Session Interface ///@{ void run() override; - void writeResponse(ResponsePtr &&response, Complete complete = nullptr) override; - void writeFailureResponse(ResponsePtr &&response, Complete complete = nullptr) override; - void beginStreaming(const std::string &mimeType, Complete complete, + void writeResponse(ResponsePtr&& response, Complete complete = nullptr) override; + void writeFailureResponse(ResponsePtr&& response, Complete complete = nullptr) override; + void beginStreaming(const std::string& mimeType, Complete complete, std::optional requestId = std::nullopt) override; - void writeChunk(const std::string &chunk, Complete complete, + void writeChunk(const std::string& chunk, Complete complete, std::optional requestId = std::nullopt) override; void closeStream() override; ///@} @@ -84,13 +84,13 @@ namespace mtconnect { using RequestMessage = boost::beast::http::request; template - void addHeaders(const Response &response, T &res); + void addHeaders(const Response& response, T& res); void requested(boost::system::error_code ec, size_t len); void sent(boost::system::error_code ec, size_t len); void read(); void reset(); - void upgrade(RequestMessage &&msg); + void upgrade(RequestMessage&& msg); protected: using RequestParser = boost::beast::http::request_parser; @@ -126,8 +126,8 @@ namespace mtconnect { /// @param list list of fields /// @param dispatch dispatch function /// @param error error format function - HttpSession(boost::beast::tcp_stream &&stream, boost::beast::flat_buffer &&buffer, - const FieldList &list, Dispatch dispatch, ErrorFunction error) + HttpSession(boost::beast::tcp_stream&& stream, boost::beast::flat_buffer&& buffer, + const FieldList& list, Dispatch dispatch, ErrorFunction error) : SessionImpl(std::move(buffer), list, dispatch, error), m_stream(std::move(stream)) { @@ -149,7 +149,7 @@ namespace mtconnect { virtual ~HttpSession() { close(); } /// @brief get the stream /// @return the stream - auto &stream() { return m_stream; } + auto& stream() { return m_stream; } /// @brief close the session and shutdown the socket void close() override @@ -165,7 +165,7 @@ namespace mtconnect { // the observer's completion handler in m_complete, forming a reference cycle. // Cancelling the observers resets that back-reference so the session (and its // socket fd) can be destroyed. Without this the fd leaks on client disconnect. - for (auto &obs : m_observers) + for (auto& obs : m_observers) { auto optr = obs.lock(); if (optr) @@ -180,7 +180,7 @@ namespace mtconnect { } /// @brief Upgrade the current connection to a websocket connection. - SessionPtr upgradeToWebsocket(RequestMessage &&msg); + SessionPtr upgradeToWebsocket(RequestMessage&& msg); protected: boost::beast::tcp_stream m_stream; diff --git a/src/mtconnect/sink/rest_sink/tls_dector.hpp b/src/mtconnect/sink/rest_sink/tls_dector.hpp index e5f24a4e..7652136d 100644 --- a/src/mtconnect/sink/rest_sink/tls_dector.hpp +++ b/src/mtconnect/sink/rest_sink/tls_dector.hpp @@ -40,9 +40,9 @@ namespace mtconnect::sink::rest_sink { /// @param[in] list the header fields /// @param[in] dispatch a dispatcher function /// @param[in] error an error function - TlsDector(boost::asio::ip::tcp::socket &&socket, boost::asio::ssl::context &context, - bool tlsOnly, bool allowPuts, const std::set &allowPutsFrom, - const FieldList &list, Dispatch dispatch, ErrorFunction error) + TlsDector(boost::asio::ip::tcp::socket&& socket, boost::asio::ssl::context& context, + bool tlsOnly, bool allowPuts, const std::set& allowPutsFrom, + const FieldList& list, Dispatch dispatch, ErrorFunction error) : m_stream(std::move(socket)), m_tlsContext(context), m_tlsOnly(tlsOnly), @@ -58,7 +58,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Method to call when TLS operation fails /// @param[in] ec the erro code /// @param[in] message the message - void fail(boost::system::error_code ec, const std::string &message) + void fail(boost::system::error_code ec, const std::string& message) { NAMED_SCOPE("TlsDector::fail"); @@ -81,7 +81,7 @@ namespace mtconnect::sink::rest_sink { protected: boost::beast::tcp_stream m_stream; - boost::asio::ssl::context &m_tlsContext; + boost::asio::ssl::context& m_tlsContext; boost::beast::flat_buffer m_buffer; bool m_tlsOnly; diff --git a/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp b/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp index d06fda32..003e49d7 100644 --- a/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp +++ b/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp @@ -36,7 +36,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Wrapper around a request with additional infomation required for a WebSocket request struct WebsocketRequest { - WebsocketRequest(const std::string &id) : m_requestId(id) {} + WebsocketRequest(const std::string& id) : m_requestId(id) {} std::string m_requestId; //! The id of the request std::optional m_streamBuffer; //! The streambuffer used in responses Complete m_complete; //! A complete function when the request has finished @@ -47,7 +47,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Create a request dispatcher /// @param httpRequest a copy of the incoming HTTP request /// @param dispatch the dispatch function to call - WebsocketRequestManager(RequestPtr &&httpRequest, Dispatch dispatch) + WebsocketRequestManager(RequestPtr&& httpRequest, Dispatch dispatch) : m_httpRequest(std::move(httpRequest)), m_dispatch(dispatch) {} @@ -63,7 +63,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Set the current request (used for testing). /// @param request the request that is owned by the manager - void setHttpRequest(RequestPtr &&request) { m_httpRequest = std::move(request); } + void setHttpRequest(RequestPtr&& request) { m_httpRequest = std::move(request); } /// @brief Get the current HTTP request /// @returns a pointer to the HTTP request @@ -72,7 +72,7 @@ namespace mtconnect::sink::rest_sink { /// @brief Finds the request for a given id /// @param id the id to search for /// @returns a pointer to the request structure or null if it is not found - WebsocketRequest *findRequest(const std::string &id) + WebsocketRequest* findRequest(const std::string& id) { auto it = m_requests.find(id); if (it != m_requests.end()) @@ -88,7 +88,7 @@ namespace mtconnect::sink::rest_sink { /// @brief finds or creates a WebSocketRequest structure and return it. /// @param id the id of the request to create /// @returns a pointer to the new websocket request or the existing one. - WebsocketRequest *findOrCreateRequest(const std::string &id) + WebsocketRequest* findOrCreateRequest(const std::string& id) { auto res = m_requests.emplace(id, id); return &res.first->second; @@ -97,7 +97,7 @@ namespace mtconnect::sink::rest_sink { /// @brief finds or creates a WebSocketRequest structure and return it. /// @param id the id of the request to create /// @returns a pointer to the new websocket request or the existing one. - WebsocketRequest *createRequest(const std::string &id) + WebsocketRequest* createRequest(const std::string& id) { auto it = m_requests.find(id); if (it == m_requests.end()) @@ -113,11 +113,11 @@ namespace mtconnect::sink::rest_sink { /// @brief Remove a request from the known requests /// @param id the id of the request to remove - void remove(const std::string &id) { m_requests.erase(id); } + void remove(const std::string& id) { m_requests.erase(id); } /// @brief Parse a JSON request buffer and create a new request ptr. /// @param buffer the text to parse - RequestPtr parse(const std::string &buffer) + RequestPtr parse(const std::string& buffer) { using namespace rapidjson; using namespace std; @@ -160,12 +160,12 @@ namespace mtconnect::sink::rest_sink { #define __GOSave__ GetObject #undef GetObject #endif - const auto &object = doc.GetObject(); + const auto& object = doc.GetObject(); #ifdef __GOSave__ #define GetObject __GOSave__ #endif - for (auto &it : object) + for (auto& it : object) { switch (it.value.GetType()) { @@ -184,9 +184,9 @@ namespace mtconnect::sink::rest_sink { break; case rapidjson::kArrayType: { - const auto &array = it.value.GetArray(); + const auto& array = it.value.GetArray(); std::stringstream buf; - for (const auto &s : array) + for (const auto& s : array) buf << s.GetString() << ";"; string str = buf.str(); str.erase(str.length() - 1); // Remove last ; @@ -226,7 +226,7 @@ namespace mtconnect::sink::rest_sink { /// @param buffer the JSON request string /// @param outId optional pointer to a string to receive the request id /// @returns `true` if the dispatch was successful. - bool dispatch(SessionPtr session, const std::string &buffer, std::string *outId = nullptr) + bool dispatch(SessionPtr session, const std::string& buffer, std::string* outId = nullptr) { using namespace std; @@ -238,7 +238,7 @@ namespace mtconnect::sink::rest_sink { if (request->m_parameters.count("id") > 0) { - auto &v = request->m_parameters["id"]; + auto& v = request->m_parameters["id"]; string id = visit(overloaded {[](monostate m) { return ""s; }, [](auto v) { return boost::lexical_cast(v); }}, v); @@ -252,7 +252,7 @@ namespace mtconnect::sink::rest_sink { "ERROR"); } - auto &id = *(request->m_requestId); + auto& id = *(request->m_requestId); if (request->m_parameters.count("request") > 0) { @@ -296,7 +296,7 @@ namespace mtconnect::sink::rest_sink { return m_dispatch(session, request); } - catch (RestError &re) + catch (RestError& re) { re.setRequestId(id); throw re; diff --git a/src/mtconnect/sink/rest_sink/websocket_session.hpp b/src/mtconnect/sink/rest_sink/websocket_session.hpp index 5a411895..666d40fa 100644 --- a/src/mtconnect/sink/rest_sink/websocket_session.hpp +++ b/src/mtconnect/sink/rest_sink/websocket_session.hpp @@ -45,7 +45,7 @@ namespace mtconnect::sink::rest_sink { protected: struct Message { - Message(const std::string &body, Complete &complete, const std::string &requestId) + Message(const std::string& body, Complete& complete, const std::string& requestId) : m_body(body), m_complete(complete), m_requestId(requestId) {} @@ -55,17 +55,17 @@ namespace mtconnect::sink::rest_sink { }; public: - WebsocketSession(RequestPtr &&request, Dispatch dispatch, ErrorFunction func) + WebsocketSession(RequestPtr&& request, Dispatch dispatch, ErrorFunction func) : Session(dispatch, func), m_requestManager(std::move(request), dispatch) {} /// @brief Session cannot be copied. - WebsocketSession(const WebsocketSession &) = delete; + WebsocketSession(const WebsocketSession&) = delete; ~WebsocketSession() = default; - Derived &derived() { return static_cast(*this); } + Derived& derived() { return static_cast(*this); } - auto &getRequestManager() { return m_requestManager; } + auto& getRequestManager() { return m_requestManager; } void close() override { @@ -94,7 +94,7 @@ namespace mtconnect::sink::rest_sink { closeStream(); } - void writeResponse(ResponsePtr &&response, Complete complete = nullptr) override + void writeResponse(ResponsePtr&& response, Complete complete = nullptr) override { NAMED_SCOPE("WebsocketSession::writeResponse"); if (!response->m_requestId) @@ -106,13 +106,13 @@ namespace mtconnect::sink::rest_sink { writeChunk(response->m_body, complete, response->m_requestId); } - void writeFailureResponse(ResponsePtr &&response, Complete complete = nullptr) override + void writeFailureResponse(ResponsePtr&& response, Complete complete = nullptr) override { NAMED_SCOPE("WebsocketSession::writeFailureResponse"); writeChunk(response->m_body, complete, response->m_requestId); } - void beginStreaming(const std::string &mimeType, Complete complete, + void beginStreaming(const std::string& mimeType, Complete complete, std::optional requestId = std::nullopt) override { if (requestId) @@ -139,7 +139,7 @@ namespace mtconnect::sink::rest_sink { } } - void writeChunk(const std::string &chunk, Complete complete, + void writeChunk(const std::string& chunk, Complete complete, std::optional requestId = std::nullopt) override { NAMED_SCOPE("WebsocketSession::writeChunk"); @@ -172,7 +172,7 @@ namespace mtconnect::sink::rest_sink { } protected: - void send(const std::string body, Complete complete, const std::string &requestId) + void send(const std::string body, Complete complete, const std::string& requestId) { NAMED_SCOPE("WebsocketSession::send"); @@ -198,7 +198,7 @@ namespace mtconnect::sink::rest_sink { } } - void sent(beast::error_code ec, std::size_t len, const std::string &id) + void sent(beast::error_code ec, std::size_t len, const std::string& id) { NAMED_SCOPE("WebsocketSession::sent"); @@ -245,7 +245,7 @@ namespace mtconnect::sink::rest_sink { // Check for queued messages if (m_messageQueue.size() > 0) { - auto &msg = m_messageQueue.front(); + auto& msg = m_messageQueue.front(); send(msg.m_body, msg.m_complete, msg.m_requestId); m_messageQueue.pop_front(); } @@ -270,18 +270,18 @@ namespace mtconnect::sink::rest_sink { using RequestMessage = boost::beast::http::request; using super = WebsocketSession; - WebsocketSessionImpl(RequestPtr &&request, RequestMessage &&msg, Dispatch dispatch, + WebsocketSessionImpl(RequestPtr&& request, RequestMessage&& msg, Dispatch dispatch, ErrorFunction func) : super(std::move(request), dispatch, func), m_msg(std::move(msg)) {} /// @brief Session cannot be copied. - WebsocketSessionImpl(const WebsocketSessionImpl &) = delete; + WebsocketSessionImpl(const WebsocketSessionImpl&) = delete; ~WebsocketSessionImpl() = default; /// @brief get this as the `Derived` type /// @return the subclass - Derived &derived() { return static_cast(*this); } + Derived& derived() { return static_cast(*this); } bool isStreamOpen() { return derived().stream().is_open(); } @@ -297,7 +297,7 @@ namespace mtconnect::sink::rest_sink { // Set a decorator to change the Server of the handshake derived().stream().set_option( - websocket::stream_base::decorator([](websocket::response_type &res) { + websocket::stream_base::decorator([](websocket::response_type& res) { res.set(http::field::server, GetAgentVersion() + " MTConnectAgent"); })); @@ -327,7 +327,7 @@ namespace mtconnect::sink::rest_sink { beast::bind_front_handler(&WebsocketSessionImpl::onRead, derived().shared_ptr())); } - void asyncSend(WebsocketRequestManager::WebsocketRequest *request) + void asyncSend(WebsocketRequestManager::WebsocketRequest* request) { NAMED_SCOPE("WebsocketSessionImpl::asyncSend"); @@ -335,7 +335,7 @@ namespace mtconnect::sink::rest_sink { auto ref = derived().shared_ptr(); - auto &requestId = request->m_requestId; + auto& requestId = request->m_requestId; derived().stream().text(derived().stream().got_text()); derived().stream().async_write( request->m_streamBuffer->data(), @@ -375,7 +375,7 @@ namespace mtconnect::sink::rest_sink { } } - catch (RestError &re) + catch (RestError& re) { auto id = re.getRequestId(); if (!id) @@ -388,7 +388,7 @@ namespace mtconnect::sink::rest_sink { super::m_errorFunction(derived().shared_ptr(), re); } - catch (std::logic_error &le) + catch (std::logic_error& le) { std::stringstream txt; txt << super::getRemote().address() << ": Logic Error: " << le.what(); @@ -420,7 +420,7 @@ namespace mtconnect::sink::rest_sink { public: using Stream = beast::websocket::stream; - PlainWebsocketSession(beast::tcp_stream &&stream, RequestPtr &&request, RequestMessage &&msg, + PlainWebsocketSession(beast::tcp_stream&& stream, RequestPtr&& request, RequestMessage&& msg, Dispatch dispatch, ErrorFunction func) : WebsocketSessionImpl(std::move(request), std::move(msg), dispatch, func), m_stream(std::move(stream)) @@ -439,7 +439,7 @@ namespace mtconnect::sink::rest_sink { m_stream.close(beast::websocket::close_code::none); } - auto &stream() { return m_stream; } + auto& stream() { return m_stream; } /// @brief Get a pointer cast as an Websocket Session /// @return shared pointer to an Websocket session @@ -458,8 +458,8 @@ namespace mtconnect::sink::rest_sink { public: using Stream = beast::websocket::stream>; - TlsWebsocketSession(beast::ssl_stream &&stream, RequestPtr &&request, - RequestMessage &&msg, Dispatch dispatch, ErrorFunction func) + TlsWebsocketSession(beast::ssl_stream&& stream, RequestPtr&& request, + RequestMessage&& msg, Dispatch dispatch, ErrorFunction func) : WebsocketSessionImpl(std::move(request), std::move(msg), dispatch, func), m_stream(std::move(stream)) { @@ -471,7 +471,7 @@ namespace mtconnect::sink::rest_sink { close(); } - auto &stream() { return m_stream; } + auto& stream() { return m_stream; } void closeStream() override { diff --git a/src/mtconnect/sink/sink.cpp b/src/mtconnect/sink/sink.cpp index 8a874966..d048ebca 100644 --- a/src/mtconnect/sink/sink.cpp +++ b/src/mtconnect/sink/sink.cpp @@ -21,10 +21,10 @@ namespace mtconnect { namespace sink { - SinkPtr SinkFactory::make(const std::string &factoryName, const std::string &sinkName, - boost::asio::io_context &io, SinkContractPtr &&contract, - const ConfigOptions &options, - const boost::property_tree::ptree &block) + SinkPtr SinkFactory::make(const std::string& factoryName, const std::string& sinkName, + boost::asio::io_context& io, SinkContractPtr&& contract, + const ConfigOptions& options, + const boost::property_tree::ptree& block) { auto factory = m_factories.find(factoryName); if (factory != m_factories.end()) diff --git a/src/mtconnect/sink/sink.hpp b/src/mtconnect/sink/sink.hpp index 4b0df107..ff2a9c26 100644 --- a/src/mtconnect/sink/sink.hpp +++ b/src/mtconnect/sink/sink.hpp @@ -70,19 +70,19 @@ namespace mtconnect { /// @brief get the printer for a mime type. Current options: `xml` or `json`. /// @param[in] aType a string for the type /// @return A pointer to a printer for that type. `nullptr` if not found - virtual printer::Printer *getPrinter(const std::string &aType) const = 0; + virtual printer::Printer* getPrinter(const std::string& aType) const = 0; /// @brief get the map of type/printer pairs /// @return a reference to the map (ownership is not transferred). - virtual const PrinterMap &getPrinters() const = 0; + virtual const PrinterMap& getPrinters() const = 0; /// @brief find a device by name /// @param[in] name the name of the device /// @return shared pointer to the device if found - virtual DevicePtr getDeviceByName(const std::string &name) const = 0; + virtual DevicePtr getDeviceByName(const std::string& name) const = 0; /// @brief find a device by its uuid or name /// @param idOrName the uuid or name /// @return shared pointer to the device if found - virtual DevicePtr findDeviceByUUIDorName(const std::string &idOrName) const = 0; + virtual DevicePtr findDeviceByUUIDorName(const std::string& idOrName) const = 0; /// @brief get a list of all the devices /// @return a list of shared device pointers virtual const std::list getDevices() const = 0; @@ -94,14 +94,14 @@ namespace mtconnect { /// @brief get a data item by its unique id /// @param[in] id a unique id /// @return shared pointer to the data item if found - virtual DataItemPtr getDataItemById(const std::string &id) const = 0; + virtual DataItemPtr getDataItemById(const std::string& id) const = 0; /// @brief find all the data items for a given XPath /// @param[in] device optional device to search /// @param[in] path the xpath to search /// @param[out] filter the set of all data items matching path to use for filtering virtual void getDataItemsForPath( - const DevicePtr device, const std::optional &path, FilterSet &filter, - const std::optional &deviceType = std::nullopt) const = 0; + const DevicePtr device, const std::optional& path, FilterSet& filter, + const std::optional& deviceType = std::nullopt) const = 0; /// @brief Add a source for this sink. /// /// This is used to create loopback sources for a sink @@ -110,21 +110,21 @@ namespace mtconnect { virtual void addSource(std::shared_ptr source) = 0; /// @brief Get the common circular buffer /// @return a reference to the circular buffer - virtual buffer::CircularBuffer &getCircularBuffer() = 0; + virtual buffer::CircularBuffer& getCircularBuffer() = 0; /// @brief Get a pointer to the asset storage /// @return a pointer to the asset storage. - virtual const asset::AssetStorage *getAssetStorage() = 0; + virtual const asset::AssetStorage* getAssetStorage() = 0; /// @brief Get a reference to the hook manager for the agent. /// @param[in] type the type manager to retrieve /// @return a reference to the hook manager - virtual configuration::HookManager &getHooks(HookType type) = 0; + virtual configuration::HookManager& getHooks(HookType type) = 0; /// @brief Shared pointer to the pipeline context std::shared_ptr m_pipelineContext; - using FindFile = std::function(const std::string &)>; + using FindFile = std::function(const std::string&)>; /// @brief function to find a configuration file FindFile m_findConfigFile; @@ -138,21 +138,21 @@ namespace mtconnect { /// @brief The factory callback or lambda to create this sink. Used for plugins. using SinkFactoryFn = boost::function; + const std::string& name, boost::asio::io_context& io, SinkContractPtr&& contract, + const ConfigOptions& options, const boost::property_tree::ptree& block)>; /// @brief Abstract Sink class AGENT_LIB_API Sink : public std::enable_shared_from_this { public: - Sink(const std::string &name, SinkContractPtr &&contract) + Sink(const std::string& name, SinkContractPtr&& contract) : m_sinkContract(std::move(contract)), m_name(name) {} virtual ~Sink() = default; /// @brief The shared_from_this pointer for this object /// @return shared pointer - SinkPtr getptr() const { return const_cast(this)->shared_from_this(); } + SinkPtr getptr() const { return const_cast(this)->shared_from_this(); } /// @brief Start the sink virtual void start() = 0; @@ -162,7 +162,7 @@ namespace mtconnect { /// @brief Receive an observation /// @param observation shared pointer to the observation /// @return `true` if the publishing was successful - virtual bool publish(observation::ObservationPtr &observation) = 0; + virtual bool publish(observation::ObservationPtr& observation) = 0; /// @brief Receive an asset /// @param asset shared point to the asset /// @return `true` if successful @@ -174,7 +174,7 @@ namespace mtconnect { /// @brief Get the name of the Sink. Sinks should have unique names. /// @return the name - const auto &getName() const { return m_name; } + const auto& getName() const { return m_name; } protected: std::unique_ptr m_sinkContract; @@ -188,7 +188,7 @@ namespace mtconnect { /// @brief Register and associate the name with the Sink factory functon /// @param name the name /// @param function the factory - void registerFactory(const std::string &name, SinkFactoryFn function) + void registerFactory(const std::string& name, SinkFactoryFn function) { m_factories.insert_or_assign(name, function); } @@ -199,7 +199,7 @@ namespace mtconnect { /// @brief Check if a sink factory exists /// @param name the name of the factory /// @return `true` if the factory exits. - bool hasFactory(const std::string &name) { return m_factories.count(name) > 0; } + bool hasFactory(const std::string& name) { return m_factories.count(name) > 0; } /// @brief Create a sink for a given name /// @param factoryName The name of the factory @@ -210,9 +210,9 @@ namespace mtconnect { /// @param block Additional configuration options for the Sink as a boost property tree. /// These options need to be interpreted by the sink /// @return A shared pointer to the sink. - SinkPtr make(const std::string &factoryName, const std::string &sinkName, - boost::asio::io_context &io, SinkContractPtr &&contract, - const ConfigOptions &options, const boost::property_tree::ptree &block); + SinkPtr make(const std::string& factoryName, const std::string& sinkName, + boost::asio::io_context& io, SinkContractPtr&& contract, + const ConfigOptions& options, const boost::property_tree::ptree& block); protected: std::map m_factories; diff --git a/src/mtconnect/source/adapter/adapter.hpp b/src/mtconnect/source/adapter/adapter.hpp index df460389..b9c26783 100644 --- a/src/mtconnect/source/adapter/adapter.hpp +++ b/src/mtconnect/source/adapter/adapter.hpp @@ -31,7 +31,7 @@ namespace mtconnect::source::adapter { /// @param name adapter name /// @param io boost asio io context /// @param options adapter options - Adapter(const std::string &name, boost::asio::io_context &io, const ConfigOptions &options) + Adapter(const std::string& name, boost::asio::io_context& io, const ConfigOptions& options) : Source(name, io), m_options(options) {} virtual ~Adapter() {} @@ -41,20 +41,20 @@ namespace mtconnect::source::adapter { /// @brief Get the host name /// @return the host - virtual const std::string &getHost() const = 0; + virtual const std::string& getHost() const = 0; /// @brief Get the adapter's identity /// @return the identity - const std::string &getIdentity() const override { return m_identity; } + const std::string& getIdentity() const override { return m_identity; } /// @brief Get the port /// @return the port virtual unsigned int getPort() const = 0; /// @brief Get the configuration options /// @return configuration options - virtual const ConfigOptions &getOptions() const { return m_options; } + virtual const ConfigOptions& getOptions() const { return m_options; } /// @brief set the adapter handler /// @param h the handler (takes ownership) - void setHandler(std::unique_ptr &h) { m_handler = std::move(h); } + void setHandler(std::unique_ptr& h) { m_handler = std::move(h); } ///@} protected: diff --git a/src/mtconnect/source/adapter/adapter_pipeline.cpp b/src/mtconnect/source/adapter/adapter_pipeline.cpp index cb258cd9..63852c4f 100644 --- a/src/mtconnect/source/adapter/adapter_pipeline.cpp +++ b/src/mtconnect/source/adapter/adapter_pipeline.cpp @@ -46,33 +46,33 @@ namespace mtconnect { auto handler = make_unique(); // Build the pipeline for an adapter - handler->m_connecting = [this](const std::string &id) { + handler->m_connecting = [this](const std::string& id) { auto entity = make_shared("ConnectionStatus", Properties {{"VALUE", "CONNECTING"s}, {"source", id}}); run(std::move(entity)); }; - handler->m_connected = [this](const std::string &id) { + handler->m_connected = [this](const std::string& id) { auto entity = make_shared("ConnectionStatus", Properties {{"VALUE", "CONNECTED"s}, {"source", id}}); run(std::move(entity)); }; - handler->m_disconnected = [this](const std::string &id) { + handler->m_disconnected = [this](const std::string& id) { auto entity = make_shared("ConnectionStatus", Properties {{"VALUE", "DISCONNECTED"s}, {"source", id}}); run(std::move(entity)); }; - handler->m_processData = [this](const std::string &data, const std::string &source) { + handler->m_processData = [this](const std::string& data, const std::string& source) { auto entity = make_shared("Data", Properties {{"VALUE", data}, {"source", source}}); run(std::move(entity)); }; - handler->m_processMessage = [this](const std::string &topic, const std::string &data, - const std::string &source) { + handler->m_processMessage = [this](const std::string& topic, const std::string& data, + const std::string& source) { auto entity = make_shared( "Message", Properties {{"VALUE", data}, {"topic", topic}, {"source", source}}); run(std::move(entity)); }; - handler->m_command = [this](const std::string &command, const std::string &value, - const std::string &source) { + handler->m_command = [this](const std::string& command, const std::string& value, + const std::string& source) { auto entity = make_shared( "Command", Properties {{"command", command}, {"VALUE", value}, {"source", source}}); run(std::move(entity)); @@ -81,7 +81,7 @@ namespace mtconnect { return handler; } - void AdapterPipeline::build(const ConfigOptions &options) + void AdapterPipeline::build(const ConfigOptions& options) { clear(); m_options = options; diff --git a/src/mtconnect/source/adapter/adapter_pipeline.hpp b/src/mtconnect/source/adapter/adapter_pipeline.hpp index 684531aa..c283a1a2 100644 --- a/src/mtconnect/source/adapter/adapter_pipeline.hpp +++ b/src/mtconnect/source/adapter/adapter_pipeline.hpp @@ -25,12 +25,12 @@ namespace mtconnect::source::adapter { /// @brief Handler functions for handling data and connection status struct Handler { - using ProcessData = std::function; - using ProcessCommand = std::function; - using ProcessMessage = std::function; - using Connect = std::function; + using ProcessData = std::function; + using ProcessCommand = std::function; + using ProcessMessage = std::function; + using Connect = std::function; /// @brief Process Data Messages ProcessData m_processData; @@ -55,24 +55,24 @@ namespace mtconnect::source::adapter { /// @brief Create and adapter pipeline /// @param context the pipeline context /// @param st boost asio strand - AdapterPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand &st) + AdapterPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand& st) : Pipeline(context, st) {} /// @brief build the pipeline /// @param options the configuration options - void build(const ConfigOptions &options) override; + void build(const ConfigOptions& options) override; /// @brief Create a handler /// @return the handler handing over ownership virtual std::unique_ptr makeHandler(); /// @brief get the associated device /// @return the device - const auto &getDevice() const { return m_device; } + const auto& getDevice() const { return m_device; } /// @brief set the associated device /// @param d the device - void setDevice(const std::string &d) { m_device = d; } + void setDevice(const std::string& d) { m_device = d; } protected: void buildDeviceList(); diff --git a/src/mtconnect/source/adapter/agent_adapter/agent_adapter.cpp b/src/mtconnect/source/adapter/agent_adapter/agent_adapter.cpp index 4c5a629c..4ca84a64 100644 --- a/src/mtconnect/source/adapter/agent_adapter/agent_adapter.cpp +++ b/src/mtconnect/source/adapter/agent_adapter/agent_adapter.cpp @@ -42,7 +42,7 @@ using namespace mtconnect::pipeline; using namespace mtconnect::url; namespace mtconnect::source::adapter::agent_adapter { - void AgentAdapterPipeline::build(const ConfigOptions &options) + void AgentAdapterPipeline::build(const ConfigOptions& options) { m_options = options; m_uuid = GetOption(options, configuration::UUID); @@ -60,8 +60,8 @@ namespace mtconnect::source::adapter::agent_adapter { applySplices(); } - AgentAdapter::AgentAdapter(boost::asio::io_context &io, pipeline::PipelineContextPtr context, - const ConfigOptions &options, const boost::property_tree::ptree &block) + AgentAdapter::AgentAdapter(boost::asio::io_context& io, pipeline::PipelineContextPtr context, + const ConfigOptions& options, const boost::property_tree::ptree& block) : Adapter("AgentAdapter", io, options), m_pipeline(context, Source::m_strand, m_feedback), m_reconnectTimer(io), @@ -269,7 +269,7 @@ namespace mtconnect::source::adapter::agent_adapter { } } - void AgentAdapter::assetsFailed(std::error_code &ec) + void AgentAdapter::assetsFailed(std::error_code& ec) { if (m_stopped) return; @@ -299,7 +299,7 @@ namespace mtconnect::source::adapter::agent_adapter { } } - void AgentAdapter::streamsFailed(std::error_code &ec) + void AgentAdapter::streamsFailed(std::error_code& ec) { if (m_stopped) return; diff --git a/src/mtconnect/source/adapter/agent_adapter/agent_adapter.hpp b/src/mtconnect/source/adapter/agent_adapter/agent_adapter.hpp index 925d6296..3f1256da 100644 --- a/src/mtconnect/source/adapter/agent_adapter/agent_adapter.hpp +++ b/src/mtconnect/source/adapter/agent_adapter/agent_adapter.hpp @@ -42,14 +42,14 @@ namespace mtconnect::source::adapter::agent_adapter { /// @param context the pipeline context /// @param st strand to run in /// @param feedback feedback from the pipeline to the adapter when an error occurs - AgentAdapterPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand &st, - pipeline::XmlTransformFeedback &feedback) + AgentAdapterPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand& st, + pipeline::XmlTransformFeedback& feedback) : AdapterPipeline(context, st), m_feedback(feedback) {} - void build(const ConfigOptions &options) override; + void build(const ConfigOptions& options) override; - Handler *m_handler = nullptr; - pipeline::XmlTransformFeedback &m_feedback; + Handler* m_handler = nullptr; + pipeline::XmlTransformFeedback& m_feedback; std::optional m_uuid; }; @@ -62,16 +62,16 @@ namespace mtconnect::source::adapter::agent_adapter { /// @param context pipeline context /// @param options configation options /// @param block additional configuration options - AgentAdapter(boost::asio::io_context &io, pipeline::PipelineContextPtr context, - const ConfigOptions &options, const boost::property_tree::ptree &block); + AgentAdapter(boost::asio::io_context& io, pipeline::PipelineContextPtr context, + const ConfigOptions& options, const boost::property_tree::ptree& block); /// @brief Register the agent adapter with the factory for `http` and `https` /// @param factory source factory - static void registerFactory(SourceFactory &factory) + static void registerFactory(SourceFactory& factory) { - auto cb = [](const std::string &name, boost::asio::io_context &io, - pipeline::PipelineContextPtr context, const ConfigOptions &options, - const boost::property_tree::ptree &block) -> source::SourcePtr { + auto cb = [](const std::string& name, boost::asio::io_context& io, + pipeline::PipelineContextPtr context, const ConfigOptions& options, + const boost::property_tree::ptree& block) -> source::SourcePtr { auto source = std::make_shared(io, context, options, block); return source; }; @@ -81,17 +81,17 @@ namespace mtconnect::source::adapter::agent_adapter { /// @name Agent Device methods ///@{ - const std::string &getHost() const override { return m_host; } + const std::string& getHost() const override { return m_host; } unsigned int getPort() const override { return 0; } ///@} /// @brief get a reference to the transform feedback /// @return reference to the transform feedback - auto &getFeedback() { return m_feedback; } + auto& getFeedback() { return m_feedback; } /// @brief get the current outstanding stream request (for testing) /// @return reference to the optional stream request - auto &getStreamRequest() { return m_streamRequest; } + auto& getStreamRequest() { return m_streamRequest; } ~AgentAdapter() override; @@ -99,7 +99,7 @@ namespace mtconnect::source::adapter::agent_adapter { ///@{ bool start() override; void stop() override; - pipeline::Pipeline *getPipeline() override { return &m_pipeline; } + pipeline::Pipeline* getPipeline() override { return &m_pipeline; } ///@} /// @brief get a shared pointer to the source @@ -115,8 +115,8 @@ namespace mtconnect::source::adapter::agent_adapter { void assets(); void updateAssets(); - void streamsFailed(std::error_code &ec); - void assetsFailed(std::error_code &ec); + void streamsFailed(std::error_code& ec); + void assetsFailed(std::error_code& ec); void recoverStreams(); void recoverAssetRequest(); diff --git a/src/mtconnect/source/adapter/agent_adapter/http_session.hpp b/src/mtconnect/source/adapter/agent_adapter/http_session.hpp index e24935d9..fce298a9 100644 --- a/src/mtconnect/source/adapter/agent_adapter/http_session.hpp +++ b/src/mtconnect/source/adapter/agent_adapter/http_session.hpp @@ -33,7 +33,7 @@ namespace mtconnect::source::adapter::agent_adapter { /// @brief Create a session to connect to the remote agent /// @param ioc the asio strand to run in /// @param url URL to connect to - HttpSession(boost::asio::io_context::strand &ioc, const url::Url &url) + HttpSession(boost::asio::io_context::strand& ioc, const url::Url& url) : super(ioc, url), m_stream(ioc.context()) {} @@ -52,13 +52,13 @@ namespace mtconnect::source::adapter::agent_adapter { /// @brief Get the boost asio tcp stream /// @return reference to the stream - auto &stream() { return m_stream; } + auto& stream() { return m_stream; } /// @brief Get the lowest protocol layer to the tcp stream /// @return lowest protocol layer - auto &lowestLayer() { return beast::get_lowest_layer(m_stream); } + auto& lowestLayer() { return beast::get_lowest_layer(m_stream); } /// @brief Get an immutable lowest protocol layer to the tcp stream /// @return const lowest protocol layer - const auto &lowestLayer() const { return beast::get_lowest_layer(m_stream); } + const auto& lowestLayer() const { return beast::get_lowest_layer(m_stream); } /// @brief method called asynchonously when the source connects to the agent /// @param ec an error code diff --git a/src/mtconnect/source/adapter/agent_adapter/https_session.hpp b/src/mtconnect/source/adapter/agent_adapter/https_session.hpp index 372d129e..bb13e61f 100644 --- a/src/mtconnect/source/adapter/agent_adapter/https_session.hpp +++ b/src/mtconnect/source/adapter/agent_adapter/https_session.hpp @@ -36,8 +36,8 @@ namespace mtconnect::source::adapter::agent_adapter { /// @param ex the strand to run in /// @param url the url to connect to /// @param ctx the TLS context - explicit HttpsSession(boost::asio::io_context::strand &ex, const url::Url &url, - ssl::context &ctx) + explicit HttpsSession(boost::asio::io_context::strand& ex, const url::Url& url, + ssl::context& ctx) : super(ex, url), m_stream(ex.context(), ctx) {} ~HttpsSession() @@ -48,13 +48,13 @@ namespace mtconnect::source::adapter::agent_adapter { /// @brief Get the boost asio ssl tcp stream /// @return reference to the stream - auto &stream() { return m_stream; } + auto& stream() { return m_stream; } /// @brief Get the lowest protocol layer to the ssl tcp stream /// @return lowest protocol layer - auto &lowestLayer() { return beast::get_lowest_layer(m_stream); } + auto& lowestLayer() { return beast::get_lowest_layer(m_stream); } /// @brief Get an immutable lowest protocol layer to the ssl tcp stream /// @return const lowest protocol layer - const auto &lowestLayer() const { return beast::get_lowest_layer(m_stream); } + const auto& lowestLayer() const { return beast::get_lowest_layer(m_stream); } std::shared_ptr getptr() { diff --git a/src/mtconnect/source/adapter/agent_adapter/session.hpp b/src/mtconnect/source/adapter/agent_adapter/session.hpp index 3d6b3638..5958cbc2 100644 --- a/src/mtconnect/source/adapter/agent_adapter/session.hpp +++ b/src/mtconnect/source/adapter/agent_adapter/session.hpp @@ -39,7 +39,7 @@ namespace mtconnect::source::adapter::agent_adapter { { public: using Next = std::function; - using Failure = std::function; + using Failure = std::function; using UpdateAssets = std::function; /// @brief An HTTP Request wrapper @@ -51,8 +51,8 @@ namespace mtconnect::source::adapter::agent_adapter { /// @param query The URL query parameters /// @param stream `true` if HTTP x-multipart-replace streaming is desired /// @param next Function to determine what to do on successful read - Request(const std::optional &device, const std::string &operation, - const url::UrlQuery &query, bool stream, Next next) + Request(const std::optional& device, const std::string& operation, + const url::UrlQuery& query, bool stream, Next next) : m_sourceDevice(device), m_operation(operation), m_query(query), @@ -60,7 +60,7 @@ namespace mtconnect::source::adapter::agent_adapter { m_next(next) {} - Request(const Request &request) = default; + Request(const Request& request) = default; std::optional m_sourceDevice; ///< optional source device std::string m_operation; ///< The REST operation (probe, current, sample, asset) @@ -72,7 +72,7 @@ namespace mtconnect::source::adapter::agent_adapter { /// @brief Given a url, get a formatted target for a given operation /// @param url The base url /// @return a string with a new URL path and query (for the GET) - auto getTarget(const url::Url &url) + auto getTarget(const url::Url& url) { return url.getTarget(m_sourceDevice, m_operation, m_query); } @@ -91,20 +91,20 @@ namespace mtconnect::source::adapter::agent_adapter { /// @brief Method called with something fails /// @param ec the error code /// @param what descriptive message - virtual void failed(std::error_code ec, const char *what) = 0; + virtual void failed(std::error_code ec, const char* what) = 0; /// @brief close the connection virtual void close() = 0; /// @brief Make a request of the remote agent /// @param request the request /// @return `true` if successful - virtual bool makeRequest(const Request &request) = 0; + virtual bool makeRequest(const Request& request) = 0; ///@} /// @name Setters for session configuration ///@{ - void setHandler(Handler *handler) { m_handler = handler; } - void setIdentity(const std::string &identity) { m_identity = identity; } + void setHandler(Handler* handler) { m_handler = handler; } + void setIdentity(const std::string& identity) { m_identity = identity; } void setFailed(Failure failed) { m_failed = std::move(failed); } void setUpdateAssets(UpdateAssets updateAssets) { m_updateAssets = std::move(updateAssets); } void setCloseConnectionAfterResponse(bool close) { m_closeConnectionAfterResponse = close; } @@ -112,7 +112,7 @@ namespace mtconnect::source::adapter::agent_adapter { ///@} protected: - Handler *m_handler = nullptr; ///< Pipeline handler for processing data + Handler* m_handler = nullptr; ///< Pipeline handler for processing data std::string m_identity; ///< Unique identity hash for this session Failure m_failed; ///< Callback invoked on connection failure UpdateAssets m_updateAssets; ///< Callback to trigger asset updates diff --git a/src/mtconnect/source/adapter/agent_adapter/session_impl.hpp b/src/mtconnect/source/adapter/agent_adapter/session_impl.hpp index 78328512..3d1a7d60 100644 --- a/src/mtconnect/source/adapter/agent_adapter/session_impl.hpp +++ b/src/mtconnect/source/adapter/agent_adapter/session_impl.hpp @@ -49,14 +49,14 @@ namespace mtconnect::source::adapter::agent_adapter { public: /// @brief Cast this class as the derived class /// @return reference to the derived class - Derived &derived() { return static_cast(*this); } + Derived& derived() { return static_cast(*this); } /// @brief Immutably cast this class as its derived subclass /// @return const reference to the derived class - const Derived &derived() const { return static_cast(*this); } + const Derived& derived() const { return static_cast(*this); } // Objects are constructed with a strand to // ensure that handlers do not execute concurrently. - SessionImpl(boost::asio::io_context::strand &strand, const url::Url &url) + SessionImpl(boost::asio::io_context::strand& strand, const url::Url& url) : m_resolver(strand.context()), m_strand(strand), m_url(url), m_chunk(1 * 1024 * 1024) {} @@ -74,7 +74,7 @@ namespace mtconnect::source::adapter::agent_adapter { /// Closes the socket and resets the request /// @param ec error code to report /// @param what the reason why the failure occurred - void failed(std::error_code ec, const char *what) override + void failed(std::error_code ec, const char* what) override { derived().lowestLayer().socket().close(); @@ -94,7 +94,7 @@ namespace mtconnect::source::adapter::agent_adapter { void stop() override { m_request.reset(); } - bool makeRequest(const Request &req) override + bool makeRequest(const Request& req) override { if (!m_request) { @@ -134,18 +134,18 @@ namespace mtconnect::source::adapter::agent_adapter { /// @brief Process data from the remote agent /// @param data the payload from the agent - void processData(const std::string &data) + void processData(const std::string& data) { try { if (m_handler && m_handler->m_processData) m_handler->m_processData(data, m_identity); } - catch (FatalException &e) + catch (FatalException& e) { throw e; } - catch (std::system_error &e) + catch (std::system_error& e) { LOG(warning) << "AgentAdapter - Error occurred processing data: " << e.what(); if (e.code().category() == TheErrorCategory()) @@ -154,7 +154,7 @@ namespace mtconnect::source::adapter::agent_adapter { failed(source::make_error_code(ErrorCode::RETRY_REQUEST), "Exception occurred in AgentAdapter::processData"); } - catch (std::exception &e) + catch (std::exception& e) { LOG(error) << "AgentAdapter - Error occurred processing data: " << e.what(); failed(source::make_error_code(ErrorCode::RETRY_REQUEST), @@ -318,7 +318,7 @@ namespace mtconnect::source::adapter::agent_adapter { return failed(source::make_error_code(ErrorCode::RETRY_REQUEST), "header"); } - auto &msg = m_headerParser->get(); + auto& msg = m_headerParser->get(); if (msg.version() < 11) { LOG(trace) << "Agent adapter: HTTP 10 requires close on read"; @@ -432,7 +432,7 @@ namespace mtconnect::source::adapter::agent_adapter { void createChunkHeaderHandler() { m_chunkHeaderHandler = [this](std::uint64_t size, boost::string_view extensions, - boost::system::error_code &ec) { + boost::system::error_code& ec) { derived().lowestLayer().expires_after(m_timeout); if (ec) @@ -457,7 +457,7 @@ namespace mtconnect::source::adapter::agent_adapter { return false; } - auto start = static_cast(m_chunk.data().data()); + auto start = static_cast(m_chunk.data().data()); boost::string_view view(start, m_chunk.data().size()); auto bp = view.find(m_boundary.c_str()); @@ -520,7 +520,7 @@ namespace mtconnect::source::adapter::agent_adapter { void createChunkBodyHandler() { m_chunkHandler = [this](std::uint64_t remain, boost::string_view body, - boost::system::error_code &ev) -> std::size_t { + boost::system::error_code& ev) -> std::size_t { if (!m_request) { derived().lowestLayer().close(); @@ -549,7 +549,7 @@ namespace mtconnect::source::adapter::agent_adapter { auto len = m_chunk.size(); if (len >= m_chunkLength) { - auto start = static_cast(m_chunk.data().data()); + auto start = static_cast(m_chunk.data().data()); boost::string_view sbuf(start, m_chunkLength); LOG(trace) << "Received Chunk: --------\n" << sbuf << "\n-------------"; @@ -603,9 +603,9 @@ namespace mtconnect::source::adapter::agent_adapter { asio::io_context::strand m_strand; url::Url m_url; - std::function + std::function m_chunkHandler; - std::function + std::function m_chunkHeaderHandler; std::string m_boundary; diff --git a/src/mtconnect/source/adapter/mqtt/mqtt_adapter.cpp b/src/mtconnect/source/adapter/mqtt/mqtt_adapter.cpp index 358374ee..5664d5de 100644 --- a/src/mtconnect/source/adapter/mqtt/mqtt_adapter.cpp +++ b/src/mtconnect/source/adapter/mqtt/mqtt_adapter.cpp @@ -51,9 +51,9 @@ namespace mtconnect { namespace source::adapter::mqtt_adapter { - MqttAdapter::MqttAdapter(boost::asio::io_context &io, + MqttAdapter::MqttAdapter(boost::asio::io_context& io, pipeline::PipelineContextPtr pipelineContext, - const ConfigOptions &options, const boost::property_tree::ptree &block) + const ConfigOptions& options, const boost::property_tree::ptree& block) : Adapter("MQTT", io, options), m_ioContext(io), m_strand(Source::m_strand), @@ -121,8 +121,8 @@ namespace mtconnect { m_handler->m_disconnected(m_identity); }; - clientHandler->m_receive = [this](shared_ptr client, const std::string &topic, - const std::string &payload) { + clientHandler->m_receive = [this](shared_ptr client, const std::string& topic, + const std::string& payload) { m_handler->m_processMessage(topic, payload, m_identity); }; @@ -163,7 +163,7 @@ namespace mtconnect { auto topics = GetOption(m_options, configuration::Topics); if (topics) { - for (const auto &s : *topics) + for (const auto& s : *topics) identity << s; } @@ -174,7 +174,7 @@ namespace mtconnect { m_pipeline.build(m_options); } - void MqttAdapter::loadTopics(const boost::property_tree::ptree &tree, ConfigOptions &options) + void MqttAdapter::loadTopics(const boost::property_tree::ptree& tree, ConfigOptions& options) { auto topics = tree.get_child_optional(configuration::Topics); if (topics) @@ -187,7 +187,7 @@ namespace mtconnect { } else { - for (auto &f : *topics) + for (auto& f : *topics) { list.emplace_back(f.second.data()); } @@ -207,19 +207,19 @@ namespace mtconnect { /// /// /// - void MqttAdapter::registerFactory(SourceFactory &factory) + void MqttAdapter::registerFactory(SourceFactory& factory) { factory.registerFactory("mqtt", - [](const std::string &name, boost::asio::io_context &io, - pipeline::PipelineContextPtr context, const ConfigOptions &options, - const boost::property_tree::ptree &block) -> source::SourcePtr { + [](const std::string& name, boost::asio::io_context& io, + pipeline::PipelineContextPtr context, const ConfigOptions& options, + const boost::property_tree::ptree& block) -> source::SourcePtr { auto source = std::make_shared(io, context, options, block); return source; }); } - const std::string &MqttAdapter::getHost() const { return m_host; } + const std::string& MqttAdapter::getHost() const { return m_host; } unsigned int MqttAdapter::getPort() const { return m_port; } @@ -241,16 +241,16 @@ namespace mtconnect { LOG(info) << "MqttClientImpl::connect: subscribing to topics"; if (topics) { - for (const auto &topic : *topics) + for (const auto& topic : *topics) { m_client->subscribe(topic); } } } - mtconnect::pipeline::Pipeline *MqttAdapter::getPipeline() { return &m_pipeline; } + mtconnect::pipeline::Pipeline* MqttAdapter::getPipeline() { return &m_pipeline; } - void MqttPipeline::build(const ConfigOptions &options) + void MqttPipeline::build(const ConfigOptions& options) { AdapterPipeline::build(options); diff --git a/src/mtconnect/source/adapter/mqtt/mqtt_adapter.hpp b/src/mtconnect/source/adapter/mqtt/mqtt_adapter.hpp index c4b45b89..8efe9144 100644 --- a/src/mtconnect/source/adapter/mqtt/mqtt_adapter.hpp +++ b/src/mtconnect/source/adapter/mqtt/mqtt_adapter.hpp @@ -34,12 +34,12 @@ namespace mtconnect::source::adapter::mqtt_adapter { /// new Mqtt session with the upstream agent /// @param context the pipeline context /// @param st strand to run in - MqttPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand &strand) + MqttPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand& strand) : AdapterPipeline(context, strand) {} - void build(const ConfigOptions &options) override; - Handler *m_handler {nullptr}; + void build(const ConfigOptions& options) override; + Handler* m_handler {nullptr}; }; /// @brief An Mqtt adapter to connnect to another Agent and replicate data @@ -52,18 +52,18 @@ namespace mtconnect::source::adapter::mqtt_adapter { /// @param context pipeline context /// @param options configation options /// @param block additional configuration options - MqttAdapter(boost::asio::io_context &io, pipeline::PipelineContextPtr pipelineContext, - const ConfigOptions &options, const boost::property_tree::ptree &block); + MqttAdapter(boost::asio::io_context& io, pipeline::PipelineContextPtr pipelineContext, + const ConfigOptions& options, const boost::property_tree::ptree& block); ~MqttAdapter() override {} /// @brief Register the Mqtt adapter with the factory /// @param factory source factory - static void registerFactory(SourceFactory &factory); + static void registerFactory(SourceFactory& factory); /// @name Agent Device methods ///@{ - const std::string &getHost() const override; + const std::string& getHost() const override; unsigned int getPort() const override; ///@} @@ -74,7 +74,7 @@ namespace mtconnect::source::adapter::mqtt_adapter { void stop() override; - pipeline::Pipeline *getPipeline() override; + pipeline::Pipeline* getPipeline() override; ///@} /// @brief subcribe to topics @@ -84,10 +84,10 @@ namespace mtconnect::source::adapter::mqtt_adapter { /// @brief load all topics /// @param ptree the property tree coming from configuration parser /// @param options configation options - void loadTopics(const boost::property_tree::ptree &tree, ConfigOptions &options); + void loadTopics(const boost::property_tree::ptree& tree, ConfigOptions& options); protected: - boost::asio::io_context &m_ioContext; + boost::asio::io_context& m_ioContext; boost::asio::io_context::strand m_strand; // If the connector has been running diff --git a/src/mtconnect/source/adapter/shdr/connector.cpp b/src/mtconnect/source/adapter/shdr/connector.cpp index 8db4a8b4..5f4a6246 100644 --- a/src/mtconnect/source/adapter/shdr/connector.cpp +++ b/src/mtconnect/source/adapter/shdr/connector.cpp @@ -42,7 +42,7 @@ namespace sys = boost::system; namespace mtconnect::source::adapter::shdr { // Connector public methods - Connector::Connector(asio::io_context::strand &strand, string server, unsigned int port, + Connector::Connector(asio::io_context::strand& strand, string server, unsigned int port, seconds legacyTimeout, seconds reconnectInterval, std::optional heartbeat) : m_server(std::move(server)), @@ -88,7 +88,7 @@ namespace mtconnect::source::adapter::shdr { return true; } - void Connector::resolved(const boost::system::error_code &ec, + void Connector::resolved(const boost::system::error_code& ec, asio::ip::tcp::resolver::results_type results) { NAMED_SCOPE("Connector::resolved"); @@ -184,7 +184,7 @@ namespace mtconnect::source::adapter::shdr { asyncTryConnect(); } - void Connector::connected(const boost::system::error_code &ec, const ip::tcp::endpoint &endpoint) + void Connector::connected(const boost::system::error_code& ec, const ip::tcp::endpoint& endpoint) { NAMED_SCOPE("Connector::connected"); @@ -272,7 +272,7 @@ namespace mtconnect::source::adapter::shdr { } } - void Connector::parseBuffer(const char *buffer) + void Connector::parseBuffer(const char* buffer) { std::ostream os(&m_incoming); os << buffer; @@ -300,7 +300,7 @@ namespace mtconnect::source::adapter::shdr { }); } - inline void Connector::processLine(const std::string &line) + inline void Connector::processLine(const std::string& line) { NAMED_SCOPE("Connector::processLine"); @@ -320,7 +320,7 @@ namespace mtconnect::source::adapter::shdr { } } - inline size_t rightTrimmedSize(const char *cp, const char *start) + inline size_t rightTrimmedSize(const char* cp, const char* start) { while (cp > start && isspace(*cp)) cp--; @@ -338,14 +338,14 @@ namespace mtconnect::source::adapter::shdr { return false; // Grab the beginning of the data buffer. - auto start = static_cast(m_incoming.data().data()); + auto start = static_cast(m_incoming.data().data()); auto len = m_incoming.data().size(); LOG(trace) << "(" << m_server << ":" << m_port << ") " << len << " characters in incomming buffer"; // Scan forward in the buffer for a \n - const char *eol = static_cast(memchr(start, '\n', len)); + const char* eol = static_cast(memchr(start, '\n', len)); size_t consumed = (eol == nullptr) ? 0 : eol - start + 1; // If there is no end of line, wait for more data. @@ -377,7 +377,7 @@ namespace mtconnect::source::adapter::shdr { return m_incoming.size() > 0; } - void Connector::sendCommand(const string &command) + void Connector::sendCommand(const string& command) { NAMED_SCOPE("Connector::sendCommand"); @@ -412,7 +412,7 @@ namespace mtconnect::source::adapter::shdr { } } - void Connector::startHeartbeats(const string &arg) + void Connector::startHeartbeats(const string& arg) { NAMED_SCOPE("Connector::startHeartbeats"); @@ -470,7 +470,7 @@ namespace mtconnect::source::adapter::shdr { if (m_socket.is_open()) m_socket.close(); } - catch (exception &e) + catch (exception& e) { LOG(error) << "(Port:" << m_localPort << ")" << "unexpected exception during close: " << e.what(); diff --git a/src/mtconnect/source/adapter/shdr/connector.hpp b/src/mtconnect/source/adapter/shdr/connector.hpp index ad0c2169..726cca02 100644 --- a/src/mtconnect/source/adapter/shdr/connector.hpp +++ b/src/mtconnect/source/adapter/shdr/connector.hpp @@ -40,7 +40,7 @@ namespace mtconnect::source::adapter::shdr { /// @param port port to connect to /// @param legacyTimout connection timeout (defaulted to 5 minutes) /// @param reconnectInterval time between reconnection attempts (defaults to 10 seconds) - Connector(boost::asio::io_context::strand &strand, std::string server, unsigned int port, + Connector(boost::asio::io_context::strand& strand, std::string server, unsigned int port, std::chrono::seconds legacyTimout = std::chrono::seconds {600}, std::chrono::seconds reconnectInterval = std::chrono::seconds {10}, std::optional heartbeat = std::nullopt); @@ -58,8 +58,8 @@ namespace mtconnect::source::adapter::shdr { virtual bool connect(); // Abstract method to handle what to do with each line of data from Socket - virtual void processData(const std::string &data) = 0; - virtual void protocolCommand(const std::string &data) = 0; + virtual void processData(const std::string& data) = 0; + virtual void protocolCommand(const std::string& data) = 0; // Set Reconnect intervals void setReconnectInterval(std::chrono::milliseconds interval) @@ -81,13 +81,13 @@ namespace mtconnect::source::adapter::shdr { std::chrono::milliseconds heartbeatFrequency() const { return m_heartbeatFrequency; } // Collect data and until it is \n terminated - void parseBuffer(const char *buffer); + void parseBuffer(const char* buffer); // Send a command to the adapter - void sendCommand(const std::string &command); + void sendCommand(const std::string& command); unsigned int getPort() const { return m_port; } - const std::string &getServer() const { return m_server; } + const std::string& getServer() const { return m_server; } std::chrono::seconds getLegacyTimeout() const { @@ -96,21 +96,21 @@ namespace mtconnect::source::adapter::shdr { void setRealTime(bool realTime = true) { m_realTime = realTime; } - const auto &getHeartbeatOverride() const { return m_heartbeatOverride; } + const auto& getHeartbeatOverride() const { return m_heartbeatOverride; } protected: void close(); void reconnect(); void asyncTryConnect(); - void resolved(const boost::system::error_code &error, + void resolved(const boost::system::error_code& error, boost::asio::ip::tcp::resolver::results_type results); - void connected(const boost::system::error_code &error, - const boost::asio::ip::tcp::endpoint &endpoint); + void connected(const boost::system::error_code& error, + const boost::asio::ip::tcp::endpoint& endpoint); void writer(boost::system::error_code ec, std::size_t length); void reader(boost::system::error_code ec, std::size_t length); bool parseSocketBuffer(); - void processLine(const std::string &line); - void startHeartbeats(const std::string &buf); + void processLine(const std::string& line); + void startHeartbeats(const std::string& buf); void heartbeat(boost::system::error_code ec); void setReceiveTimeout(); @@ -119,7 +119,7 @@ namespace mtconnect::source::adapter::shdr { std::string m_server; // Connection – reference to the owning Source's strand (not a copy) - boost::asio::io_context::strand &m_strand; + boost::asio::io_context::strand& m_strand; boost::asio::ip::tcp::socket m_socket; boost::asio::ip::tcp::endpoint m_endpoint; boost::asio::ip::tcp::resolver::results_type m_results; diff --git a/src/mtconnect/source/adapter/shdr/shdr_adapter.cpp b/src/mtconnect/source/adapter/shdr/shdr_adapter.cpp index b013bc21..9826f509 100644 --- a/src/mtconnect/source/adapter/shdr/shdr_adapter.cpp +++ b/src/mtconnect/source/adapter/shdr/shdr_adapter.cpp @@ -37,9 +37,9 @@ using namespace std::literals; namespace mtconnect::source::adapter::shdr { // Adapter public methods - ShdrAdapter::ShdrAdapter(boost::asio::io_context &io, + ShdrAdapter::ShdrAdapter(boost::asio::io_context& io, pipeline::PipelineContextPtr pipelineContext, - const ConfigOptions &options, const boost::property_tree::ptree &block) + const ConfigOptions& options, const boost::property_tree::ptree& block) : Adapter("ShdrAdapter", io, options), Connector(Source::m_strand, "", 0, 60s), m_pipeline(pipelineContext, Source::m_strand), @@ -113,7 +113,7 @@ namespace mtconnect::source::adapter::shdr { } } - void ShdrAdapter::processData(const string &data) + void ShdrAdapter::processData(const string& data) { NAMED_SCOPE("ShdrAdapter::processData"); @@ -143,7 +143,7 @@ namespace mtconnect::source::adapter::shdr { forwardData(data); } } - catch (std::exception &e) + catch (std::exception& e) { LOG(error) << "Error in processData: " << e.what(); } @@ -165,9 +165,9 @@ namespace mtconnect::source::adapter::shdr { LOG(debug) << "Adapter exited: " << m_name; } - inline bool is_true(const std::string &value) { return value == "yes" || value == "true"; } + inline bool is_true(const std::string& value) { return value == "yes" || value == "true"; } - void ShdrAdapter::protocolCommand(const std::string &data) + void ShdrAdapter::protocolCommand(const std::string& data) { NAMED_SCOPE("ShdrAdapter::protocolCommand"); @@ -182,7 +182,7 @@ namespace mtconnect::source::adapter::shdr { using qi::lit; string command; - auto f = [&command](const auto &s) { command = string(s.begin(), s.end()); }; + auto f = [&command](const auto& s) { command = string(s.begin(), s.end()); }; auto it = data.begin(); bool res = diff --git a/src/mtconnect/source/adapter/shdr/shdr_adapter.hpp b/src/mtconnect/source/adapter/shdr/shdr_adapter.hpp index a760a442..ed353b9c 100644 --- a/src/mtconnect/source/adapter/shdr/shdr_adapter.hpp +++ b/src/mtconnect/source/adapter/shdr/shdr_adapter.hpp @@ -49,19 +49,19 @@ namespace mtconnect { /// @param[in] pipelineContext pipeline context /// @param[in] options configuration options /// @param[in] block additional configuration options not in options - ShdrAdapter(boost::asio::io_context &io, pipeline::PipelineContextPtr pipelineContext, - const ConfigOptions &options, const boost::property_tree::ptree &block); - ShdrAdapter(const ShdrAdapter &) = delete; + ShdrAdapter(boost::asio::io_context& io, pipeline::PipelineContextPtr pipelineContext, + const ConfigOptions& options, const boost::property_tree::ptree& block); + ShdrAdapter(const ShdrAdapter&) = delete; /// @brief Factory registration method associate this source with `shdr` /// @param[in] factory the source factory - static void registerFactory(SourceFactory &factory) + static void registerFactory(SourceFactory& factory) { factory.registerFactory( "shdr", - [](const std::string &name, boost::asio::io_context &io, - pipeline::PipelineContextPtr context, const ConfigOptions &options, - const boost::property_tree::ptree &block) -> source::SourcePtr { + [](const std::string& name, boost::asio::io_context& io, + pipeline::PipelineContextPtr context, const ConfigOptions& options, + const boost::property_tree::ptree& block) -> source::SourcePtr { auto source = std::make_shared(io, context, options, block); return source; }); @@ -72,12 +72,12 @@ namespace mtconnect { /// @brief The termination text when collecting multi-line data /// @return the termination text - auto &getTerminator() const { return m_terminator; } + auto& getTerminator() const { return m_terminator; } /// @name Source interface ///@{ - void processData(const std::string &data) override; - void protocolCommand(const std::string &data) override; + void processData(const std::string& data) override; + void protocolCommand(const std::string& data) override; // Method called when connection is lost. void connecting() override @@ -110,18 +110,18 @@ namespace mtconnect { /// @name Agent Device methods ///@{ - const std::string &getHost() const override { return m_server; } + const std::string& getHost() const override { return m_server; } unsigned int getPort() const override { return m_port; } - pipeline::Pipeline *getPipeline() override { return &m_pipeline; } + pipeline::Pipeline* getPipeline() override { return &m_pipeline; } ///@} /// @brief Change the options for the adapter /// @param[in] options the set of options - void setOptions(const ConfigOptions &options) override + void setOptions(const ConfigOptions& options) override { bool changed = false; - for (auto &o : options) + for (auto& o : options) { auto it = m_options.find(o.first); if (it == m_options.end() || it->second != o.second) @@ -140,7 +140,7 @@ namespace mtconnect { } protected: - void forwardData(const std::string &data) + void forwardData(const std::string& data) { if (data[0] == '*') protocolCommand(data); diff --git a/src/mtconnect/source/adapter/shdr/shdr_pipeline.cpp b/src/mtconnect/source/adapter/shdr/shdr_pipeline.cpp index 167927ea..e3895b73 100644 --- a/src/mtconnect/source/adapter/shdr/shdr_pipeline.cpp +++ b/src/mtconnect/source/adapter/shdr/shdr_pipeline.cpp @@ -40,7 +40,7 @@ namespace mtconnect { using namespace pipeline; namespace source::adapter::shdr { - void ShdrPipeline::build(const ConfigOptions &options) + void ShdrPipeline::build(const ConfigOptions& options) { AdapterPipeline::build(options); buildDeviceList(); diff --git a/src/mtconnect/source/adapter/shdr/shdr_pipeline.hpp b/src/mtconnect/source/adapter/shdr/shdr_pipeline.hpp index 062fdfd0..b480bd75 100644 --- a/src/mtconnect/source/adapter/shdr/shdr_pipeline.hpp +++ b/src/mtconnect/source/adapter/shdr/shdr_pipeline.hpp @@ -28,10 +28,10 @@ namespace mtconnect::source::adapter::shdr { /// @brief Create a pipeline for the SHDR Adapter /// @param context the pipeline context /// @param st boost asio strand for this source - ShdrPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand &st) + ShdrPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand& st) : AdapterPipeline(context, st) {} - void build(const ConfigOptions &options) override; + void build(const ConfigOptions& options) override; }; } // namespace mtconnect::source::adapter::shdr diff --git a/src/mtconnect/source/error_code.hpp b/src/mtconnect/source/error_code.hpp index 786669f2..11e1f230 100644 --- a/src/mtconnect/source/error_code.hpp +++ b/src/mtconnect/source/error_code.hpp @@ -51,7 +51,7 @@ namespace mtconnect::source { /// @brief Error categories for error reporting using std:error_code and std::error_condition struct ErrorCategory : std::error_category { - const char *name() const noexcept override { return "MTConnect::Error"; } + const char* name() const noexcept override { return "MTConnect::Error"; } std::string message(int ec) const override { switch (static_cast(ec)) @@ -83,7 +83,7 @@ namespace mtconnect::source { } }; - AGENT_SYMBOL_VISIBLE inline const std::error_category &TheErrorCategory() + AGENT_SYMBOL_VISIBLE inline const std::error_category& TheErrorCategory() { static const ErrorCategory theErrorCategory {}; return theErrorCategory; diff --git a/src/mtconnect/source/loopback_source.cpp b/src/mtconnect/source/loopback_source.cpp index 23aab7cc..5a661283 100644 --- a/src/mtconnect/source/loopback_source.cpp +++ b/src/mtconnect/source/loopback_source.cpp @@ -36,7 +36,7 @@ namespace mtconnect::source { using namespace observation; using namespace asset; using namespace pipeline; - void LoopbackPipeline::build(const ConfigOptions &options) + void LoopbackPipeline::build(const ConfigOptions& options) { m_options = options; @@ -86,7 +86,7 @@ namespace mtconnect::source { else { LOG(error) << "Cannot add observation: "; - for (auto &e : errors) + for (auto& e : errors) { LOG(error) << "Cannot add observation: " << e->what(); } @@ -95,7 +95,7 @@ namespace mtconnect::source { return 0; } - SequenceNumber_t LoopbackSource::receive(DataItemPtr dataItem, const std::string &value, + SequenceNumber_t LoopbackSource::receive(DataItemPtr dataItem, const std::string& value, std::optional timestamp) { if (dataItem->isCondition()) @@ -104,7 +104,7 @@ namespace mtconnect::source { return receive(dataItem, {{"VALUE", value}}, timestamp); } - SequenceNumber_t LoopbackSource::receive(const std::string &data) + SequenceNumber_t LoopbackSource::receive(const std::string& data) { auto ent = make_shared("Data", Properties {{"VALUE", data}, {"source", getIdentity()}}); auto res = m_pipeline.run(std::move(ent)); @@ -120,11 +120,11 @@ namespace mtconnect::source { void LoopbackSource::receive(DevicePtr device) { m_pipeline.run(device); } - AssetPtr LoopbackSource::receiveAsset(DevicePtr device, const std::string &document, - const std::optional &id, - const std::optional &type, - const std::optional &time, - entity::ErrorList &errors) + AssetPtr LoopbackSource::receiveAsset(DevicePtr device, const std::string& document, + const std::optional& id, + const std::optional& type, + const std::optional& time, + entity::ErrorList& errors) { // Parse the asset auto entity = entity::XmlParser::parse(asset::Asset::getRoot(), document, errors); @@ -132,7 +132,7 @@ namespace mtconnect::source { { LOG(warning) << "Asset could not be parsed"; LOG(warning) << document; - for (auto &e : errors) + for (auto& e : errors) LOG(warning) << e->what(); return nullptr; } @@ -175,7 +175,7 @@ namespace mtconnect::source { return asset; } - void LoopbackSource::removeAsset(const std::optional device, const std::string &id) + void LoopbackSource::removeAsset(const std::optional device, const std::string& id) { auto ac = make_shared("AssetCommand", Properties {}); ac->m_timestamp = chrono::system_clock::now(); diff --git a/src/mtconnect/source/loopback_source.hpp b/src/mtconnect/source/loopback_source.hpp index 52fba973..44f171d9 100644 --- a/src/mtconnect/source/loopback_source.hpp +++ b/src/mtconnect/source/loopback_source.hpp @@ -33,12 +33,12 @@ namespace mtconnect::source { /// @brief Create a loopback pipeline /// @param[in] context pipeline context /// @param[in] st boost asio strand - LoopbackPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand &st) + LoopbackPipeline(pipeline::PipelineContextPtr context, boost::asio::io_context::strand& st) : pipeline::Pipeline(context, st) {} /// @brief build the pipeline /// @param options configuration options - void build(const ConfigOptions &options) override; + void build(const ConfigOptions& options) override; protected: ConfigOptions m_options; @@ -53,8 +53,8 @@ namespace mtconnect::source { /// @param io boost asio strand /// @param pipelineContext pipeline context /// @param options loopback source options - LoopbackSource(const std::string &name, boost::asio::io_context::strand &io, - pipeline::PipelineContextPtr pipelineContext, const ConfigOptions &options) + LoopbackSource(const std::string& name, boost::asio::io_context::strand& io, + pipeline::PipelineContextPtr pipelineContext, const ConfigOptions& options) : Source(name, io), m_pipeline(pipelineContext, Source::m_strand) { m_pipeline.build(options); @@ -70,7 +70,7 @@ namespace mtconnect::source { return true; } void stop() override { m_pipeline.clear(); } - pipeline::Pipeline *getPipeline() override { return &m_pipeline; } + pipeline::Pipeline* getPipeline() override { return &m_pipeline; } /// @brief send an observation running it through the pipeline /// @param observation the observation @@ -99,12 +99,12 @@ namespace mtconnect::source { /// @param value simple string value /// @param timestamp optional observation timestamp /// @return the sequence number - SequenceNumber_t receive(DataItemPtr dataItem, const std::string &value, + SequenceNumber_t receive(DataItemPtr dataItem, const std::string& value, std::optional timestamp = std::nullopt); /// @brief create and send an observation with shdr through the pipeline /// @param shdr shdr pipe deliminated text /// @return the sequence number - SequenceNumber_t receive(const std::string &shdr); + SequenceNumber_t receive(const std::string& shdr); /// @brief receives a device and sends it to the sinks /// @param device the device to be received @@ -122,14 +122,14 @@ namespace mtconnect::source { /// @param time optional asset timestamp /// @param[out] errors errors if any occurred /// @return shared pointer to the asset - asset::AssetPtr receiveAsset(DevicePtr device, const std::string &document, - const std::optional &id, - const std::optional &type, - const std::optional &time, entity::ErrorList &errors); + asset::AssetPtr receiveAsset(DevicePtr device, const std::string& document, + const std::optional& id, + const std::optional& type, + const std::optional& time, entity::ErrorList& errors); /// @brief set a remove asset command through the pipeline /// @param device optional device /// @param id the asset id - void removeAsset(const std::optional device, const std::string &id); + void removeAsset(const std::optional device, const std::string& id); protected: LoopbackPipeline m_pipeline; diff --git a/src/mtconnect/source/source.cpp b/src/mtconnect/source/source.cpp index c837058e..c2e71df3 100644 --- a/src/mtconnect/source/source.cpp +++ b/src/mtconnect/source/source.cpp @@ -24,11 +24,11 @@ #include "mtconnect/logging.hpp" namespace mtconnect::source { - source::SourcePtr SourceFactory::make(const std::string &factoryName, - const std::string &sourceName, boost::asio::io_context &io, + source::SourcePtr SourceFactory::make(const std::string& factoryName, + const std::string& sourceName, boost::asio::io_context& io, std::shared_ptr context, - const ConfigOptions &options, - const boost::property_tree::ptree &block) + const ConfigOptions& options, + const boost::property_tree::ptree& block) { auto factory = m_factories.find(factoryName); if (factory != m_factories.end()) @@ -42,7 +42,7 @@ namespace mtconnect::source { return nullptr; } - std::string CreateIdentityHash(const std::string &input) + std::string CreateIdentityHash(const std::string& input) { using namespace std; diff --git a/src/mtconnect/source/source.hpp b/src/mtconnect/source/source.hpp index 47b58911..245bfc37 100644 --- a/src/mtconnect/source/source.hpp +++ b/src/mtconnect/source/source.hpp @@ -34,9 +34,9 @@ namespace mtconnect { class Source; using SourcePtr = std::shared_ptr; using SourceFactoryFn = boost::function( - const std::string &name, boost::asio::io_context &io, - std::shared_ptr pipelineContext, const ConfigOptions &options, - const boost::property_tree::ptree &block)>; + const std::string& name, boost::asio::io_context& io, + std::shared_ptr pipelineContext, const ConfigOptions& options, + const boost::property_tree::ptree& block)>; /// @brief Abstract agent data source class AGENT_LIB_API Source : public std::enable_shared_from_this @@ -44,25 +44,25 @@ namespace mtconnect { public: /// @brief Create a source with an io context /// @param io boost asio io context - Source(boost::asio::io_context &io) : m_strand(io) {} + Source(boost::asio::io_context& io) : m_strand(io) {} /// @brief Create a source with a strand /// @param io boost asio strand - Source(boost::asio::io_context::strand &io) : m_strand(io) {} + Source(boost::asio::io_context::strand& io) : m_strand(io) {} /// @brief Create a named source with an io context /// @param name source name /// @param io boost asio io context - Source(const std::string &name, boost::asio::io_context &io) : m_name(name), m_strand(io) {} + Source(const std::string& name, boost::asio::io_context& io) : m_name(name), m_strand(io) {} /// @brief Create a named source with a strand /// @param name source name /// @param io boost asio strand - Source(const std::string &name, boost::asio::io_context::strand &io) + Source(const std::string& name, boost::asio::io_context::strand& io) : m_name(name), m_strand(io) {} virtual ~Source() {} /// @brief get a shared pointer to the source /// @return shared pointer to this - SourcePtr getptr() const { return const_cast(this)->shared_from_this(); } + SourcePtr getptr() const { return const_cast(this)->shared_from_this(); } /// @brief start the source /// @return `true` if it succeeded @@ -74,22 +74,22 @@ namespace mtconnect { virtual bool isLoopback() { return false; } /// @brief get the identity of the source /// @return the identity - virtual const std::string &getIdentity() const { return m_name; } + virtual const std::string& getIdentity() const { return m_name; } /// @brief get the pipeline associated with the source /// @return pointer to the pipeline - virtual pipeline::Pipeline *getPipeline() = 0; + virtual pipeline::Pipeline* getPipeline() = 0; /// @brief get the name of the source /// @return the name - const auto &getName() const { return m_name; } + const auto& getName() const { return m_name; } /// @brief get the source's strand /// @return the asio strand - boost::asio::io_context::strand &getStrand(); + boost::asio::io_context::strand& getStrand(); /// @brief changes the options in the source /// @param[in] options the options to update - virtual void setOptions(const ConfigOptions &options) {} + virtual void setOptions(const ConfigOptions& options) {} protected: std::string m_name; @@ -99,7 +99,7 @@ namespace mtconnect { /// @brief create a unique identity hash for an XML id starting with an `_` and 10 hex digits /// @param text the text to create the hashed id /// @returns a string with the hashed result - AGENT_LIB_API std::string CreateIdentityHash(const std::string &input); + AGENT_LIB_API std::string CreateIdentityHash(const std::string& input); /// @brief A factory for creating the source class AGENT_LIB_API SourceFactory @@ -113,15 +113,15 @@ namespace mtconnect { /// @param options configuration options /// @param block additional options /// @return shared pointer to the source - SourcePtr make(const std::string &factoryName, const std::string &sourceName, - boost::asio::io_context &io, + SourcePtr make(const std::string& factoryName, const std::string& sourceName, + boost::asio::io_context& io, std::shared_ptr context, - const ConfigOptions &options, const boost::property_tree::ptree &block); + const ConfigOptions& options, const boost::property_tree::ptree& block); /// @brief Register the factory with the factory name /// @param name the name of the factory /// @param function factory function to create a source - void registerFactory(const std::string &name, SourceFactoryFn function) + void registerFactory(const std::string& name, SourceFactoryFn function) { m_factories.insert_or_assign(name, function); } @@ -131,7 +131,7 @@ namespace mtconnect { /// @brief check if a factory exists /// @param name the name of the factory /// @return `true` if the factory is registered - bool hasFactory(const std::string &name) { return m_factories.count(name) > 0; } + bool hasFactory(const std::string& name) { return m_factories.count(name) > 0; } private: std::map m_factories; diff --git a/src/mtconnect/utilities.cpp b/src/mtconnect/utilities.cpp index 3b729fa9..3371b22f 100644 --- a/src/mtconnect/utilities.cpp +++ b/src/mtconnect/utilities.cpp @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -35,31 +36,31 @@ #include #include #include -#include #include "logging.hpp" // Don't include WinSock.h when processing #ifdef _WINDOWS #define _WINSOCKAPI_ +#include #include #include -#include #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ull -#else // _WINDOWS +#else // _WINDOWS // Resource management required includes by OS #if defined(__linux__) #include + #include #include #elif defined(__APPLE__) -#include #include -#else // not __linux__ or __APPLE__ +#include +#else // not __linux__ or __APPLE__ #include -#endif // __linux__ or __APPLE__ -#endif // _WINDOWS +#endif // __linux__ or __APPLE__ +#endif // _WINDOWS using namespace std; using namespace std::chrono; @@ -88,7 +89,7 @@ BOOST_FUSION_ADAPT_STRUCT(mtconnect::url::Url, m_fragment)) namespace mtconnect { - inline string::size_type insertPrefix(string &aPath, string::size_type &aPos, + inline string::size_type insertPrefix(string& aPath, string::size_type& aPos, const string aPrefix) { aPath.insert(aPos, aPrefix); @@ -98,7 +99,7 @@ namespace mtconnect { return aPos; } - inline bool hasNamespace(const string &aPath, string::size_type aStart) + inline bool hasNamespace(const string& aPath, string::size_type aStart) { string::size_type len = aPath.length(), pos = aStart; @@ -155,7 +156,7 @@ namespace mtconnect { return newPath; } - std::string GetBestHostAddress(boost::asio::io_context &context, bool onlyV4) + std::string GetBestHostAddress(boost::asio::io_context& context, bool onlyV4) { using namespace boost; using namespace asio; @@ -173,9 +174,9 @@ namespace mtconnect { } else { - for (auto &res : results) + for (auto& res : results) { - const auto &ad = res.endpoint().address(); + const auto& ad = res.endpoint().address(); if (!ad.is_unspecified() && !ad.is_loopback() && (!onlyV4 || !ad.is_v6())) { auto ads {ad.to_string()}; @@ -289,7 +290,7 @@ namespace mtconnect { bool has_user_name = false; }; - Url Url::parse(const std::string_view &url) + Url Url::parse(const std::string_view& url) { Url ast; UriGrammar grammar; @@ -305,7 +306,7 @@ namespace mtconnect { return ast; } } // namespace url - + std::size_t openFdCount() { #if defined(_WIN32) @@ -320,7 +321,8 @@ namespace mtconnect { namespace fs = boost::filesystem; boost::system::error_code ec; fs::directory_iterator it("/proc/self/fd", ec), end; - if (ec) return 0; + if (ec) + return 0; // the iterator itself holds one fd open on the directory auto n = static_cast(std::distance(it, end)); return n ? n - 1 : 0; @@ -328,10 +330,12 @@ namespace mtconnect { #else // /proc may be absent; scan up to the soft limit. long maxfd = sysconf(_SC_OPEN_MAX); - if (maxfd < 0) maxfd = 65536; + if (maxfd < 0) + maxfd = 65536; std::size_t n = 0; for (int fd = 0; fd < maxfd; ++fd) - if (fcntl(fd, F_GETFD) != -1) ++n; + if (fcntl(fd, F_GETFD) != -1) + ++n; return n; #endif } @@ -348,8 +352,8 @@ namespace mtconnect { #elif defined(__APPLE__) mach_task_basic_info_data_t info {}; mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; - if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, - reinterpret_cast(&info), &count) != KERN_SUCCESS) + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast(&info), + &count) != KERN_SUCCESS) return 0; return static_cast(info.resident_size); @@ -357,9 +361,11 @@ namespace mtconnect { // /proc/self/statm: total resident shared text lib data dt; field 2 = resident pages std::ifstream f("/proc/self/statm"); std::size_t total = 0, resident = 0; - if (!(f >> total >> resident)) return 0; + if (!(f >> total >> resident)) + return 0; long pageSize = sysconf(_SC_PAGESIZE); - if (pageSize < 0) return 0; + if (pageSize < 0) + return 0; return resident * static_cast(pageSize); #else diff --git a/src/mtconnect/utilities.hpp b/src/mtconnect/utilities.hpp index 7d795da7..8923874c 100644 --- a/src/mtconnect/utilities.hpp +++ b/src/mtconnect/utilities.hpp @@ -30,9 +30,12 @@ #include #include +#include #include +#include #include #include +#include #include #include #include @@ -40,9 +43,6 @@ #include #include #include -#include -#include -#include #include "mtconnect/config.hpp" #include "mtconnect/logging.hpp" @@ -78,27 +78,27 @@ namespace mtconnect { public: /// @brief Create a fatal exception with a message /// @param str The message - FatalException(const std::string &str) : m_what(str) {} + FatalException(const std::string& str) : m_what(str) {} /// @brief Create a fatal exception with a message /// @param str The message - FatalException(const std::string_view &str) : m_what(str) {} + FatalException(const std::string_view& str) : m_what(str) {} /// @brief Create a fatal exception with a message /// @param str The message - FatalException(const char *str) : m_what(str) {} + FatalException(const char* str) : m_what(str) {} /// @brief Create a default fatal exception /// Has the message `Fatal Exception Occurred` FatalException() : m_what("Fatal Exception Occurred") {} /// @brief Copy construction from an exception /// @param ex the exception - FatalException(const std::exception &ex) : m_what(ex.what()) {} + FatalException(const std::exception& ex) : m_what(ex.what()) {} /// @brief Defaut construction - FatalException(const FatalException &) = default; + FatalException(const FatalException&) = default; /// @brief Default destructor ~FatalException() = default; /// @brief gets the message /// @returns the message as a string - const char *what() const noexcept override { return m_what.c_str(); } + const char* what() const noexcept override { return m_what.c_str(); } protected: std::string m_what; @@ -116,18 +116,18 @@ namespace mtconnect { /// @brief Converts string to floating point numberss /// @param[in] text the number /// @return the converted value or 0.0 if incorrect. - inline double stringToFloat(const std::string &text) + inline double stringToFloat(const std::string& text) { double value = 0.0; try { value = stof(text); } - catch (const std::out_of_range &) + catch (const std::out_of_range&) { value = 0.0; } - catch (const std::invalid_argument &) + catch (const std::invalid_argument&) { value = 0.0; } @@ -137,18 +137,18 @@ namespace mtconnect { /// @brief Converts string to integer /// @param[in] text the number /// @return the converted value or 0 if incorrect. - inline int stringToInt(const std::string &text, int outOfRangeDefault) + inline int stringToInt(const std::string& text, int outOfRangeDefault) { int value = 0; try { value = stoi(text); } - catch (const std::out_of_range &) + catch (const std::out_of_range&) { value = outOfRangeDefault; } - catch (const std::invalid_argument &) + catch (const std::invalid_argument&) { value = 0; } @@ -184,8 +184,8 @@ namespace mtconnect { /// @param[in] fmter reference to this formatter /// @return reference to the output stream template - inline friend std::basic_ostream<_CharT, _Traits> &operator<<( - std::basic_ostream<_CharT, _Traits> &os, const format_double_stream &fmter) + inline friend std::basic_ostream<_CharT, _Traits>& operator<<( + std::basic_ostream<_CharT, _Traits>& os, const format_double_stream& fmter) { constexpr int precision = std::numeric_limits::digits10; os << std::setprecision(precision) << fmter.val; @@ -201,7 +201,7 @@ namespace mtconnect { /// @brief Convert text to upper case /// @param[in,out] text text /// @return upper-case of text as string - inline std::string &toUpperCase(std::string &text) + inline std::string& toUpperCase(std::string& text) { std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return std::toupper(c); }); @@ -212,7 +212,7 @@ namespace mtconnect { /// @brief Simple check if a number as a string is negative /// @param s the numbeer /// @return `true` if positive - inline bool isNonNegativeInteger(const std::string &s) + inline bool isNonNegativeInteger(const std::string& s) { for (const char c : s) { @@ -226,7 +226,7 @@ namespace mtconnect { /// @brief Checks if a string is a valid integer /// @param s the string /// @return `true` if is `[+-]\d+` - inline bool isInteger(const std::string &s) + inline bool isInteger(const std::string& s) { auto iter = s.cbegin(); if (*iter == '-' || *iter == '+') @@ -244,7 +244,7 @@ namespace mtconnect { /// @brief Thread safe localtime function that uses localtime_s or localtime_r based on platform /// @param[in] timer pointer to time_t /// @param[out] buf pointer to tm struct to fill - inline void safe_localtime(const std::time_t *timer, std::tm *buf) + inline void safe_localtime(const std::time_t* timer, std::tm* buf) { #ifdef _WINDOWS localtime_s(buf, timer); @@ -319,7 +319,7 @@ namespace mtconnect { /// @brief Parse the given time /// @param aTime the time in text /// @return uns64 in microseconds since epoch - inline uint64_t parseTimeMicro(const std::string &aTime) + inline uint64_t parseTimeMicro(const std::string& aTime) { std::stringstream str(aTime); if (isdigit(aTime.back())) @@ -343,7 +343,7 @@ namespace mtconnect { /// @brief escaped reserved XML characters from text /// @param data text with reserved characters escaped - inline void replaceIllegalCharacters(std::string &data) + inline void replaceIllegalCharacters(std::string& data) { for (auto i = 0u; i < data.length(); i++) { @@ -402,7 +402,7 @@ namespace mtconnect { /// @brief split a string into two parts using a ':' separator /// @param key the key to split /// @return a pair of the key and an optional prefix. - static inline std::pair> splitKey(const std::string &key) + static inline std::pair> splitKey(const std::string& key) { auto c = key.find(':'); if (c != std::string::npos) @@ -415,7 +415,7 @@ namespace mtconnect { /// @param a first string /// @param b second string /// @return `true` if equal - inline bool iequals(const std::string &a, const std::string_view &b) + inline bool iequals(const std::string& a, const std::string_view& b) { if (a.size() != b.size()) return false; @@ -443,10 +443,10 @@ namespace mtconnect { class reverse { private: - T &m_iterable; + T& m_iterable; public: - explicit reverse(T &iterable) : m_iterable(iterable) {} + explicit reverse(T& iterable) : m_iterable(iterable) {} auto begin() const { return std::rbegin(m_iterable); } auto end() const { return std::rend(m_iterable); } }; @@ -478,7 +478,7 @@ namespace mtconnect { /// @param name the name to get /// @return the value of the option otherwise std::nullopt template - inline const std::optional GetOption(const ConfigOptions &options, const std::string &name) + inline const std::optional GetOption(const ConfigOptions& options, const std::string& name) { auto v = options.find(name); if (v != options.end()) @@ -491,7 +491,7 @@ namespace mtconnect { /// @param options the set of options /// @param name the name of the option /// @return `true` if the option exists and has a bool type - inline bool IsOptionSet(const ConfigOptions &options, const std::string &name) + inline bool IsOptionSet(const ConfigOptions& options, const std::string& name) { auto v = options.find(name); if (v != options.end()) @@ -504,7 +504,7 @@ namespace mtconnect { /// @param[in] options the set of options /// @param[in] name the name of the option /// @return `true` if the option exists - inline bool HasOption(const ConfigOptions &options, const std::string &name) + inline bool HasOption(const ConfigOptions& options, const std::string& name) { auto v = options.find(name); return v != options.end(); @@ -514,32 +514,32 @@ namespace mtconnect { /// @param[in] s the /// @param[in] def template for the option /// @return a typed option matching `def` - inline auto ConvertOption(const std::string &s, const ConfigOption &def, - const ConfigOptions &options) + inline auto ConvertOption(const std::string& s, const ConfigOption& def, + const ConfigOptions& options) { ConfigOption option {s}; if (std::holds_alternative(option)) { std::string sv = std::get(option); - visit(overloaded {[&option, &sv](const std::string &) { + visit(overloaded {[&option, &sv](const std::string&) { if (sv.empty()) option = std::monostate(); else option = sv; }, - [&option, &sv](const int &) { option = stoi(sv); }, - [&option, &sv](const Milliseconds &) { option = Milliseconds {stoi(sv)}; }, - [&option, &sv](const Seconds &) { option = Seconds {stoi(sv)}; }, - [&option, &sv](const double &) { option = stod(sv); }, - [&option, &sv](const bool &) { option = sv == "yes" || sv == "true"; }, - [&option, &sv](const StringList &) { + [&option, &sv](const int&) { option = stoi(sv); }, + [&option, &sv](const Milliseconds&) { option = Milliseconds {stoi(sv)}; }, + [&option, &sv](const Seconds&) { option = Seconds {stoi(sv)}; }, + [&option, &sv](const double&) { option = stod(sv); }, + [&option, &sv](const bool&) { option = sv == "yes" || sv == "true"; }, + [&option, &sv](const StringList&) { StringList list; boost::split(list, sv, boost::is_any_of(",")); - for (auto &s : list) + for (auto& s : list) boost::trim(s); option = list; }, - [](const auto &) {}}, + [](const auto&) {}}, def); } return option; @@ -556,7 +556,7 @@ namespace mtconnect { /// @param[in] name the name of the options /// @param[in] size the default size (0) /// @return the size honoring suffixes - inline int64_t ConvertFileSize(const ConfigOptions &options, const std::string &name, + inline int64_t ConvertFileSize(const ConfigOptions& options, const std::string& name, int64_t size = 0) { using namespace std; @@ -605,10 +605,10 @@ namespace mtconnect { /// @param[in] tree the property tree coming from configuration parser /// @param[in,out] options the options set /// @param[in] entries a set of typed options to check - inline void AddOptions(const boost::property_tree::ptree &tree, ConfigOptions &options, - const ConfigOptions &entries) + inline void AddOptions(const boost::property_tree::ptree& tree, ConfigOptions& options, + const ConfigOptions& entries) { - for (auto &e : entries) + for (auto& e : entries) { auto val = tree.get_optional(e.first); if (val) @@ -631,10 +631,10 @@ namespace mtconnect { /// @param[in] tree the property tree coming from configuration parser /// @param[in,out] options the option set /// @param[in] entries the options with default values - inline void AddDefaultedOptions(const boost::property_tree::ptree &tree, ConfigOptions &options, - const ConfigOptions &entries) + inline void AddDefaultedOptions(const boost::property_tree::ptree& tree, ConfigOptions& options, + const ConfigOptions& entries) { - for (auto &e : entries) + for (auto& e : entries) { auto val = tree.get_optional(e.first); if (val) @@ -658,9 +658,9 @@ namespace mtconnect { /// @brief combine two option sets /// @param[in,out] options existing set of options /// @param[in] entries options to add or update - inline void MergeOptions(ConfigOptions &options, const ConfigOptions &entries) + inline void MergeOptions(ConfigOptions& options, const ConfigOptions& entries) { - for (auto &e : entries) + for (auto& e : entries) { options.insert_or_assign(e.first, e.second); } @@ -670,10 +670,10 @@ namespace mtconnect { /// @param[in] tree the property tree coming from configuration parser /// @param[in,out] options option set to modify /// @param[in] entries a set of typed options to check - inline void GetOptions(const boost::property_tree::ptree &tree, ConfigOptions &options, - const ConfigOptions &entries) + inline void GetOptions(const boost::property_tree::ptree& tree, ConfigOptions& options, + const ConfigOptions& entries) { - for (auto &e : entries) + for (auto& e : entries) { if (!std::holds_alternative(e.second) || !std::get(e.second).empty()) @@ -689,7 +689,7 @@ namespace mtconnect { /// @brief Format a timestamp as a string in microseconds /// @param[in] ts the timestamp /// @return the time with microsecond resolution - inline std::string format(const Timestamp &ts) + inline std::string format(const Timestamp& ts) { using namespace std; string time = date::format("%FT%T", date::floor(ts)); @@ -710,7 +710,7 @@ namespace mtconnect { /// /// @param[in,out] start starting iterator /// @param[in,out] end ending iterator - inline void capitalize(std::ostringstream &camel, std::string::const_iterator start, + inline void capitalize(std::ostringstream& camel, std::string::const_iterator start, std::string::const_iterator end) { using namespace std; @@ -721,7 +721,7 @@ namespace mtconnect { {"IP", "IP"}, {"URI", "URI"}, {"MTCONNECT", "MTConnect"}}; std::string_view s(&*start, distance(start, end)); - const auto &w = exceptions.find(s); + const auto& w = exceptions.find(s); ostream_iterator out(camel); if (w != exceptions.end()) { @@ -742,7 +742,7 @@ namespace mtconnect { /// @param[in] type the words to capitalize /// @param[out] prefix the prefix of the string /// @return a pascalized upper-camel-case string - inline std::string pascalize(const std::string &type, std::optional &prefix) + inline std::string pascalize(const std::string& type, std::optional& prefix) { using namespace std; if (type.empty()) @@ -780,7 +780,7 @@ namespace mtconnect { /// @brief parse a string timestamp to a `Timestamp` /// @param timestamp[in] the timestamp as a string /// @return converted `Timestamp` - inline Timestamp parseTimestamp(const std::string ×tamp) + inline Timestamp parseTimestamp(const std::string& timestamp) { Timestamp ts; std::istringstream in(timestamp); @@ -810,7 +810,7 @@ namespace mtconnect { /// @brief convert a string version to a major and minor as two integers separated by a char. /// @param s the version - inline int32_t IntSchemaVersion(const std::string &s) + inline int32_t IntSchemaVersion(const std::string& s) { int major {0}, minor {0}; char c; @@ -829,7 +829,7 @@ namespace mtconnect { /// @brief Retrieve the best Host IP address from the network interfaces. /// @param[in] context the boost asio io_context for resolving the address /// @param[in] onlyV4 only consider IPV4 addresses if `true` - std::string GetBestHostAddress(boost::asio::io_context &context, bool onlyV4 = false); + std::string GetBestHostAddress(boost::asio::io_context& context, bool onlyV4 = false); /// @brief Function to create a unique id given a sha1 namespace and an id. /// @@ -840,8 +840,8 @@ namespace mtconnect { /// @param[in] sha the sha1 namespace to use as context /// @param[in] id the id to use transform /// @returns Returns the first 16 characters of the base 64 encoded sha1 - inline std::string makeUniqueId(const ::boost::uuids::detail::sha1 &contextSha, - const std::string &id) + inline std::string makeUniqueId(const ::boost::uuids::detail::sha1& contextSha, + const std::string& id) { using namespace std; using namespace boost::uuids::detail; @@ -858,7 +858,7 @@ namespace mtconnect { sha1::digest_type digest; sha.get_digest(digest); - auto data = (unsigned int *)digest; + auto data = (unsigned int*)digest; string s(32, ' '); auto len = boost::beast::detail::base64::encode(s.data(), data, sizeof(digest)); @@ -895,7 +895,7 @@ namespace mtconnect { std::stringstream ss; bool has_pre = false; - for (const auto &kv : *this) + for (const auto& kv : *this) { if (has_pre) ss << '&'; @@ -911,7 +911,7 @@ namespace mtconnect { /// @param query query to merge void merge(UrlQuery query) { - for (const auto &kv : query) + for (const auto& kv : query) { insert_or_assign(kv.first, kv.second); } @@ -964,8 +964,8 @@ namespace mtconnect { /// @param operation the operation (probe,sample,current, or asset) /// @param query query parameters /// @return A string with the target for a GET reuest - std::string getTarget(const std::optional &device, const std::string &operation, - const UrlQuery &query) const + std::string getTarget(const std::optional& device, const std::string& operation, + const UrlQuery& query) const { UrlQuery uq {m_query}; if (!query.empty()) @@ -1000,7 +1000,7 @@ namespace mtconnect { /// @brief Format the URL as text /// @param device optional device to add to the URL /// @return formatted URL - std::string getUrlText(const std::optional &device) const + std::string getUrlText(const std::optional& device) const { std::stringstream url; url << m_protocol << "://" << getHost() << ':' << getPort() << getTarget(); @@ -1011,20 +1011,20 @@ namespace mtconnect { /// @brief parse a string to a Url /// @return parsed URL - static Url parse(const std::string_view &url); + static Url parse(const std::string_view& url); }; /// @brief output operator for URL /// @param os the output stream /// @param url the URL to output - inline std::ostream &operator<<(std::ostream &os, const Url &url) + inline std::ostream& operator<<(std::ostream& os, const Url& url) { os << url.getUrlText(std::nullopt); return os; } } // namespace url - + /// @brief Current number of open file descriptors (handles on Windows) for this process std::size_t openFdCount(); @@ -1058,42 +1058,57 @@ namespace mtconnect { {} // call on a timer (e.g. every 10–30s) - struct Report { std::size_t m_current, m_highWater; double m_slope; bool m_suspect; }; + struct Report + { + std::size_t m_current, m_highWater; + double m_slope; + bool m_suspect; + }; - Report sample() { + Report sample() + { std::size_t n = m_sampler(); m_highWater = std::max(m_highWater, n); m_samples.push_back(n); - if (m_samples.size() > m_window) m_samples.pop_front(); + if (m_samples.size() > m_window) + m_samples.pop_front(); double s = slope(); // suspect if steadily rising AND at a new high across the whole window double threshold = std::max(m_absThreshold, m_relThreshold * mean()); - bool suspect = m_samples.size() == m_window - && s > threshold - && m_samples.back() == m_highWater; - return { n, m_highWater, s, suspect }; + bool suspect = + m_samples.size() == m_window && s > threshold && m_samples.back() == m_highWater; + return {n, m_highWater, s, suspect}; } private: - double mean() const { - if (m_samples.empty()) return 0.0; + double mean() const + { + if (m_samples.empty()) + return 0.0; double sum = 0.0; - for (auto v : m_samples) sum += double(v); + for (auto v : m_samples) + sum += double(v); return sum / double(m_samples.size()); } - double slope() const { // least-squares over the window + double slope() const + { // least-squares over the window std::size_t m = m_samples.size(); - if (m < 2) return 0.0; - double sx=0, sy=0, sxy=0, sxx=0; - for (std::size_t i = 0; i < m; ++i) { + if (m < 2) + return 0.0; + double sx = 0, sy = 0, sxy = 0, sxx = 0; + for (std::size_t i = 0; i < m; ++i) + { double x = double(i), y = double(m_samples[i]); - sx+=x; sy+=y; sxy+=x*y; sxx+=x*x; + sx += x; + sy += y; + sxy += x * y; + sxx += x * x; } - double d = m*sxx - sx*sx; - return d == 0.0 ? 0.0 : (m*sxy - sx*sy) / d; + double d = m * sxx - sx * sx; + return d == 0.0 ? 0.0 : (m * sxy - sx * sy) / d; } Sampler m_sampler; diff --git a/src/mtconnect/validation/observations.hpp b/src/mtconnect/validation/observations.hpp index 6f614f64..4de56614 100644 --- a/src/mtconnect/validation/observations.hpp +++ b/src/mtconnect/validation/observations.hpp @@ -45,5 +45,5 @@ namespace mtconnect { /// * SCHEMA_VERSION if deprecated extern Validation ControlledVocabularies; } // namespace observations - } // namespace validation + } // namespace validation } // namespace mtconnect diff --git a/test_package/adapter_test.cpp b/test_package/adapter_test.cpp index de01ef4f..7c3702c9 100644 --- a/test_package/adapter_test.cpp +++ b/test_package/adapter_test.cpp @@ -42,7 +42,7 @@ namespace asio = boost::asio; using namespace std::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -60,7 +60,7 @@ TEST(AdapterTest, should_handle_multiline_data) auto handler = make_unique(); string data; - handler->m_processData = [&](const string &d, const string &s) { data = d; }; + handler->m_processData = [&](const string& d, const string& s) { data = d; }; adapter->setHandler(handler); adapter->processData("Simple Pass Through"); @@ -92,7 +92,7 @@ TEST(AdapterTest, should_forward_multiline_command) auto handler = make_unique(); string command, value; - handler->m_command = [&](const string &c, const string &v, const string &s) { + handler->m_command = [&](const string& c, const string& v, const string& s) { command = c; value = v; }; @@ -143,7 +143,7 @@ TEST(AdapterTest, should_set_heartbeat_override_from_configuration) pipeline::PipelineContextPtr context = make_shared(); auto adapter = make_unique(ioc, context, options, tree); - const auto &over = adapter->getHeartbeatOverride(); + const auto& over = adapter->getHeartbeatOverride(); ASSERT_TRUE(over); ASSERT_EQ(123ms, *over); } diff --git a/test_package/agent_adapter_test.cpp b/test_package/agent_adapter_test.cpp index 72e87518..fc75ce2d 100644 --- a/test_package/agent_adapter_test.cpp +++ b/test_package/agent_adapter_test.cpp @@ -52,7 +52,7 @@ using status = boost::beast::http::status; namespace asio = boost::asio; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -60,13 +60,13 @@ int main(int argc, char *argv[]) struct MockPipelineContract : public PipelineContract { - MockPipelineContract(DevicePtr &device) : m_device(device) {} - DevicePtr findDevice(const std::string &device) override + MockPipelineContract(DevicePtr& device) : m_device(device) {} + DevicePtr findDevice(const std::string& device) override { m_deviceName = device; return m_device; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_device->getDeviceDataItem(name); } @@ -81,9 +81,9 @@ struct MockPipelineContract : public PipelineContract int32_t getSchemaVersion() const override { return IntDefaultSchemaVersion(); } void deliverAssetCommand(entity::EntityPtr) override {} void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &dev, bool flag) override {} - void sourceFailed(const std::string &id) override { m_failed = true; } - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList& dev, bool flag) override {} + void sourceFailed(const std::string& id) override { m_failed = true; } + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } bool isValidating() const override { return false; } bool m_failed = false; @@ -187,7 +187,7 @@ TEST_F(AgentAdapterTest, should_connect_to_agent) bool connecting = false; bool connected = false; ResponseDocument data; - handler->m_processData = [&](const string &d, const string &s) {}; + handler->m_processData = [&](const string& d, const string& s) {}; handler->m_connecting = [&](const string id) { connecting = true; }; handler->m_connected = [&](const string id) { connected = true; }; @@ -228,7 +228,7 @@ TEST_F(AgentAdapterTest, should_get_current_from_agent) unique_ptr handler = make_unique(); bool current = false; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { if (d.find("MTConnectStreams") != string::npos) current = true; }; @@ -265,7 +265,7 @@ TEST_F(AgentAdapterTest, should_get_assets_from_agent) unique_ptr handler = make_unique(); bool assets = false; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { if (d.find("MTConnectAssets") != string::npos) assets = true; }; @@ -305,7 +305,7 @@ TEST_F(AgentAdapterTest, should_receive_sample) int rc = 0; ResponseDocument rd; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { ResponseDocument::parse(d, rd, m_context); rc++; @@ -363,7 +363,7 @@ TEST_F(AgentAdapterTest, should_reconnect) int rc = 0; ResponseDocument rd; bool response = false; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { response = true; ResponseDocument::parse(d, rd, m_context); @@ -431,7 +431,7 @@ TEST_F(AgentAdapterTest, should_reset_request_from_sequence_on_recovery) int rc = 0; ResponseDocument rd; bool response = false; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { response = true; ResponseDocument::parse(d, rd, m_context); @@ -530,13 +530,13 @@ TEST_F(AgentAdapterTest, should_resync_with_current_when_instance_id_changes_on_ // than resuming a `sample` from the now-stale sequence. vector> requests; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { rd.m_next = 0; rd.m_instanceId = 0; ResponseDocument::parse(d, rd, m_context); rc++; - if (auto &req = adapter->getStreamRequest()) + if (auto& req = adapter->getStreamRequest()) { string from; auto f = req->m_query.find("from"); @@ -656,7 +656,7 @@ TEST_F(AgentAdapterTest, should_connect_with_http_10_agent) int rc = 0; ResponseDocument rd; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { ResponseDocument::parse(d, rd, m_context); rc++; @@ -716,7 +716,7 @@ TEST_F(AgentAdapterTest, should_check_instance_id_on_recovery) bool recovering = false; bool response = false; ResponseDocument rd; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { rd.m_next = 0; rd.m_instanceId = 0; ResponseDocument::parse(d, rd, m_context); @@ -812,7 +812,7 @@ TEST_F(AgentAdapterTest, should_map_device_name_and_uuid) } }); - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); while (contract->m_observations.size() == 0) { @@ -836,7 +836,7 @@ TEST_F(AgentAdapterTest, should_use_polling_when_option_is_set) int rc = 0; ResponseDocument rd; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { ResponseDocument::parse(d, rd, m_context); rc++; @@ -919,7 +919,7 @@ TEST_F(AgentAdapterTest, should_connect_to_tls_agent) unique_ptr handler = make_unique(); bool current = false; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { if (d.find("MTConnectStreams") != string::npos) current = true; }; @@ -959,7 +959,7 @@ TEST_F(AgentAdapterTest, should_create_device_when_option_supplied) int rc = 0; ResponseDocument rd; - handler->m_processData = [&](const string &d, const string &s) { + handler->m_processData = [&](const string& d, const string& s) { ResponseDocument::parse(d, rd, m_context); rc++; diff --git a/test_package/agent_asset_test.cpp b/test_package/agent_asset_test.cpp index 87552fe3..057206c6 100644 --- a/test_package/agent_asset_test.cpp +++ b/test_package/agent_asset_test.cpp @@ -52,7 +52,7 @@ using namespace mtconnect::observation; using status = boost::beast::http::status; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -168,7 +168,7 @@ TEST_F(AgentAssetTest, should_handle_asset_buffer_and_buffer_limits) queries["device"] = "000"; queries["type"] = "FakeAsset"; - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); ASSERT_EQ((unsigned int)4, storage->getMaxAssets()); ASSERT_EQ((unsigned int)0, storage->getCount()); @@ -380,7 +380,7 @@ TEST_F(AgentAssetTest, should_handle_asset_from_adapter_on_one_line) { addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); m_agentTestHelper->m_adapter->processData( "2021-02-01T12:00:00Z|@ASSET@|P1|FakeAsset|TEST 1"); @@ -398,7 +398,7 @@ TEST_F(AgentAssetTest, should_handle_multiline_asset) { addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); m_agentTestHelper->m_adapter->parseBuffer( "2021-02-01T12:00:00Z|@ASSET@|P1|FakeAsset|--multiline--AAAA\n"); @@ -435,7 +435,7 @@ TEST_F(AgentAssetTest, should_handle_multiline_asset) TEST_F(AgentAssetTest, should_handle_bad_asset_from_adapter) { addAdapter(); - const auto &storage = m_agentTestHelper->m_agent->getAssetStorage(); + const auto& storage = m_agentTestHelper->m_agent->getAssetStorage(); m_agentTestHelper->m_adapter->parseBuffer( "2021-02-01T12:00:00Z|@ASSET@|111|CuttingTool|--multiline--AAAA\n"); @@ -452,7 +452,7 @@ TEST_F(AgentAssetTest, should_handle_asset_removal_from_REST_api) query["device"] = "LinuxCNC"; query["type"] = "FakeAsset"; - const auto &storage = m_agentTestHelper->m_agent->getAssetStorage(); + const auto& storage = m_agentTestHelper->m_agent->getAssetStorage(); ASSERT_EQ((unsigned int)4, storage->getMaxAssets()); ASSERT_EQ((unsigned int)0, storage->getCount()); @@ -543,7 +543,7 @@ TEST_F(AgentAssetTest, should_handle_asset_removal_from_adapter) addAdapter(); QueryMap query; auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); ASSERT_EQ((unsigned int)4, storage->getMaxAssets()); @@ -647,7 +647,7 @@ TEST_F(AgentAssetTest, asset_id_is_zero_padded_when_prepend_id_prefix_is_used) { addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); m_agentTestHelper->m_adapter->processData( "2021-02-01T12:00:00Z|@ASSET@|@1|FakeAsset|TEST 1"); @@ -666,7 +666,7 @@ TEST_F(AgentAssetTest, should_remove_changed_asset) { addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); ASSERT_EQ((unsigned int)4, storage->getMaxAssets()); @@ -698,7 +698,7 @@ TEST_F(AgentAssetTest, should_remove_changed_observation_asset_in_2_6) addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); ASSERT_EQ((unsigned int)4, storage->getMaxAssets()); @@ -732,7 +732,7 @@ TEST_F(AgentAssetTest, should_remove_added_asset_observation_in_2_6) addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); ASSERT_EQ((unsigned int)4, storage->getMaxAssets()); @@ -762,7 +762,7 @@ TEST_F(AgentAssetTest, should_remove_asset_using_http_delete) { auto agent = m_agentTestHelper->createAgent("/samples/test_config.xml", 8, 4, "1.3", 4, true); addAdapter(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); ASSERT_EQ((unsigned int)4, storage->getMaxAssets()); @@ -815,7 +815,7 @@ TEST_F(AgentAssetTest, should_remove_all_assets) { addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); ASSERT_EQ((unsigned int)4, storage->getMaxAssets()); @@ -873,7 +873,7 @@ TEST_F(AgentAssetTest, probe_should_have_the_asset_counts) auto agent = m_agentTestHelper->createAgent("/samples/test_config.xml", 8, 4, "1.3", 4, true); string body = "TEST 1"; QueryMap queries; - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); queries["device"] = "LinuxCNC"; queries["type"] = "FakeAsset"; @@ -1037,7 +1037,7 @@ TEST_F(AgentAssetTest, asset_count_is_absent_from_probe_header_in_schema_2_0) string body = "TEST 1"; QueryMap queries; - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); queries["device"] = "LinuxCNC"; queries["type"] = "FakeAsset"; @@ -1063,7 +1063,7 @@ TEST_F(AgentAssetTest, asset_count_tracks_additions_and_removals_per_type) string body1 = "TEST 1"; QueryMap queries; - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); queries["device"] = "LinuxCNC"; queries["type"] = "FakeAsset"; @@ -1121,7 +1121,7 @@ TEST_F(AgentAssetTest, assets_endpoint_accepts_post_requests_for_asset_storage) string body = "TEST 1"; QueryMap queries; - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); { PARSE_XML_RESPONSE_PUT("/assets", body, queries); diff --git a/test_package/agent_device_test.cpp b/test_package/agent_device_test.cpp index 509fb79c..765c21ff 100644 --- a/test_package/agent_device_test.cpp +++ b/test_package/agent_device_test.cpp @@ -45,7 +45,7 @@ namespace sys = boost::system; namespace config = mtconnect::configuration; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -159,7 +159,7 @@ TEST_F(AgentDeviceTest, should_have_device_added_in_buffer) { auto agent = m_agentTestHelper->getAgent(); auto device = agent->findDeviceByUUIDorName("000"); - auto &circ = agent->getCircularBuffer(); + auto& circ = agent->getCircularBuffer(); ASSERT_TRUE(device); auto uuid = *device->getUuid(); ASSERT_EQ("000", uuid); diff --git a/test_package/agent_test.cpp b/test_package/agent_test.cpp index f57d8349..87c28f6c 100644 --- a/test_package/agent_test.cpp +++ b/test_package/agent_test.cpp @@ -52,7 +52,7 @@ using namespace mtconnect::observation; using status = boost::beast::http::status; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -334,7 +334,7 @@ TEST_F(AgentTest, should_handle_current_at) addAdapter(); // Get the current position - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); char line[80] = {0}; @@ -405,7 +405,7 @@ TEST_F(AgentTest, should_handle_64_bit_current_at) char line[80] = {0}; // Initialize the sliding buffer at a very large number. - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); uint64_t start = (((uint64_t)1) << 48) + 1317; circ.setSequence(start); @@ -443,7 +443,7 @@ TEST_F(AgentTest, should_report_out_of_range_for_current_at) m_agentTestHelper->m_adapter->processData(line); } - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); { @@ -484,7 +484,7 @@ TEST_F(AgentTest, should_report_2_6_out_of_range_for_current_at) m_agentTestHelper->m_adapter->processData(line); } - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); auto max = seq - 1; { @@ -607,7 +607,7 @@ TEST_F(AgentTest, should_include_composition_ids_in_observations) TEST_F(AgentTest, should_report_an_error_when_the_count_is_out_of_range) { - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); int size = circ.getBufferSize() + 1; { QueryMap query {{"count", "NON_INTEGER"}}; @@ -667,7 +667,7 @@ TEST_F(AgentTest, should_report_a_2_6_error_when_the_count_is_out_of_range) m_agentTestHelper->createAgent("/samples/test_config.xml", 8, 4, "2.6", 4, false, true, {{configuration::Validation, false}}); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); int size = circ.getBufferSize() + 1; { QueryMap query {{"count", "NON_INTEGER"}}; @@ -811,7 +811,7 @@ TEST_F(AgentTest, should_get_samples_using_next_sequence) m_agentTestHelper->m_adapter->processData(line); } - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); { query["from"] = to_string(seq); @@ -824,7 +824,7 @@ TEST_F(AgentTest, should_give_correct_number_of_samples_with_count) { QueryMap query; addAdapter(); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); // Get the current position @@ -871,7 +871,7 @@ TEST_F(AgentTest, should_give_correct_number_of_samples_with_negative_count) m_agentTestHelper->m_adapter->processData(line); } - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence() - 20; { @@ -907,7 +907,7 @@ TEST_F(AgentTest, should_give_correct_number_of_samples_with_to_parameter) m_agentTestHelper->m_adapter->processData(line); } - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence() - 20; { @@ -970,7 +970,7 @@ TEST_F(AgentTest, should_give_empty_stream_with_no_new_samples) } { - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); QueryMap query {{"from", to_string(circ.getSequence())}}; PARSE_XML_RESPONSE_QUERY("/sample", query); ASSERT_XML_PATH_EQUAL(doc, "//m:Streams", nullptr); @@ -984,7 +984,7 @@ TEST_F(AgentTest, should_not_leak_observations_when_added_to_buffer) string device("LinuxCNC"), key("badKey"), value("ON"); SequenceNumber_t seqNum {0}; - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto event1 = circ.getFromBuffer(seqNum); ASSERT_FALSE(event1); @@ -1020,7 +1020,7 @@ TEST_F(AgentTest, should_int_64_sequences_should_not_truncate_at_32_bits) addAdapter(); // Set the sequence number near MAX_UINT32 - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); circ.setSequence(0xFFFFFFA0); SequenceNumber_t seq = circ.getSequence(); ASSERT_EQ((int64_t)0xFFFFFFA0, seq); @@ -1294,7 +1294,7 @@ TEST_F(AgentTest, should_support_dynamic_calibration_data) ASSERT_TRUE(di); // TODO: Fix conversions - auto &conv1 = di->getConverter(); + auto& conv1 = di->getConverter(); ASSERT_TRUE(conv1); ASSERT_EQ(0.01, conv1->factor()); ASSERT_EQ(200.0, conv1->offset()); @@ -1302,7 +1302,7 @@ TEST_F(AgentTest, should_support_dynamic_calibration_data) di = agent->getDataItemForDevice("LinuxCNC", "Zact"); ASSERT_TRUE(di); - auto &conv2 = di->getConverter(); + auto& conv2 = di->getConverter(); ASSERT_TRUE(conv2); ASSERT_EQ(0.02, conv2->factor()); ASSERT_EQ(300.0, conv2->offset()); @@ -1960,7 +1960,7 @@ TEST_F(AgentTest, adapter_should_receive_commands) ASSERT_XML_PATH_EQUAL(doc, "//m:Device@uuid", "MK-1234"); } - auto &options = m_agentTestHelper->m_adapter->getOptions(); + auto& options = m_agentTestHelper->m_adapter->getOptions(); ASSERT_EQ("MK-1234", *GetOption(options, configuration::Device)); } @@ -2102,7 +2102,7 @@ TEST_F(AgentTest, should_handle_uuid_change) ASSERT_XML_PATH_EQUAL(doc, "//m:Description@station", "YYYY"); } - auto *pipe = static_cast(m_agentTestHelper->m_adapter->getPipeline()); + auto* pipe = static_cast(m_agentTestHelper->m_adapter->getPipeline()); ASSERT_EQ("MK-1234", pipe->getDevice()); @@ -2230,7 +2230,7 @@ TEST_F(AgentTest, should_stream_data_with_interval) addAdapter(); auto heartbeatFreq {200ms}; auto rest = m_agentTestHelper->getRestService(); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); rest->start(); // Start a thread... @@ -2292,7 +2292,7 @@ TEST_F(AgentTest, should_signal_observer_when_observations_arrive) auto rest = m_agentTestHelper->getRestService(); rest->start(); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); /// - Set up streaming every 100ms with a 1000ms heartbeat std::map query; @@ -2326,7 +2326,7 @@ TEST_F(AgentTest, should_fail_if_from_is_out_of_range) auto rest = m_agentTestHelper->getRestService(); rest->start(); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); // Start a thread... std::map query; @@ -2418,8 +2418,8 @@ TEST_F(AgentTest, asset_count_data_item_is_added_to_probe_in_schema_2_0) TEST_F(AgentTest, pre_start_hook_should_be_called) { bool called = false; - Agent::Hook lambda = [&](Agent &agent) { called = true; }; - AgentTestHelper::Hook helperHook = [&](AgentTestHelper &helper) { + Agent::Hook lambda = [&](Agent& agent) { called = true; }; + AgentTestHelper::Hook helperHook = [&](AgentTestHelper& helper) { helper.getAgent()->beforeStartHooks().add(lambda); }; m_agentTestHelper->setAgentCreateHook(helperHook); @@ -2434,8 +2434,8 @@ TEST_F(AgentTest, pre_start_hook_should_be_called) TEST_F(AgentTest, pre_initialize_hooks_should_be_called) { bool called = false; - Agent::Hook lambda = [&](Agent &agent) { called = true; }; - AgentTestHelper::Hook helperHook = [&](AgentTestHelper &helper) { + Agent::Hook lambda = [&](Agent& agent) { called = true; }; + AgentTestHelper::Hook helperHook = [&](AgentTestHelper& helper) { helper.getAgent()->beforeInitializeHooks().add(lambda); }; m_agentTestHelper->setAgentCreateHook(helperHook); @@ -2447,8 +2447,8 @@ TEST_F(AgentTest, pre_initialize_hooks_should_be_called) TEST_F(AgentTest, post_initialize_hooks_should_be_called) { bool called = false; - Agent::Hook lambda = [&](Agent &agent) { called = true; }; - AgentTestHelper::Hook helperHook = [&](AgentTestHelper &helper) { + Agent::Hook lambda = [&](Agent& agent) { called = true; }; + AgentTestHelper::Hook helperHook = [&](AgentTestHelper& helper) { helper.getAgent()->afterInitializeHooks().add(lambda); }; m_agentTestHelper->setAgentCreateHook(helperHook); @@ -2460,8 +2460,8 @@ TEST_F(AgentTest, post_initialize_hooks_should_be_called) TEST_F(AgentTest, pre_stop_hook_should_be_called) { static bool called = false; - Agent::Hook lambda = [&](Agent &agent) { called = true; }; - AgentTestHelper::Hook helperHook = [&lambda](AgentTestHelper &helper) { + Agent::Hook lambda = [&](Agent& agent) { called = true; }; + AgentTestHelper::Hook helperHook = [&lambda](AgentTestHelper& helper) { helper.getAgent()->beforeStopHooks().add(lambda); }; m_agentTestHelper->setAgentCreateHook(helperHook); @@ -2651,7 +2651,7 @@ TEST_F(AgentTest, should_handle_japanese_characters) PARSE_JSON_RESPONSE("/current"); json streams = doc.at("/MTConnectStreams/Streams/DeviceStream/0/ComponentStream"_json_pointer); ASSERT_TRUE(streams.is_array()); - auto controller = std::find_if(streams.begin(), streams.end(), [](const nlohmann::json &comp) { + auto controller = std::find_if(streams.begin(), streams.end(), [](const nlohmann::json& comp) { return comp.at("/component"_json_pointer).get() == "Controller"; }); ASSERT_NE(streams.end(), controller); @@ -2810,7 +2810,7 @@ TEST_F(AgentTest, should_add_local_locations_when_files_are_given) /// by name, and returns null for an unknown name TEST_F(AgentTest, get_device_by_name_const_resolves_default_known_and_unknown) { - const Agent &agent = *m_agentTestHelper->getAgent(); + const Agent& agent = *m_agentTestHelper->getAgent(); // Empty name returns the default device auto def = agent.getDeviceByName(""); diff --git a/test_package/agent_test_helper.cpp b/test_package/agent_test_helper.cpp index 5a417dfc..f46a7524 100644 --- a/test_package/agent_test_helper.cpp +++ b/test_package/agent_test_helper.cpp @@ -34,10 +34,10 @@ using namespace mtconnect::sink::rest_sink; namespace beast = boost::beast; namespace http = beast::http; -void AgentTestHelper::makeRequest(const char *file, int line, boost::beast::http::verb verb, - const std::string &body, - const mtconnect::sink::rest_sink::QueryMap &aQueries, - const char *path, const char *accepts) +void AgentTestHelper::makeRequest(const char* file, int line, boost::beast::http::verb verb, + const std::string& body, + const mtconnect::sink::rest_sink::QueryMap& aQueries, + const char* path, const char* accepts) { m_request = make_shared(); @@ -57,70 +57,70 @@ void AgentTestHelper::makeRequest(const char *file, int line, boost::beast::http m_dispatched = m_restService->getServer()->dispatch(m_session, m_request); } -void AgentTestHelper::responseHelper(const char *file, int line, const QueryMap &aQueries, - xmlDocPtr *doc, const char *path, const char *accepts) +void AgentTestHelper::responseHelper(const char* file, int line, const QueryMap& aQueries, + xmlDocPtr* doc, const char* path, const char* accepts) { makeRequest(file, line, http::verb::get, "", aQueries, path, accepts); *doc = xmlParseMemory(m_session->m_body.c_str(), int32_t(m_session->m_body.size())); } -void AgentTestHelper::responseStreamHelper(const char *file, int line, const QueryMap &aQueries, - const char *path, const char *accepts) +void AgentTestHelper::responseStreamHelper(const char* file, int line, const QueryMap& aQueries, + const char* path, const char* accepts) { makeRequest(file, line, http::verb::get, "", aQueries, path, accepts); } -void AgentTestHelper::putResponseHelper(const char *file, int line, const string &body, - const QueryMap &aQueries, xmlDocPtr *doc, const char *path, - const char *accepts) +void AgentTestHelper::putResponseHelper(const char* file, int line, const string& body, + const QueryMap& aQueries, xmlDocPtr* doc, const char* path, + const char* accepts) { makeRequest(file, line, http::verb::put, body, aQueries, path, accepts); if (m_session->m_mimeType.ends_with("xml"sv)) *doc = xmlParseMemory(m_session->m_body.c_str(), int32_t(m_session->m_body.size())); } -void AgentTestHelper::deleteResponseHelper(const char *file, int line, const QueryMap &aQueries, - xmlDocPtr *doc, const char *path, const char *accepts) +void AgentTestHelper::deleteResponseHelper(const char* file, int line, const QueryMap& aQueries, + xmlDocPtr* doc, const char* path, const char* accepts) { makeRequest(file, line, http::verb::delete_, "", aQueries, path, accepts); if (m_session->m_mimeType.ends_with("xml"sv)) *doc = xmlParseMemory(m_session->m_body.c_str(), int32_t(m_session->m_body.size())); } -void AgentTestHelper::chunkStreamHelper(const char *file, int line, xmlDocPtr *doc) +void AgentTestHelper::chunkStreamHelper(const char* file, int line, xmlDocPtr* doc) { *doc = xmlParseMemory(m_session->m_chunkBody.c_str(), int32_t(m_session->m_chunkBody.size())); } -void AgentTestHelper::responseHelper(const char *file, int line, const QueryMap &aQueries, - nlohmann::json &doc, const char *path, const char *accepts) +void AgentTestHelper::responseHelper(const char* file, int line, const QueryMap& aQueries, + nlohmann::json& doc, const char* path, const char* accepts) { makeRequest(file, line, http::verb::get, "", aQueries, path, accepts); doc = nlohmann::json::parse(m_session->m_body); } -void AgentTestHelper::makeWebSocketRequest(const char *file, int line, const std::string &json, - xmlDocPtr *doc, std::string &id) +void AgentTestHelper::makeWebSocketRequest(const char* file, int line, const std::string& json, + xmlDocPtr* doc, std::string& id) { m_dispatched = m_websocketSession->dispatch(json, id); parseResponse(file, line, doc, id); } -void AgentTestHelper::makeWebSocketRequest(const char *file, int line, const std::string &json, - nlohmann::json &doc, std::string &id) +void AgentTestHelper::makeWebSocketRequest(const char* file, int line, const std::string& json, + nlohmann::json& doc, std::string& id) { m_dispatched = m_websocketSession->dispatch(json, id); parseResponse(file, line, doc, id); } -void AgentTestHelper::makeAsyncWebSocketRequest(const char *file, int line, const std::string &json, - std::string &id) +void AgentTestHelper::makeAsyncWebSocketRequest(const char* file, int line, const std::string& json, + std::string& id) { m_dispatched = m_websocketSession->dispatch(json, id); } -void AgentTestHelper::parseResponse(const char *file, int line, xmlDocPtr *doc, - const std::string &id) +void AgentTestHelper::parseResponse(const char* file, int line, xmlDocPtr* doc, + const std::string& id) { auto response = m_websocketSession->getNextResponse(id); ASSERT_TRUE(response) << "No response for id " << id; @@ -130,8 +130,8 @@ void AgentTestHelper::parseResponse(const char *file, int line, xmlDocPtr *doc, } } -void AgentTestHelper::parseResponse(const char *file, int line, nlohmann::json &doc, - const std::string &id) +void AgentTestHelper::parseResponse(const char* file, int line, nlohmann::json& doc, + const std::string& id) { auto response = m_websocketSession->getNextResponse(id); ASSERT_TRUE(response) << "No response for id " << id; diff --git a/test_package/agent_test_helper.hpp b/test_package/agent_test_helper.hpp index c4da7dad..063f7bc1 100644 --- a/test_package/agent_test_helper.hpp +++ b/test_package/agent_test_helper.hpp @@ -59,7 +59,7 @@ namespace mtconnect { } void run() override {} - void writeResponse(ResponsePtr &&response, Complete complete = nullptr) override + void writeResponse(ResponsePtr&& response, Complete complete = nullptr) override { m_code = response->m_status; if (response->m_file) @@ -70,7 +70,7 @@ namespace mtconnect { if (complete) complete(); } - void writeFailureResponse(ResponsePtr &&response, Complete complete = nullptr) override + void writeFailureResponse(ResponsePtr&& response, Complete complete = nullptr) override { if (m_streaming) { @@ -81,14 +81,14 @@ namespace mtconnect { writeResponse(std::move(response), complete); } } - void beginStreaming(const std::string &mimeType, Complete complete, + void beginStreaming(const std::string& mimeType, Complete complete, std::optional requestId = std::nullopt) override { m_mimeType = mimeType; m_streaming = true; complete(); } - void writeChunk(const std::string &chunk, Complete complete, + void writeChunk(const std::string& chunk, Complete complete, std::optional requestId = std::nullopt) override { m_chunkBody = chunk; @@ -115,7 +115,7 @@ namespace mtconnect { public: using super = WebsocketSession; - TestWebsocketSession(boost::asio::executor &&exec, RequestPtr &&request, Dispatch dispatch, + TestWebsocketSession(boost::asio::executor&& exec, RequestPtr&& request, Dispatch dispatch, ErrorFunction func) : WebsocketSession(std::move(request), dispatch, func), m_executor(std::move(exec)) { @@ -129,7 +129,7 @@ namespace mtconnect { void run() override {} - void read(const std::string &json) + void read(const std::string& json) { if (!m_requestManager.dispatch(shared_ptr(), json)) { @@ -141,14 +141,14 @@ namespace mtconnect { bool isStreamOpen() { return m_isOpen; } - void sent(beast::error_code ec, std::size_t len, const std::string &id) + void sent(beast::error_code ec, std::size_t len, const std::string& id) { NAMED_SCOPE("WebsocketSession::sent"); super::sent(ec, len, id); m_responsesSent[id]++; } - void asyncSend(WebsocketRequestManager::WebsocketRequest *request) + void asyncSend(WebsocketRequestManager::WebsocketRequest* request) { auto buffer = beast::buffers_to_string(request->m_streamBuffer->data()); @@ -159,20 +159,20 @@ namespace mtconnect { 0, request->m_requestId)); } - auto &getExecutor() { return m_executor; } + auto& getExecutor() { return m_executor; } - bool dispatch(const std::string &buffer, std::string &id) + bool dispatch(const std::string& buffer, std::string& id) { return m_requestManager.dispatch(shared_ptr(), buffer, &id); } - bool hasResponse(const std::string &id) const + bool hasResponse(const std::string& id) const { const auto q = m_responses.find(id); return q != m_responses.end() && !q->second.empty(); } - std::optional getNextResponse(const std::string &id) + std::optional getNextResponse(const std::string& id) { auto q = m_responses.find(id); if (q != m_responses.end() && !q->second.empty()) @@ -196,7 +196,7 @@ namespace mtconnect { boost::asio::executor m_executor; }; } // namespace rest_sink - } // namespace sink + } // namespace sink } // namespace mtconnect namespace mhttp = mtconnect::sink::rest_sink; @@ -206,7 +206,7 @@ namespace observe = mtconnect::observation; class AgentTestHelper { public: - using Hook = std::function; + using Hook = std::function; AgentTestHelper() : m_incomingIp("127.0.0.1"), m_strand(m_ioContext), m_socket(m_ioContext) {} @@ -225,7 +225,7 @@ class AgentTestHelper auto session() { return m_session; } auto websocketSession() { return m_websocketSession; } - void setAgentCreateHook(Hook &hook) { m_agentCreateHook = hook; } + void setAgentCreateHook(Hook& hook) { m_agentCreateHook = hook; } /// @brief Helper to get a response from the agent /// @param file The source file the request is made from @@ -234,9 +234,9 @@ class AgentTestHelper /// @param doc The returned document /// @param path The request path /// @param accepts The accepted mime type - void responseHelper(const char *file, int line, - const mtconnect::sink::rest_sink::QueryMap &aQueries, xmlDocPtr *doc, - const char *path, const char *accepts = "text/xml"); + void responseHelper(const char* file, int line, + const mtconnect::sink::rest_sink::QueryMap& aQueries, xmlDocPtr* doc, + const char* path, const char* accepts = "text/xml"); /// @brief Helper to get a streaming response from the agent /// @param file The source file the request is made from @@ -244,9 +244,9 @@ class AgentTestHelper /// @param aQueries The query parameters /// @param path The request path /// @param accepts The accepted mime type - void responseStreamHelper(const char *file, int line, - const mtconnect::sink::rest_sink::QueryMap &aQueries, const char *path, - const char *accepts = "text/xml"); + void responseStreamHelper(const char* file, int line, + const mtconnect::sink::rest_sink::QueryMap& aQueries, const char* path, + const char* accepts = "text/xml"); /// @brief Helper to get a json response from the agent /// @param file The source file the request is made from @@ -255,9 +255,9 @@ class AgentTestHelper /// @param doc The returned document /// @param path The request path /// @param accepts The accepted mime type - void responseHelper(const char *file, int line, - const mtconnect::sink::rest_sink::QueryMap &aQueries, nlohmann::json &doc, - const char *path, const char *accepts = "application/json"); + void responseHelper(const char* file, int line, + const mtconnect::sink::rest_sink::QueryMap& aQueries, nlohmann::json& doc, + const char* path, const char* accepts = "application/json"); /// @brief Helper to make a PUT request to the agent /// @param file The source file the request is made from @@ -267,9 +267,9 @@ class AgentTestHelper /// @param doc The returned document /// @param path The request path /// @param accepts The accepted mime type - void putResponseHelper(const char *file, int line, const std::string &body, - const mtconnect::sink::rest_sink::QueryMap &aQueries, xmlDocPtr *doc, - const char *path, const char *accepts = "text/xml"); + void putResponseHelper(const char* file, int line, const std::string& body, + const mtconnect::sink::rest_sink::QueryMap& aQueries, xmlDocPtr* doc, + const char* path, const char* accepts = "text/xml"); /// @brief Helper to make a POST request to the agent /// @param file The source file the request is made from @@ -278,15 +278,15 @@ class AgentTestHelper /// @param doc The returned document /// @param path The request path /// @param accepts The accepted mime type - void deleteResponseHelper(const char *file, int line, - const mtconnect::sink::rest_sink::QueryMap &aQueries, xmlDocPtr *doc, - const char *path, const char *accepts = "text/xml"); + void deleteResponseHelper(const char* file, int line, + const mtconnect::sink::rest_sink::QueryMap& aQueries, xmlDocPtr* doc, + const char* path, const char* accepts = "text/xml"); /// @brief Helper to get a chunked response from the agent /// @param file The source file the request is made from /// @param line The line number /// @param doc The returned document - void chunkStreamHelper(const char *file, int line, xmlDocPtr *doc); + void chunkStreamHelper(const char* file, int line, xmlDocPtr* doc); /// @brief Make a request to the agent /// @param file The source file the request is made from @@ -296,9 +296,9 @@ class AgentTestHelper /// @param aQueries The query parameters /// @param path The request path /// @param accepts The accepted mime type - void makeRequest(const char *file, int line, boost::beast::http::verb verb, - const std::string &body, const mtconnect::sink::rest_sink::QueryMap &aQueries, - const char *path, const char *accepts); + void makeRequest(const char* file, int line, boost::beast::http::verb verb, + const std::string& body, const mtconnect::sink::rest_sink::QueryMap& aQueries, + const char* path, const char* accepts); /// @brief Make a request using a json command to parse and dispatch /// @param file The source file the request is made from @@ -306,8 +306,8 @@ class AgentTestHelper /// @param json the request /// @param doc the returned document /// @param id the request id - void makeWebSocketRequest(const char *file, int line, const std::string &json, xmlDocPtr *doc, - std::string &id); + void makeWebSocketRequest(const char* file, int line, const std::string& json, xmlDocPtr* doc, + std::string& id); /// @brief Make a request using a json command to parse and dispatch /// @param file The source file the request is made from @@ -315,30 +315,30 @@ class AgentTestHelper /// @param json the request /// @param doc the returned document /// @param id the request id - void makeWebSocketRequest(const char *file, int line, const std::string &json, - nlohmann::json &doc, std::string &id); + void makeWebSocketRequest(const char* file, int line, const std::string& json, + nlohmann::json& doc, std::string& id); /// @brief Make a request and don't wait for a response /// @param file The source file the request is made from /// @param line The line number /// @param json the request /// @param id the request id - void makeAsyncWebSocketRequest(const char *file, int line, const std::string &json, - std::string &id); + void makeAsyncWebSocketRequest(const char* file, int line, const std::string& json, + std::string& id); /// @brief Parse an async respone /// @param file The source file the request is made from /// @param line The line number /// @param doc the returned document /// @param id the request id - void parseResponse(const char *file, int line, nlohmann::json &doc, const std::string &id); + void parseResponse(const char* file, int line, nlohmann::json& doc, const std::string& id); /// @brief Parse an async respone /// @param file The source file the request is made from /// @param line The line number /// @param doc the returned document /// @param id the request id - void parseResponse(const char *file, int line, xmlDocPtr *doc, const std::string &id); + void parseResponse(const char* file, int line, xmlDocPtr* doc, const std::string& id); auto getAgent() { return m_agent.get(); } std::shared_ptr getRestService() @@ -366,10 +366,10 @@ class AgentTestHelper return mqtt2; } - auto createAgent(const std::string &file, int bufferSize = 8, int maxAssets = 4, - const std::string &version = "1.7", int checkpoint = 25, bool put = false, + auto createAgent(const std::string& file, int bufferSize = 8, int maxAssets = 4, + const std::string& version = "1.7", int checkpoint = 25, bool put = false, bool observe = true, const mtconnect::ConfigOptions ops = {}, - const boost::property_tree::ptree &config = {}) + const boost::property_tree::ptree& config = {}) { using namespace mtconnect; using namespace mtconnect::pipeline; @@ -404,7 +404,7 @@ class AgentTestHelper auto sinkContract = m_agent->makeSinkContract(); sinkContract->m_findDataFile = - [](const std::string &n) -> std::optional { + [](const std::string& n) -> std::optional { if (std::filesystem::exists(n)) { return std::filesystem::path(n); @@ -475,8 +475,8 @@ class AgentTestHelper return m_agent.get(); } - auto addAdapter(mtconnect::ConfigOptions options = {}, const std::string &host = "localhost", - uint16_t port = 7878, const std::string &device = "") + auto addAdapter(mtconnect::ConfigOptions options = {}, const std::string& host = "localhost", + uint16_t port = 7878, const std::string& device = "") { using namespace mtconnect; using namespace mtconnect::source::adapter; @@ -494,8 +494,8 @@ class AgentTestHelper return m_adapter; } - uint64_t addToBuffer(mtconnect::DataItemPtr di, const mtconnect::entity::Properties &shdr, - const mtconnect::Timestamp &time) + uint64_t addToBuffer(mtconnect::DataItemPtr di, const mtconnect::entity::Properties& shdr, + const mtconnect::Timestamp& time) { using namespace mtconnect; using namespace mtconnect::observation; @@ -510,7 +510,7 @@ class AgentTestHelper } template - bool waitFor(const std::chrono::duration &time, std::function pred) + bool waitFor(const std::chrono::duration& time, std::function pred) { std::decay_t run = time / 2; if (run > std::chrono::milliseconds(500)) @@ -536,7 +536,7 @@ class AgentTestHelper } template - bool waitForResponseSent(const std::chrono::duration &time, const std::string &id) + bool waitForResponseSent(const std::chrono::duration& time, const std::string& id) { uint32_t initial = m_websocketSession->m_responsesSent[id]; return waitFor(time, [this, initial, id]() -> bool { @@ -558,7 +558,7 @@ class AgentTestHelper << "------------------------" << std::endl; } - void printLastWSResponse(const std::string &id) + void printLastWSResponse(const std::string& id) { auto it = m_websocketSession->m_lastResponses.find(id); if (it != m_websocketSession->m_lastResponses.end()) @@ -568,12 +568,12 @@ class AgentTestHelper } } - auto getResponseCount(const std::string &id) + auto getResponseCount(const std::string& id) { return m_websocketSession->m_responses[id].size(); } - mhttp::Server *m_server {nullptr}; + mhttp::Server* m_server {nullptr}; std::shared_ptr m_context; std::shared_ptr m_adapter; std::shared_ptr m_mqttService; diff --git a/test_package/asset_buffer_test.cpp b/test_package/asset_buffer_test.cpp index fb0c3474..7cdaf46d 100644 --- a/test_package/asset_buffer_test.cpp +++ b/test_package/asset_buffer_test.cpp @@ -43,7 +43,7 @@ using namespace mtconnect::entity; using namespace mtconnect::asset; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -56,8 +56,8 @@ class AssetBufferTest : public testing::Test void TearDown() override { m_assetBuffer.reset(); } - AssetPtr makeAsset(const string &type, const string &uuid, const string &device, const string &ts, - ErrorList &errors) + AssetPtr makeAsset(const string& type, const string& uuid, const string& device, const string& ts, + ErrorList& errors) { Properties props {{"assetId", uuid}, {"deviceUuid", device}, {"timestamp", ts}}; auto asset = Asset::getFactory()->make(type, props, errors); diff --git a/test_package/asset_hash_test.cpp b/test_package/asset_hash_test.cpp index bdbd1638..b238a923 100644 --- a/test_package/asset_hash_test.cpp +++ b/test_package/asset_hash_test.cpp @@ -38,7 +38,7 @@ using namespace mtconnect::source::adapter; using namespace entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -63,7 +63,7 @@ class AssetHashTest : public testing::Test m_agentTestHelper->m_agent->getDefaultDevice()->getName()); } - Adapter *m_adapter {nullptr}; + Adapter* m_adapter {nullptr}; std::string m_agentId; DevicePtr m_device; std::unique_ptr m_agentTestHelper; @@ -73,7 +73,7 @@ TEST_F(AssetHashTest, should_assign_hash_when_receiving_asset) { addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); m_agentTestHelper->m_adapter->parseBuffer( R"("2021-02-01T12:00:00Z|@ASSET@|P1|FakeAsset|--multiline--AAAA @@ -137,7 +137,7 @@ TEST_F(AssetHashTest, hash_should_change_when_doc_changes) { addAdapter(); auto agent = m_agentTestHelper->getAgent(); - const auto &storage = agent->getAssetStorage(); + const auto& storage = agent->getAssetStorage(); m_agentTestHelper->m_adapter->parseBuffer( R"("2021-02-01T12:00:00Z|@ASSET@|P1|FakeAsset|--multiline--AAAA diff --git a/test_package/asset_test.cpp b/test_package/asset_test.cpp index 9dad7564..6a0d8178 100644 --- a/test_package/asset_test.cpp +++ b/test_package/asset_test.cpp @@ -43,7 +43,7 @@ using namespace mtconnect::entity; using namespace mtconnect::asset; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -76,7 +76,7 @@ TEST_F(AssetTest, extended_asset_with_arbitrary_content_is_parsed_and_printed) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); entity::XmlPrinter printer; @@ -104,6 +104,6 @@ TEST_F(AssetTest, asset_should_parse_and_load_if_asset_id_is_missing_from_xml) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); } diff --git a/test_package/change_observer_test.cpp b/test_package/change_observer_test.cpp index 9d1a3069..c64dcd59 100644 --- a/test_package/change_observer_test.cpp +++ b/test_package/change_observer_test.cpp @@ -35,7 +35,7 @@ using namespace std::literals; using WorkGuard = boost::asio::executor_work_guard; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -141,7 +141,7 @@ namespace mtconnect { TEST_F(ChangeObserverTest, observer_is_removed_from_signaler_when_destroyed) { - mtconnect::ChangeObserver *changeObserver = nullptr; + mtconnect::ChangeObserver* changeObserver = nullptr; { changeObserver = new mtconnect::ChangeObserver(*m_strand); @@ -216,7 +216,7 @@ namespace mtconnect { { public: using AsyncObserver::AsyncObserver; - void fail(boost::beast::http::status status, const std::string &message) override + void fail(boost::beast::http::status status, const std::string& message) override { LOG(error) << message; }; @@ -299,7 +299,7 @@ namespace mtconnect { make_shared(*m_strand, m_buffer, std::move(filter), 500ms, 1000ms)}; auto expected = addObservations(3); - observer->observe(4, [this](const string &id) { return m_signalers[id].get(); }); + observer->observe(4, [this](const string& id) { return m_signalers[id].get(); }); bool called {false}; observer->m_handler = [&](std::shared_ptr obs) { @@ -332,7 +332,7 @@ namespace mtconnect { make_shared(*m_strand, m_buffer, std::move(filter), 250ms, 500ms)}; addObservations(3); - observer->observe(2, [this](const string &id) { return m_signalers[id].get(); }); + observer->observe(2, [this](const string& id) { return m_signalers[id].get(); }); ASSERT_FALSE(observer->isEndOfBuffer()); @@ -374,7 +374,7 @@ namespace mtconnect { make_shared(*m_strand, m_buffer, std::move(filter), 200ms, 500ms)}; addObservations(3); - observer->observe(1, [this](const string &id) { return m_signalers[id].get(); }); + observer->observe(1, [this](const string& id) { return m_signalers[id].get(); }); ASSERT_FALSE(observer->isEndOfBuffer()); @@ -438,7 +438,7 @@ namespace mtconnect { addObservations(3); - observer->observe(4, [this](const string &id) { return m_signalers[id].get(); }); + observer->observe(4, [this](const string& id) { return m_signalers[id].get(); }); ASSERT_TRUE(observer->isEndOfBuffer()); @@ -473,7 +473,7 @@ namespace mtconnect { addObservations(3); - observer->observe(4, [this](const string &id) { return m_signalers[id].get(); }); + observer->observe(4, [this](const string& id) { return m_signalers[id].get(); }); ASSERT_TRUE(observer->isEndOfBuffer()); diff --git a/test_package/checkpoint_test.cpp b/test_package/checkpoint_test.cpp index 5683f566..336a0da5 100644 --- a/test_package/checkpoint_test.cpp +++ b/test_package/checkpoint_test.cpp @@ -35,13 +35,13 @@ using namespace std::literals; using namespace date::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } -inline ConditionPtr Cond(ObservationPtr &ptr) { return dynamic_pointer_cast(ptr); } +inline ConditionPtr Cond(ObservationPtr& ptr) { return dynamic_pointer_cast(ptr); } class CheckpointTest : public testing::Test { diff --git a/test_package/circular_buffer_test.cpp b/test_package/circular_buffer_test.cpp index 2f228485..f1ce547f 100644 --- a/test_package/circular_buffer_test.cpp +++ b/test_package/circular_buffer_test.cpp @@ -36,13 +36,13 @@ using namespace std::literals; using namespace date::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } -inline ConditionPtr Cond(ObservationPtr &ptr) { return dynamic_pointer_cast(ptr); } +inline ConditionPtr Cond(ObservationPtr& ptr) { return dynamic_pointer_cast(ptr); } class CircularBufferTest : public testing::Test { diff --git a/test_package/component_parameters_test.cpp b/test_package/component_parameters_test.cpp index 428eb6ae..a71d26f7 100644 --- a/test_package/component_parameters_test.cpp +++ b/test_package/component_parameters_test.cpp @@ -45,7 +45,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -83,7 +83,7 @@ TEST_F(ComponentParametersTest, should_parse_simple_parameter_set) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("PARAMS2", asset->getAssetId()); @@ -117,7 +117,7 @@ TEST_F(ComponentParametersTest, should_parse_simple_parameter_set) auto hash1 = entity->hash(); entity->addHash(); - auto &hv = entity->getProperty("hash"); + auto& hv = entity->getProperty("hash"); ASSERT_NE(size_t(ValueType::EMPTY), hv.index()); auto hash2 = entity->hash(); @@ -165,7 +165,7 @@ TEST_F(ComponentParametersTest, should_parse_two_parameter_sets) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("PARAMS2", asset->getAssetId()); diff --git a/test_package/component_test.cpp b/test_package/component_test.cpp index 4ada0c51..ee1ff039 100644 --- a/test_package/component_test.cpp +++ b/test_package/component_test.cpp @@ -29,7 +29,7 @@ using namespace data_item; using namespace entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/composition_test.cpp b/test_package/composition_test.cpp index 76c1f039..0a40a9d3 100644 --- a/test_package/composition_test.cpp +++ b/test_package/composition_test.cpp @@ -40,7 +40,7 @@ using namespace device_model; using namespace entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -70,7 +70,7 @@ TEST_F(CompositionTest, composition_attributes_description_and_specifications_ar using namespace mtconnect::entity; ASSERT_NE(nullptr, m_component); - const auto &compositions = m_component->getList("Compositions"); + const auto& compositions = m_component->getList("Compositions"); ASSERT_TRUE(compositions); ASSERT_EQ(1, compositions->size()); @@ -91,7 +91,7 @@ TEST_F(CompositionTest, composition_attributes_description_and_specifications_ar EXPECT_EQ("A", get(description->getProperty("station"))); EXPECT_EQ("Hello There", get(description->getValue())); - const auto &configuration = (*composition)->get("Configuration"); + const auto& configuration = (*composition)->get("Configuration"); auto specs = configuration->getList("Specifications"); ASSERT_TRUE(specs); @@ -166,7 +166,7 @@ TEST_F(CompositionTest, should_create_topic) using namespace mtconnect::device_model; ASSERT_NE(nullptr, m_component); - const auto &compositions = m_component->getList("Compositions"); + const auto& compositions = m_component->getList("Compositions"); ASSERT_TRUE(compositions); auto composition = dynamic_pointer_cast(compositions->front()); diff --git a/test_package/config_parser_test.cpp b/test_package/config_parser_test.cpp index 82e6d443..26c091cc 100644 --- a/test_package/config_parser_test.cpp +++ b/test_package/config_parser_test.cpp @@ -26,7 +26,7 @@ using namespace configuration; using namespace std; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/config_test.cpp b/test_package/config_test.cpp index d96bb69c..2c6da48c 100644 --- a/test_package/config_test.cpp +++ b/test_package/config_test.cpp @@ -51,7 +51,7 @@ using namespace std::chrono_literals; using namespace boost::algorithm; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -77,7 +77,7 @@ namespace { chdir(m_cwd.string().c_str()); } - fs::path createTempDirectory(const string &ext) + fs::path createTempDirectory(const string& ext) { fs::path root {fs::path(TEST_BIN_ROOT_DIR) / ("config_test_" + ext)}; if (fs::exists(root)) @@ -93,7 +93,7 @@ namespace { return root; } - fs::path copySampleFile(const std::string &src, fs::path target, chrono::seconds delta) + fs::path copySampleFile(const std::string& src, fs::path target, chrono::seconds delta) { fs::path file {fs::path("samples") / src}; return copyFile(file, target, delta); @@ -111,7 +111,7 @@ namespace { return target; } - void replaceTextInFile(fs::path file, const std::string &from, const std::string &to) + void replaceTextInFile(fs::path file, const std::string& from, const std::string& to) { ifstream is {file.string(), ios::binary | ios::ate}; auto size = is.tellg(); @@ -146,7 +146,7 @@ namespace { m_config->loadConfig("BufferSize = 4\n"); auto agent = m_config->getAgent(); - auto &circ = agent->getCircularBuffer(); + auto& circ = agent->getCircularBuffer(); ASSERT_TRUE(agent); ASSERT_EQ(16U, circ.getBufferSize()); @@ -223,7 +223,7 @@ namespace { ASSERT_TRUE(source); const auto adapter = dynamic_pointer_cast(source); ASSERT_TRUE(adapter); - const auto &opts = adapter->getOptions(); + const auto& opts = adapter->getOptions(); EXPECT_EQ("http", *GetOption(opts, configuration::Protocol)); EXPECT_EQ("192.168.1.50", *GetOption(opts, configuration::Host)); @@ -342,9 +342,9 @@ namespace { "}\n"); m_config->loadConfig(streams); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("xml")); + auto printer = dynamic_cast(agent->getPrinter("xml")); ASSERT_TRUE(printer); auto path = printer->getStreamsUrn("x"); @@ -360,9 +360,9 @@ namespace { "}\n"); m_config->loadConfig(devices); - agent = const_cast(m_config->getAgent()); + agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - printer = dynamic_cast(agent->getPrinter("xml")); + printer = dynamic_cast(agent->getPrinter("xml")); ASSERT_TRUE(printer); path = printer->getDevicesUrn("y"); ASSERT_EQ(std::string("urn:example.com:ExampleDevices:1.2"), path); @@ -377,9 +377,9 @@ namespace { "}\n"); m_config->loadConfig(asset); - agent = const_cast(m_config->getAgent()); + agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - printer = dynamic_cast(agent->getPrinter("xml")); + printer = dynamic_cast(agent->getPrinter("xml")); ASSERT_TRUE(printer); path = printer->getAssetsUrn("z"); ASSERT_EQ(std::string("urn:example.com:ExampleAssets:1.2"), path); @@ -394,9 +394,9 @@ namespace { "}\n"); m_config->loadConfig(errors); - agent = const_cast(m_config->getAgent()); + agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - printer = dynamic_cast(agent->getPrinter("xml")); + printer = dynamic_cast(agent->getPrinter("xml")); ASSERT_TRUE(printer); path = printer->getErrorUrn("a"); ASSERT_EQ(std::string("urn:example.com:ExampleErrors:1.2"), path); @@ -461,9 +461,9 @@ namespace { "}\n"); m_config->loadConfig(streams); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("xml")); + auto printer = dynamic_cast(agent->getPrinter("xml")); ASSERT_TRUE(printer); auto path = printer->getStreamsUrn("m"); @@ -479,9 +479,9 @@ namespace { string streams("SchemaVersion = 1.4\n"); m_config->loadConfig(streams); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("xml")); + auto printer = dynamic_cast(agent->getPrinter("xml")); ASSERT_TRUE(printer); auto version = printer->getSchemaVersion(); @@ -507,9 +507,9 @@ namespace { m_config->setDebug(true); m_config->loadConfig(schemas); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("xml")); + auto printer = dynamic_cast(agent->getPrinter("xml")); ASSERT_TRUE(printer); auto path = printer->getStreamsUrn("m"); @@ -541,7 +541,7 @@ namespace { "\n" "}\n"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); ASSERT_TRUE(agent); @@ -551,10 +551,10 @@ namespace { ASSERT_TRUE(rest); const auto server = rest->getServer(); - const auto &headers = server->getHttpHeaders(); + const auto& headers = server->getHttpHeaders(); ASSERT_EQ(1, headers.size()); - const auto &first = headers.front(); + const auto& first = headers.front(); ASSERT_EQ("Access-Control-Allow-Origin", first.first); ASSERT_EQ(" *", first.second); } @@ -573,7 +573,7 @@ Sinks { )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto sink = agent->findSink("TestBADService"); @@ -590,7 +590,7 @@ Sinks { )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); @@ -612,7 +612,7 @@ Sinks { )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); @@ -630,7 +630,7 @@ Sinks { )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto sink1 = agent->findSink("sink_plugin_test"); @@ -651,7 +651,7 @@ Sinks { )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto sink1 = agent->findSink("sink_plugin_test"); @@ -674,7 +674,7 @@ Adapters { )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto adapter = agent->findSource("_Host1_7878"); @@ -693,7 +693,7 @@ Adapters { )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto adapter = agent->findSource("Test"); @@ -717,7 +717,7 @@ Adapters { )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto adapter = agent->findSource("Test"); @@ -731,7 +731,7 @@ MaxCachedFileSize = 2000 )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto rest = @@ -749,7 +749,7 @@ MaxCachedFileSize = 2k )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto rest = @@ -767,7 +767,7 @@ MaxCachedFileSize = 2K )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto rest = @@ -785,7 +785,7 @@ MaxCachedFileSize = 2m )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto rest = @@ -803,7 +803,7 @@ MaxCachedFileSize = 2g )"); m_config->loadConfig(str); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); const auto rest = @@ -1108,10 +1108,10 @@ Port = 0 options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &context = m_config->getAsyncContext(); + auto& context = m_config->getAsyncContext(); auto agent = m_config->getAgent(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto chg = printer->getModelChangeTime(); @@ -1153,7 +1153,7 @@ Port = 0 EXPECT_FALSE(dataItem->isOrphan()); auto agent = m_config->getAgent(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); EXPECT_NE(nullptr, printer); EXPECT_NE(chg, printer->getModelChangeTime()); } @@ -1187,10 +1187,10 @@ Port = 0 options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &context = m_config->getAsyncContext(); + auto& context = m_config->getAsyncContext(); auto agent = m_config->getAgent(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto chg = printer->getModelChangeTime(); @@ -1219,7 +1219,7 @@ Port = 0 if (!ec) { auto agent = m_config->getAgent(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); EXPECT_NE(nullptr, printer); EXPECT_EQ(chg, printer->getModelChangeTime()); } @@ -1232,7 +1232,7 @@ Port = 0 TEST_F(ConfigTest, should_restart_agent_when_config_file_changes) { fs::path root {createTempDirectory("3")}; - auto &context = m_config->getAsyncContext(); + auto& context = m_config->getAsyncContext(); fs::path devices(root / "Devices.xml"); fs::path config {root / "agent.cfg"}; @@ -1328,10 +1328,10 @@ Port = 0 options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &context = m_config->getAsyncContext(); + auto& context = m_config->getAsyncContext(); auto agent = m_config->getAgent(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto chg = printer->getModelChangeTime(); @@ -1370,7 +1370,7 @@ Port = 0 EXPECT_TRUE(last); EXPECT_EQ("001", last->getUuid()); - const auto &dis = last->getDeviceDataItems(); + const auto& dis = last->getDeviceDataItems(); EXPECT_EQ(5, dis.size()); EXPECT_TRUE(last->getDeviceDataItem("xd1")); @@ -1396,7 +1396,7 @@ Port = 0 string streams("SchemaVersion = 2.0\nDisableAgentDevice = true\n"); m_config->loadConfig(streams); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); auto devices = agent->getDevices(); @@ -1411,7 +1411,7 @@ Port = 0 string streams("SchemaVersion = 2.0\n"); m_config->loadConfig(streams); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); auto devices = agent->getDevices(); @@ -1447,7 +1447,7 @@ Port = 0 m_config->initialize(options); auto agent = m_config->getAgent(); - auto &context = m_config->getAsyncContext(); + auto& context = m_config->getAsyncContext(); auto sink = agent->findSink("RestService"); auto rest = dynamic_pointer_cast(sink); ASSERT_TRUE(rest); @@ -1456,7 +1456,7 @@ Port = 0 sink.reset(); rest.reset(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); ASSERT_EQ("1.2", *printer->getSchemaVersion()); @@ -1501,7 +1501,7 @@ Port = 0 EXPECT_TRUE(dataItem); EXPECT_EQ("ROTARY_VELOCITY", dataItem->getType()); - const auto &printer = agent2->getPrinter("xml"); + const auto& printer = agent2->getPrinter("xml"); EXPECT_NE(nullptr, printer); ASSERT_EQ("1.3", *printer->getSchemaVersion()); } @@ -1544,10 +1544,10 @@ Adapters { options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &asyncContext = m_config->getAsyncContext(); + auto& asyncContext = m_config->getAsyncContext(); auto agent = m_config->getAgent(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto sp = agent->findSource("_localhost_7878"); @@ -1568,13 +1568,13 @@ Adapters { auto dit = directory_iterator("."); std::list entries; copy_if(dit, end(dit), back_inserter(entries), - [&ext](const auto &de) { return contains(de.path().string(), ext); }); + [&ext](const auto& de) { return contains(de.path().string(), ext); }); ASSERT_EQ(1, entries.size()); auto device = agent->getDeviceByName("LinuxCNC"); ASSERT_TRUE(device) << "Cannot find LinuxCNC device"; - const auto &components = device->getChildren(); + const auto& components = device->getChildren(); ASSERT_EQ(1, components->size()); auto cont = device->getComponentById("cont"); @@ -1583,7 +1583,7 @@ Adapters { auto exec = device->getDeviceDataItem("exec"); ASSERT_TRUE(exec) << "Cannot find DataItem with id exec"; - auto pipeline = dynamic_cast(adapter->getPipeline()); + auto pipeline = dynamic_cast(adapter->getPipeline()); ASSERT_EQ("000", pipeline->getDevice()); } m_config->stop(); @@ -1656,13 +1656,13 @@ Port = 0 options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &asyncContext = m_config->getAsyncContext(); + auto& asyncContext = m_config->getAsyncContext(); auto agent = m_config->getAgent(); auto device = agent->getDeviceByName("LinuxCNC"); ASSERT_TRUE(device); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto sp = agent->findSource("_localhost_7878"); @@ -1683,13 +1683,13 @@ Port = 0 auto dit = directory_iterator("."); std::list entries; copy_if(dit, end(dit), back_inserter(entries), - [&ext](const auto &de) { return contains(de.path().string(), ext); }); + [&ext](const auto& de) { return contains(de.path().string(), ext); }); ASSERT_EQ(2, entries.size()); auto device = agent->getDeviceByName("LinuxCNC"); ASSERT_TRUE(device) << "Cannot find LinuxCNC device"; - const auto &components = device->getChildren(); + const auto& components = device->getChildren(); ASSERT_EQ(1, components->size()); auto conts = device->getComponentByType("Controller"); @@ -1715,7 +1715,7 @@ Port = 0 auto exec = device->getDeviceDataItem("exc"); ASSERT_TRUE(exec) << "Cannot find DataItem with id exc"; - auto pipeline = dynamic_cast(adapter->getPipeline()); + auto pipeline = dynamic_cast(adapter->getPipeline()); ASSERT_EQ("000", pipeline->getDevice()); } m_config->stop(); @@ -1847,13 +1847,13 @@ Port = 0 options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &asyncContext = m_config->getAsyncContext(); + auto& asyncContext = m_config->getAsyncContext(); auto agent = m_config->getAgent(); auto device = agent->getDeviceByName("LinuxCNC"); ASSERT_TRUE(device); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto sp = agent->findSource("_localhost_7878"); @@ -1874,7 +1874,7 @@ Port = 0 auto dit = directory_iterator("."); std::list entries; copy_if(dit, end(dit), back_inserter(entries), - [&ext](const auto &de) { return contains(de.path().string(), ext); }); + [&ext](const auto& de) { return contains(de.path().string(), ext); }); ASSERT_EQ(2, entries.size()); ASSERT_EQ(3, agent->getDevices().size()); @@ -1885,7 +1885,7 @@ Port = 0 auto device2 = agent->getDeviceByName("AnotherCNC"); ASSERT_TRUE(device2) << "Cannot find LinuxCNC device"; - auto pipeline = dynamic_cast(adapter->getPipeline()); + auto pipeline = dynamic_cast(adapter->getPipeline()); ASSERT_EQ("001", pipeline->getDevice()); } m_config->stop(); @@ -1900,7 +1900,7 @@ Port = 0 } else { - auto pipeline = dynamic_cast(adapter->getPipeline()); + auto pipeline = dynamic_cast(adapter->getPipeline()); ASSERT_EQ("LinuxCNC", pipeline->getDevice()); adapter->processData("* deviceModel: --multiline--AAAAA"); @@ -1965,10 +1965,10 @@ Adapters { options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &asyncContext = m_config->getAsyncContext(); + auto& asyncContext = m_config->getAsyncContext(); auto agent = m_config->getAgent(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto sp = agent->findSource("_localhost_7878"); @@ -1989,7 +1989,7 @@ Adapters { auto dit = directory_iterator("."); std::list entries; copy_if(dit, end(dit), back_inserter(entries), - [&ext](const auto &de) { return contains(de.path().string(), ext); }); + [&ext](const auto& de) { return contains(de.path().string(), ext); }); ASSERT_EQ(1, entries.size()); auto device = agent->getDeviceByName("LinuxCNC"); @@ -2070,13 +2070,13 @@ Port = 0 options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &asyncContext = m_config->getAsyncContext(); + auto& asyncContext = m_config->getAsyncContext(); auto agent = m_config->getAgent(); auto device = agent->getDeviceByName("LinuxCNC"); ASSERT_TRUE(device); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto sp = agent->findSource("_localhost_7878"); @@ -2104,7 +2104,7 @@ Port = 0 auto dit = directory_iterator("."); std::list entries; copy_if(dit, end(dit), back_inserter(entries), - [&ext](const auto &de) { return contains(de.path().string(), ext); }); + [&ext](const auto& de) { return contains(de.path().string(), ext); }); ASSERT_EQ(2, entries.size()); ASSERT_EQ(3, agent->getDevices().size()); @@ -2115,7 +2115,7 @@ Port = 0 auto device2 = agent->getDeviceByName("AnotherCNC"); ASSERT_TRUE(device2) << "Cannot find LinuxCNC device"; - auto pipeline = dynamic_cast(adapter->getPipeline()); + auto pipeline = dynamic_cast(adapter->getPipeline()); ASSERT_EQ("001", pipeline->getDevice()); } @@ -2132,7 +2132,7 @@ Port = 0 } else { - auto pipeline = dynamic_cast(adapter->getPipeline()); + auto pipeline = dynamic_cast(adapter->getPipeline()); ASSERT_EQ("LinuxCNC", pipeline->getDevice()); adapter->processData("* deviceModel: --multiline--AAAAA"); @@ -2197,10 +2197,10 @@ Adapters { options.insert(make_pair("config-file"s, value)); m_config->initialize(options); - auto &asyncContext = m_config->getAsyncContext(); + auto& asyncContext = m_config->getAsyncContext(); auto agent = m_config->getAgent(); - const auto &printer = agent->getPrinter("xml"); + const auto& printer = agent->getPrinter("xml"); ASSERT_NE(nullptr, printer); auto sp = agent->findSource("_localhost_7878"); @@ -2256,7 +2256,7 @@ ServiceName=$CONFIG_TEST m_config->setDebug(true); m_config->loadConfig(config); - const auto &options = m_config->getAgent()->getOptions(); + const auto& options = m_config->getAgent()->getOptions(); ASSERT_EQ("TestValue", *GetOption(options, configuration::ServiceName)); } @@ -2272,7 +2272,7 @@ ServiceName=$TestVariable m_config->setDebug(true); m_config->loadConfig(config); - const auto &options = m_config->getAgent()->getOptions(); + const auto& options = m_config->getAgent()->getOptions(); ASSERT_EQ("TestValue", *GetOption(options, configuration::ServiceName)); } @@ -2288,7 +2288,7 @@ ServiceName=/some/prefix/$CONFIG_TEST:suffix m_config->setDebug(true); m_config->loadConfig(config); - const auto &options = m_config->getAgent()->getOptions(); + const auto& options = m_config->getAgent()->getOptions(); ASSERT_EQ("/some/prefix/TestValue:suffix", *GetOption(options, configuration::ServiceName)); } @@ -2304,7 +2304,7 @@ ServiceName="some_prefix_${CONFIG_TEST}_suffix" m_config->setDebug(true); m_config->loadConfig(config); - const auto &options = m_config->getAgent()->getOptions(); + const auto& options = m_config->getAgent()->getOptions(); ASSERT_EQ("some_prefix_TestValue_suffix", *GetOption(options, configuration::ServiceName)); } @@ -2376,7 +2376,7 @@ AgentDeviceUUID = SOME_UUID m_config->setDebug(true); m_config->loadConfig(config); - const auto &ad = m_config->getAgent()->getAgentDevice(); + const auto& ad = m_config->getAgent()->getAgentDevice(); ASSERT_EQ("SOME_UUID", *(ad->getUuid())); } @@ -2557,9 +2557,9 @@ DevicesStyle { string streams("Sender = MachineXXX\n"); m_config->loadConfig(streams); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("xml")); + auto printer = dynamic_cast(agent->getPrinter("xml")); ASSERT_TRUE(printer); auto sender = printer->getSenderName(); @@ -2577,11 +2577,11 @@ DevicesJsonSchema {{ PROJECT_ROOT_DIR)}; m_config->loadConfig(config); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("json")); + auto printer = dynamic_cast(agent->getPrinter("json")); ASSERT_TRUE(printer); - const auto &schema = printer->getDevicesSchema(); + const auto& schema = printer->getDevicesSchema(); ASSERT_TRUE(schema); ASSERT_EQ("http://localhost:5000/myschemas/MTConnectDevices_2.7_draft-04.schema.json", *schema); } @@ -2596,11 +2596,11 @@ StreamsJsonSchema {{ PROJECT_ROOT_DIR)}; m_config->loadConfig(config); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("json")); + auto printer = dynamic_cast(agent->getPrinter("json")); ASSERT_TRUE(printer); - const auto &schema = printer->getStreamsSchema(); + const auto& schema = printer->getStreamsSchema(); ASSERT_TRUE(schema); ASSERT_EQ("http://localhost:5000/myschemas/MTConnectStreams_2.7_draft-04.schema.json", *schema); } @@ -2615,11 +2615,11 @@ AssetsJsonSchema {{ PROJECT_ROOT_DIR)}; m_config->loadConfig(config); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("json")); + auto printer = dynamic_cast(agent->getPrinter("json")); ASSERT_TRUE(printer); - const auto &schema = printer->getAssetsSchema(); + const auto& schema = printer->getAssetsSchema(); ASSERT_TRUE(schema); ASSERT_EQ("http://localhost:5000/myschemas/MTConnectAssets_2.7_draft-04.schema.json", *schema); } @@ -2634,11 +2634,11 @@ ErrorJsonSchema {{ PROJECT_ROOT_DIR)}; m_config->loadConfig(config); - auto agent = const_cast(m_config->getAgent()); + auto agent = const_cast(m_config->getAgent()); ASSERT_TRUE(agent); - auto printer = dynamic_cast(agent->getPrinter("json")); + auto printer = dynamic_cast(agent->getPrinter("json")); ASSERT_TRUE(printer); - const auto &schema = printer->getErrorSchema(); + const auto& schema = printer->getErrorSchema(); ASSERT_TRUE(schema); ASSERT_EQ("http://localhost:5000/myschemas/MTConnectError_2.7_draft-04.schema.json", *schema); } diff --git a/test_package/connector_test.cpp b/test_package/connector_test.cpp index 0368d0f4..668ae460 100644 --- a/test_package/connector_test.cpp +++ b/test_package/connector_test.cpp @@ -51,7 +51,7 @@ namespace sys = boost::system; using namespace chrono_literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -61,7 +61,7 @@ int main(int argc, char *argv[]) class TestConnector : public Connector { public: - TestConnector(boost::asio::io_context::strand &strand, const std::string &server, + TestConnector(boost::asio::io_context::strand& strand, const std::string& server, unsigned int port, std::chrono::seconds legacyTimeout = std::chrono::seconds {5}, std::chrono::seconds reconnectInterval = std::chrono::seconds {10}, std::optional heartbeat = std::nullopt) @@ -76,7 +76,7 @@ class TestConnector : public Connector return Connector::start(); } - void processData(const std::string &data) override + void processData(const std::string& data) override { if (data[0] == '*') protocolCommand(data); @@ -87,7 +87,7 @@ class TestConnector : public Connector } } - void protocolCommand(const std::string &data) override { m_command = data; } + void protocolCommand(const std::string& data) override { m_command = data; } void connecting() override {} @@ -95,7 +95,7 @@ class TestConnector : public Connector void connected() override { m_disconnected = false; } bool heartbeats() { return m_heartbeats; } - void startHeartbeats(std::string &aString) { Connector::startHeartbeats(aString); } + void startHeartbeats(std::string& aString) { Connector::startHeartbeats(aString); } void resetHeartbeats() { m_heartbeats = false; } @@ -105,7 +105,7 @@ class TestConnector : public Connector std::string m_command; bool m_disconnected; - boost::asio::io_context::strand &m_strand; + boost::asio::io_context::strand& m_strand; }; /// @brief Connector test runner @@ -163,7 +163,7 @@ class ConnectorTest : public testing::Test EXPECT_TRUE(pred()); } - void send(const std::string &s) + void send(const std::string& s) { ASSERT_TRUE(m_server); diff --git a/test_package/coordinate_system_test.cpp b/test_package/coordinate_system_test.cpp index a3f739cc..c59f32e9 100644 --- a/test_package/coordinate_system_test.cpp +++ b/test_package/coordinate_system_test.cpp @@ -38,7 +38,7 @@ using namespace mtconnect::source::adapter; using namespace entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -57,7 +57,7 @@ class CoordinateSystemTest : public testing::Test void TearDown() override { m_agentTestHelper.reset(); } - Adapter *m_adapter {nullptr}; + Adapter* m_adapter {nullptr}; std::string m_agentId; DevicePtr m_device {nullptr}; std::unique_ptr m_agentTestHelper; @@ -67,10 +67,10 @@ TEST_F(CoordinateSystemTest, coordinate_systems_with_origin_and_transformation_a { ASSERT_NE(nullptr, m_device); - auto &clc = m_device->get("Configuration"); + auto& clc = m_device->get("Configuration"); ASSERT_TRUE(clc); - const auto &cds = clc->getList("CoordinateSystems"); + const auto& cds = clc->getList("CoordinateSystems"); ASSERT_TRUE(cds); ASSERT_EQ(2, cds->size()); diff --git a/test_package/correct_timestamp_test.cpp b/test_package/correct_timestamp_test.cpp index b2a6ca06..17fc6bbc 100644 --- a/test_package/correct_timestamp_test.cpp +++ b/test_package/correct_timestamp_test.cpp @@ -42,7 +42,7 @@ using namespace std::literals; using namespace std::chrono_literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -51,9 +51,9 @@ int main(int argc, char *argv[]) class MockPipelineContract : public PipelineContract { public: - MockPipelineContract(std::map &items) : m_dataItems(items) {} - DevicePtr findDevice(const std::string &device) override { return nullptr; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + MockPipelineContract(std::map& items) : m_dataItems(items) {} + DevicePtr findDevice(const std::string& device) override { return nullptr; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_dataItems[name]; } @@ -66,11 +66,11 @@ class MockPipelineContract : public PipelineContract int32_t getSchemaVersion() const override { return IntDefaultSchemaVersion(); } bool isValidating() const override { return false; } void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return nullptr; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return nullptr; } - std::map &m_dataItems; + std::map& m_dataItems; }; class CorrectTimestampTest : public testing::Test diff --git a/test_package/cutting_tool_test.cpp b/test_package/cutting_tool_test.cpp index e0fd816d..d51419e5 100644 --- a/test_package/cutting_tool_test.cpp +++ b/test_package/cutting_tool_test.cpp @@ -48,7 +48,7 @@ using namespace mtconnect::source::adapter; using namespace mtconnect::asset; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -104,7 +104,7 @@ TEST_F(CuttingToolTest, minimal_cutting_tool_archetype_is_parsed) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("CAT", get(entity->getProperty("toolId"))); @@ -163,7 +163,7 @@ TEST_F(CuttingToolTest, cutting_tool_archetype_measurements_are_parsed) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("CAT", get(entity->getProperty("toolId"))); @@ -238,7 +238,7 @@ TEST_F(CuttingToolTest, cutting_tool_archetype_cutting_items_are_parsed) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("CAT", get(entity->getProperty("toolId"))); @@ -357,7 +357,7 @@ TEST_F(CuttingToolTest, minimal_cutting_tool_is_parsed) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("CAT", get(entity->getProperty("toolId"))); @@ -460,7 +460,7 @@ TEST_F(CuttingToolTest, cutting_tool_measurements_without_value_fails_validation TEST_F(CuttingToolTest, cutting_tool_with_simple_cutting_items_is_loaded_via_adapter) { - auto printer = dynamic_cast(m_agentTestHelper->m_agent->getPrinter("xml")); + auto printer = dynamic_cast(m_agentTestHelper->m_agent->getPrinter("xml")); ASSERT_TRUE(printer != nullptr); printer->clearAssetsNamespaces(); @@ -525,7 +525,7 @@ TEST_F(CuttingToolTest, test_extended_cutting_item) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("123456", get(entity->getProperty("toolId"))); @@ -539,7 +539,7 @@ TEST_F(CuttingToolTest, test_extended_cutting_item) auto itemList = lifeCycle->getList("CuttingItems"); ASSERT_EQ(1, itemList->size()); - auto &item = *itemList->begin(); + auto& item = *itemList->begin(); ASSERT_EQ("1", get(item->getProperty("indices"))); auto life = get(item->getProperty("ItemLife")); @@ -666,7 +666,7 @@ TEST_F(CuttingToolTest, test_extended_cutting_tool_with_json_v2) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); entity::JsonEntityPrinter jprinter(2, true); diff --git a/test_package/data_item_mapping_test.cpp b/test_package/data_item_mapping_test.cpp index 95a1296a..1b99dc83 100644 --- a/test_package/data_item_mapping_test.cpp +++ b/test_package/data_item_mapping_test.cpp @@ -35,7 +35,7 @@ using namespace data_item; using namespace std; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -44,11 +44,11 @@ int main(int argc, char *argv[]) class MockPipelineContract : public PipelineContract { public: - MockPipelineContract(std::map &items, int32_t schemaVersion) + MockPipelineContract(std::map& items, int32_t schemaVersion) : m_dataItems(items), m_schemaVersion(schemaVersion) {} - DevicePtr findDevice(const std::string &) override { return nullptr; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DevicePtr findDevice(const std::string&) override { return nullptr; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_dataItems[name]; } @@ -61,11 +61,11 @@ class MockPipelineContract : public PipelineContract bool isValidating() const override { return false; } void deliverAssetCommand(entity::EntityPtr) override {} void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } - std::map &m_dataItems; + std::map& m_dataItems; int32_t m_schemaVersion; }; @@ -82,7 +82,7 @@ class DataItemMappingTest : public testing::Test void TearDown() override { m_dataItems.clear(); } - DataItemPtr makeDataItem(const Properties &props) + DataItemPtr makeDataItem(const Properties& props) { Properties ps(props); ErrorList errors; @@ -106,8 +106,8 @@ class DataItemMappingTest : public testing::Test std::map m_dataItems; }; -inline DataSetEntry operator""_E(const char *c, std::size_t) { return DataSetEntry(c); } -inline TableCell operator""_C(const char *c, std::size_t) { return TableCell(c); } +inline DataSetEntry operator""_E(const char* c, std::size_t) { return DataSetEntry(c); } +inline TableCell operator""_C(const char* c, std::size_t) { return TableCell(c); } TEST_F(DataItemMappingTest, should_map_simple_sample) { @@ -116,7 +116,7 @@ TEST_F(DataItemMappingTest, should_map_simple_sample) auto ts = makeTimestamped({"a", "READY"}); auto observations = (*m_mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -137,7 +137,7 @@ TEST_F(DataItemMappingTest, should_map_simple_unavailable_event) auto ts = makeTimestamped({"a", "unavailable"s}); auto observations = (*m_mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -157,7 +157,7 @@ TEST_F(DataItemMappingTest, should_map_two_simple_events) auto ts = makeTimestamped({"a", "READY", "a", "ACTIVE"}); auto observations = (*m_mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -187,7 +187,7 @@ TEST_F(DataItemMappingTest, should_map_a_message) auto ts = makeTimestamped({"a", "A123", "some text"}); auto observations = (*m_mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -209,7 +209,7 @@ TEST_F(DataItemMappingTest, should_map_a_sample_and_validate_type) {{"id", "a"s}, {"type", "POSITION"s}, {"category", "SAMPLE"s}, {"units", "MILLIMETER"}}); auto ts = makeTimestamped({"a", "1.23456"}); auto observations = (*m_mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -228,7 +228,7 @@ TEST_F(DataItemMappingTest, should_map_a_sample_with_invalid_data_to_unavailable {{"id", "a"s}, {"type", "POSITION"s}, {"category", "SAMPLE"s}, {"units", "MILLIMETER"s}}); auto ts = makeTimestamped({"a", "ABC"}); auto observations = (*m_mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); ASSERT_EQ(1, oblist.size()); @@ -360,7 +360,7 @@ TEST_F(DataItemMappingTest, should_map_an_event_data_set) ASSERT_EQ(di, set->getDataItem()); - auto &ds = set->getValue(); + auto& ds = set->getValue(); ASSERT_EQ(3, ds.size()); ASSERT_EQ(1, get(ds.find("a"_E)->m_value)); ASSERT_EQ(2, get(ds.find("b"_E)->m_value)); @@ -385,7 +385,7 @@ TEST_F(DataItemMappingTest, should_map_a_sample_data_set) ASSERT_EQ(di, set->getDataItem()); - auto &ds = set->getValue(); + auto& ds = set->getValue(); ASSERT_EQ(3, ds.size()); ASSERT_EQ(1, get(ds.find("a"_E)->m_value)); ASSERT_EQ(2, get(ds.find("b"_E)->m_value)); @@ -408,19 +408,19 @@ TEST_F(DataItemMappingTest, should_map_an_event_table) ASSERT_EQ(di, set->getDataItem()); ASSERT_EQ("SomethingTable", set->getName()); - auto &ds = set->getValue(); + auto& ds = set->getValue(); ASSERT_EQ(3, ds.size()); - const auto &a = get(ds.find("a"_E)->m_value); + const auto& a = get(ds.find("a"_E)->m_value); ASSERT_EQ(2, a.size()); ASSERT_EQ(1, get(a.find("c"_C)->m_value)); ASSERT_EQ(3.0, get(a.find("n"_C)->m_value)); - const auto &b = get(ds.find("b"_E)->m_value); + const auto& b = get(ds.find("b"_E)->m_value); ASSERT_EQ(2, a.size()); ASSERT_EQ(2, get(b.find("d"_C)->m_value)); ASSERT_EQ(3, get(b.find("e"_C)->m_value)); - const auto &c = get(ds.find("c"_E)->m_value); + const auto& c = get(ds.find("c"_E)->m_value); ASSERT_EQ(2, c.size()); ASSERT_EQ("abc", get(c.find("x"_C)->m_value)); ASSERT_EQ("def", get(c.find("y"_C)->m_value)); @@ -444,19 +444,19 @@ TEST_F(DataItemMappingTest, should_map_an_sample_table) ASSERT_EQ(di, set->getDataItem()); ASSERT_EQ("SomethingTable", set->getName()); - auto &ds = set->getValue(); + auto& ds = set->getValue(); ASSERT_EQ(3, ds.size()); - const auto &a = get(ds.find("a"_E)->m_value); + const auto& a = get(ds.find("a"_E)->m_value); ASSERT_EQ(2, a.size()); ASSERT_EQ(1, get(a.find("c"_C)->m_value)); ASSERT_EQ(3.0, get(a.find("n"_C)->m_value)); - const auto &b = get(ds.find("b"_E)->m_value); + const auto& b = get(ds.find("b"_E)->m_value); ASSERT_EQ(2, a.size()); ASSERT_EQ(2, get(b.find("d"_C)->m_value)); ASSERT_EQ(3, get(b.find("e"_C)->m_value)); - const auto &c = get(ds.find("c"_E)->m_value); + const auto& c = get(ds.find("c"_E)->m_value); ASSERT_EQ(2, c.size()); ASSERT_EQ("abc", get(c.find("x"_C)->m_value)); ASSERT_EQ("def", get(c.find("y"_C)->m_value)); @@ -479,7 +479,7 @@ TEST_F(DataItemMappingTest, should_handle_data_set_reset_trigger) ASSERT_EQ("SomethingDataSet", set->getName()); ASSERT_EQ("MANUAL", set->get("resetTriggered")); - auto &ds = set->getValue(); + auto& ds = set->getValue(); ASSERT_EQ(3, ds.size()); } @@ -497,7 +497,7 @@ TEST_F(DataItemMappingTest, should_handle_table_reset_trigger) ASSERT_TRUE(set); ASSERT_EQ("DAY", set->get("resetTriggered")); - auto &ds = set->getValue(); + auto& ds = set->getValue(); ASSERT_EQ(3, ds.size()); } @@ -575,7 +575,7 @@ TEST_F(DataItemMappingTest, continue_after_conversion_error) auto ts = makeTimestamped({"a", "test"s, "b", "1.23"s, "c", "program"s}); auto observations = (*m_mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -605,7 +605,7 @@ TEST_F(DataItemMappingTest, continue_after_conversion_error) TEST_F(DataItemMappingTest, version_23_condition_behavior_with_native_code) { auto di = makeDataItem({{"id", "a"s}, {"type", "POSITION"s}, {"category", "CONDITION"s}}); - auto *context = dynamic_cast(m_context->m_contract.get()); + auto* context = dynamic_cast(m_context->m_contract.get()); context->m_schemaVersion = SCHEMA_VERSION(2, 3); // ||||| @@ -629,7 +629,7 @@ TEST_F(DataItemMappingTest, version_23_condition_behavior_with_native_code) TEST_F(DataItemMappingTest, version_23_condition_behavior_with_condition_id) { auto di = makeDataItem({{"id", "a"s}, {"type", "POSITION"s}, {"category", "CONDITION"s}}); - auto *context = dynamic_cast(m_context->m_contract.get()); + auto* context = dynamic_cast(m_context->m_contract.get()); context->m_schemaVersion = SCHEMA_VERSION(2, 3); // ||||| @@ -653,7 +653,7 @@ TEST_F(DataItemMappingTest, version_23_condition_behavior_with_condition_id) TEST_F(DataItemMappingTest, version_23_condition_behavior_with_only_condition_id) { auto di = makeDataItem({{"id", "a"s}, {"type", "POSITION"s}, {"category", "CONDITION"s}}); - auto *context = dynamic_cast(m_context->m_contract.get()); + auto* context = dynamic_cast(m_context->m_contract.get()); context->m_schemaVersion = SCHEMA_VERSION(2, 3); // ||||| diff --git a/test_package/data_item_test.cpp b/test_package/data_item_test.cpp index c586f261..defd13c9 100644 --- a/test_package/data_item_test.cpp +++ b/test_package/data_item_test.cpp @@ -29,7 +29,7 @@ using namespace mtconnect::entity; using namespace mtconnect::device_model::data_item; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/data_set_test.cpp b/test_package/data_set_test.cpp index fc06fd19..1203d404 100644 --- a/test_package/data_set_test.cpp +++ b/test_package/data_set_test.cpp @@ -36,7 +36,7 @@ using namespace mtconnect::sink::rest_sink; using namespace mtconnect::buffer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -77,7 +77,7 @@ using namespace std::literals; using namespace chrono_literals; using namespace date::literals; -inline DataSetEntry operator""_E(const char *c, std::size_t) { return DataSetEntry(c); } +inline DataSetEntry operator""_E(const char* c, std::size_t) { return DataSetEntry(c); } TEST_F(DataSetTest, data_item_is_identified_as_data_set_representation) { @@ -170,7 +170,7 @@ TEST_F(DataSetTest, parser_with_big_data_set) using namespace std::filesystem; path p(TEST_RESOURCE_DIR "/big_data_set.txt"); auto size = std::filesystem::file_size(p); - char *buffer = (char *)malloc(size + 1); + char* buffer = (char*)malloc(size + 1); auto file = std::fopen(p.string().c_str(), "r"); size = std::fread(buffer, 1, size, file); buffer[size] = '\0'; @@ -480,7 +480,7 @@ TEST_F(DataSetTest, current_at_sequence_reconstructs_data_set_state_at_given_poi using namespace mtconnect::sink::rest_sink; m_agentTestHelper->addAdapter(); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); m_agentTestHelper->m_adapter->processData("TIME|vars|a=1 b=2 c=3"); @@ -575,12 +575,12 @@ TEST_F(DataSetTest, removed_keys_are_deleted_from_checkpoint_data_set) ASSERT_EQ(0, errors.size()); m_checkpoint->addObservation(ce2); - auto &ds = ce2->getValue(); + auto& ds = ce2->getValue(); ASSERT_TRUE(ds.find("a"_E)->m_removed); ASSERT_TRUE(ds.find("c"_E)->m_removed); auto ce3 = m_checkpoint->getObservation("v1"); - auto &map1 = ce3->getValue(); + auto& map1 = ce3->getValue(); ASSERT_EQ(3, map1.size()); ASSERT_EQ(2, get(map1.find("b"_E)->m_value)); @@ -781,7 +781,7 @@ TEST_F(DataSetTest, json_current_response_includes_data_set_entries_with_typed_v ASSERT_EQ(4_S, streams.size()); json stream; - for (auto &s : streams) + for (auto& s : streams) { auto id = s.at("/ComponentStream/componentId"_json_pointer); ASSERT_TRUE(id.is_string()); @@ -796,7 +796,7 @@ TEST_F(DataSetTest, json_current_response_includes_data_set_entries_with_typed_v auto events = stream.at("/ComponentStream/Events"_json_pointer); ASSERT_TRUE(events.is_array()); json offsets; - for (auto &o : events) + for (auto& o : events) { ASSERT_TRUE(o.is_object()); auto v = o.begin().key(); diff --git a/test_package/device_test.cpp b/test_package/device_test.cpp index 7b202b0b..0264556c 100644 --- a/test_package/device_test.cpp +++ b/test_package/device_test.cpp @@ -27,7 +27,7 @@ using namespace device_model; using namespace data_item; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -116,7 +116,7 @@ TEST_F(DeviceTest, data_items_are_added_to_device_and_retrievable_in_order) m_devA->addDataItem(data1, errors); m_devA->addDataItem(data2, errors); - const auto &items = m_devA->getDataItems(); + const auto& items = m_devA->getDataItems(); ASSERT_EQ(2, items->size()); ASSERT_TRUE(data1 == items->front()); diff --git a/test_package/duplicate_filter_test.cpp b/test_package/duplicate_filter_test.cpp index c268b8f8..b3df336f 100644 --- a/test_package/duplicate_filter_test.cpp +++ b/test_package/duplicate_filter_test.cpp @@ -42,7 +42,7 @@ using namespace std::literals; using namespace std::chrono_literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -51,9 +51,9 @@ int main(int argc, char *argv[]) class MockPipelineContract : public PipelineContract { public: - MockPipelineContract(std::map &items) : m_dataItems(items) {} - DevicePtr findDevice(const std::string &device) override { return nullptr; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + MockPipelineContract(std::map& items) : m_dataItems(items) {} + DevicePtr findDevice(const std::string& device) override { return nullptr; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_dataItems[name]; } @@ -68,15 +68,15 @@ class MockPipelineContract : public PipelineContract void deliverAssetCommand(entity::EntityPtr) override {} int32_t getSchemaVersion() const override { return IntDefaultSchemaVersion(); } void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return m_checkpoint.checkDuplicate(obs); } bool isValidating() const override { return false; } - std::map &m_dataItems; + std::map& m_dataItems; buffer::Checkpoint m_checkpoint; }; @@ -224,7 +224,7 @@ TEST_F(DuplicateFilterTest, test_condition_duplicates) m_mapper->bind(filter); filter->bind(make_shared(m_context)); - auto *contract = dynamic_cast(m_context->m_contract.get()); + auto* contract = dynamic_cast(m_context->m_contract.get()); makeDataItem({{"id", "c1"s}, {"type", "SYSTEM"s}, {"category", "CONDITION"s}}); { auto os = observe({"c1", "warning", "XXX", "100", "HIGH", "XXX Happened"}); diff --git a/test_package/embedded_ruby_test.cpp b/test_package/embedded_ruby_test.cpp index 1cc4c1dc..32e48f17 100644 --- a/test_package/embedded_ruby_test.cpp +++ b/test_package/embedded_ruby_test.cpp @@ -57,7 +57,7 @@ #endif // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -79,9 +79,9 @@ namespace { class MockPipelineContract : public PipelineContract { public: - MockPipelineContract(const Agent *agent) : m_agent(agent) {} - DevicePtr findDevice(const std::string &device) override { return nullptr; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + MockPipelineContract(const Agent* agent) : m_agent(agent) {} + DevicePtr findDevice(const std::string& device) override { return nullptr; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_agent->getDataItemForDevice(device, name); } @@ -94,11 +94,11 @@ namespace { int32_t getSchemaVersion() const override { return IntDefaultSchemaVersion(); } bool isValidating() const override { return false; } void deliverCommand(entity::EntityPtr c) override { m_command = c; } - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } - const Agent *m_agent; + const Agent* m_agent; ObservationPtr m_observation; entity::EntityPtr m_command; AssetPtr m_asset; @@ -117,7 +117,7 @@ namespace { m_context->m_contract = make_unique(m_config->getAgent()); } - void load(const char *file) + void load(const char* file) { string str("Devices = " TEST_RESOURCE_DIR "/samples/test_config.xml\n" @@ -160,7 +160,7 @@ namespace { for (int i = 0; i < size; i++) { auto pipeline = MRubyPtr::unwrap(mrb, values[i]); - ASSERT_NE(nullptr, dynamic_cast(pipeline)); + ASSERT_NE(nullptr, dynamic_cast(pipeline)); } } @@ -214,7 +214,7 @@ namespace { auto cent1 = MRubySharedPtr::unwrap(mrb, ent1); ASSERT_TRUE(cent1); - const DataSet &ds = cent1->getValue(); + const DataSet& ds = cent1->getValue(); ASSERT_EQ(3, ds.size()); ASSERT_EQ("value1", ds.get("string")); @@ -238,16 +238,16 @@ namespace { auto cent1 = MRubySharedPtr::unwrap(mrb, ent1); ASSERT_TRUE(cent1); - const DataSet &ds = cent1->getValue(); + const DataSet& ds = cent1->getValue(); ASSERT_EQ(2, ds.size()); - const auto &row1 = ds.get("row1"); + const auto& row1 = ds.get("row1"); ASSERT_EQ(2, row1.size()); ASSERT_EQ("text1", row1.get("string")); ASSERT_NEAR(1.0, row1.get("float"), 0.000001); - const auto &row2 = ds.get("row2"); + const auto& row2 = ds.get("row2"); ASSERT_EQ(2, row2.size()); ASSERT_EQ("text2", row2.get("string")); @@ -283,7 +283,7 @@ p $source auto di = m_config->getAgent()->getDataItemForDevice("LinuxCNC", "execution"); [[maybe_unused]] auto out = loopback->receive(di, "1"s); - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); ASSERT_TRUE(contract->m_observation); ASSERT_EQ("READY", contract->m_observation->getValue()); } @@ -314,7 +314,7 @@ p $source auto di = m_config->getAgent()->getDataItemForDevice("LinuxCNC", "execution"); [[maybe_unused]] auto out = loopback->receive(di, "1"s); - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); ASSERT_TRUE(contract->m_observation); ASSERT_EQ("READY", contract->m_observation->getValue()); } @@ -346,7 +346,7 @@ p $source loopback->getPipeline()->run(tokens); - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); ASSERT_TRUE(contract->m_observation); ASSERT_EQ(100.0, contract->m_observation->getValue()); ASSERT_EQ("Xact", contract->m_observation->getDataItem()->getName()); @@ -384,7 +384,7 @@ p $source loopback->getPipeline()->run(std::move(entity)); - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); ASSERT_TRUE(contract->m_observation); ASSERT_EQ("G0X100Y100", contract->m_observation->getValue()); ASSERT_EQ("block", contract->m_observation->getDataItem()->getName()); @@ -417,7 +417,7 @@ p $source loopback->getPipeline()->run(std::move(entity)); - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); ASSERT_TRUE(contract->m_observation); auto cond = dynamic_pointer_cast(contract->m_observation); diff --git a/test_package/entity_parser_test.cpp b/test_package/entity_parser_test.cpp index e7a1a6b0..cc50a064 100644 --- a/test_package/entity_parser_test.cpp +++ b/test_package/entity_parser_test.cpp @@ -38,7 +38,7 @@ using namespace mtconnect; using namespace mtconnect::entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -371,14 +371,14 @@ TEST_F(EntityParserTest, should_parse_tables) auto entity = parser.parse(root, doc, errors); ASSERT_EQ("Root", entity->getName()); - const DataSet &set = entity->get("Table"); - const auto &e1 = set.get("A"); + const DataSet& set = entity->get("Table"); + const auto& e1 = set.get("A"); ASSERT_EQ("abc", e1.get("text")); ASSERT_EQ(101, e1.get("int")); ASSERT_EQ(50.5, e1.get("double")); - const auto &e2 = set.get("B"); + const auto& e2 = set.get("B"); ASSERT_EQ("def", e2.get("text2")); ASSERT_EQ(102, e2.get("int2")); diff --git a/test_package/entity_printer_test.cpp b/test_package/entity_printer_test.cpp index 211da61c..4ef3842f 100644 --- a/test_package/entity_printer_test.cpp +++ b/test_package/entity_printer_test.cpp @@ -41,7 +41,7 @@ using namespace mtconnect::entity; using namespace std::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/entity_test.cpp b/test_package/entity_test.cpp index ce2b13bd..0a141aa6 100644 --- a/test_package/entity_test.cpp +++ b/test_package/entity_test.cpp @@ -35,7 +35,7 @@ using namespace mtconnect; using namespace mtconnect::entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -863,21 +863,21 @@ TEST_F(EntityTest, entities_should_merge_entity_list_with_new_item) auto v1 = createEnt("woof"s, 0_i64); ASSERT_TRUE(v1); - auto const &list1 = v1->getList("seconds"); + auto const& list1 = v1->getList("seconds"); ASSERT_TRUE(list1); EXPECT_EQ(1, list1->size()); auto v2 = createEnt("meow"s, 1_i64); ASSERT_TRUE(v2); - auto const &list2 = v2->getList("seconds"); + auto const& list2 = v2->getList("seconds"); ASSERT_TRUE(list2); EXPECT_EQ(2, list2->size()); ASSERT_TRUE(v1->reviseTo(v2)); // EXPECT_EQ(2, list1->size()); - auto const &list3 = v1->getList("seconds"); + auto const& list3 = v1->getList("seconds"); EXPECT_EQ(2, list3->size()); auto it = list3->begin(); diff --git a/test_package/file_asset_test.cpp b/test_package/file_asset_test.cpp index 85068ecb..be035940 100644 --- a/test_package/file_asset_test.cpp +++ b/test_package/file_asset_test.cpp @@ -45,7 +45,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -86,7 +86,7 @@ TEST_F(FileAssetTest, minimal_file_archetype_is_parsed) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("F1", asset->getAssetId()); @@ -144,7 +144,7 @@ TEST_F(FileAssetTest, minimal_file_asset_is_parsed) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); EXPECT_EQ("F1", asset->getAssetId()); diff --git a/test_package/file_cache_test.cpp b/test_package/file_cache_test.cpp index 736a0993..964b78ef 100644 --- a/test_package/file_cache_test.cpp +++ b/test_package/file_cache_test.cpp @@ -41,7 +41,7 @@ using namespace mtconnect; using namespace mtconnect::sink::rest_sink; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -192,7 +192,7 @@ TEST_F(FileCacheTest, file_cache_should_compress_file_async) } } -static inline void touch(const std::filesystem::path &file) +static inline void touch(const std::filesystem::path& file) { namespace fs = std::filesystem; namespace ch = std::chrono; @@ -267,9 +267,9 @@ TEST_F(FileCacheTest, should_find_mtconnect_schema_files_for_xsd_and_json) auto files = m_cache->registerDirectory("/myschemas", PROJECT_ROOT_DIR "/schemas", "2.7"); ASSERT_EQ(8, files.size()); - auto exists = [&files](const std::string &uri) -> std::optional { + auto exists = [&files](const std::string& uri) -> std::optional { auto it = std::find_if(files.begin(), files.end(), - [&uri](const MTConnectSchema &s) { return s.m_uri == uri; }); + [&uri](const MTConnectSchema& s) { return s.m_uri == uri; }); if (it != files.end()) { return *it; diff --git a/test_package/fixture_test.cpp b/test_package/fixture_test.cpp index adf83124..de8c351b 100644 --- a/test_package/fixture_test.cpp +++ b/test_package/fixture_test.cpp @@ -48,7 +48,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -94,7 +94,7 @@ TEST_F(FixtureTest, minimal_fixture_definition) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("7ae770f0-c11e-013a-c34c-4e7f553bbb76", asset->getAssetId()); diff --git a/test_package/image_file_test.cpp b/test_package/image_file_test.cpp index dc16dd2b..2e723e1a 100644 --- a/test_package/image_file_test.cpp +++ b/test_package/image_file_test.cpp @@ -38,7 +38,7 @@ using namespace mtconnect::source::adapter; using namespace entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -57,7 +57,7 @@ class ImageFileTest : public testing::Test void TearDown() override { m_agentTestHelper.reset(); } - Adapter *m_adapter {nullptr}; + Adapter* m_adapter {nullptr}; std::string m_agentId; DevicePtr m_device; std::unique_ptr m_agentTestHelper; @@ -67,10 +67,10 @@ TEST_F(ImageFileTest, should_parse_configuration_with_image_file) { ASSERT_NE(nullptr, m_device); - auto &clc = m_device->get("Configuration"); + auto& clc = m_device->get("Configuration"); ASSERT_TRUE(clc); - const auto &ifs = clc->getList("ImageFiles"); + const auto& ifs = clc->getList("ImageFiles"); ASSERT_TRUE(ifs); ASSERT_EQ(2, ifs->size()); diff --git a/test_package/json_device_parser_test.cpp b/test_package/json_device_parser_test.cpp index 0fc41d4a..32385e1e 100644 --- a/test_package/json_device_parser_test.cpp +++ b/test_package/json_device_parser_test.cpp @@ -34,7 +34,7 @@ using namespace mtconnect::device_model; using namespace mtconnect::device_model::data_item; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -495,7 +495,7 @@ TEST_F(JsonDeviceParserTest, should_parse_v1_device_with_description) auto device = parser.parseDevice(doc); ASSERT_TRUE(device); - auto &description = device->get("Description"); + auto& description = device->get("Description"); ASSERT_TRUE(description); ASSERT_EQ("ACME", description->get("manufacturer")); ASSERT_EQ("X100", description->get("model")); diff --git a/test_package/json_helper.hpp b/test_package/json_helper.hpp index 02e5ba07..4dcc4bfc 100644 --- a/test_package/json_helper.hpp +++ b/test_package/json_helper.hpp @@ -22,13 +22,13 @@ constexpr inline nlohmann::json::size_type operator""_S(unsigned long long v) return static_cast(v); } -inline std::string operator""_S(const char *v, std::size_t) { return std::string(v); } +inline std::string operator""_S(const char* v, std::size_t) { return std::string(v); } -static inline nlohmann::json find(nlohmann::json &array, const char *path, const char *value) +static inline nlohmann::json find(nlohmann::json& array, const char* path, const char* value) { nlohmann::json::json_pointer pointer(path); nlohmann::json res; - for (auto &item : array) + for (auto& item : array) { if (item.at(pointer).get() == value) { diff --git a/test_package/json_mapping_test.cpp b/test_package/json_mapping_test.cpp index 7b23f936..e55a9f28 100644 --- a/test_package/json_mapping_test.cpp +++ b/test_package/json_mapping_test.cpp @@ -39,7 +39,7 @@ using namespace data_item; using namespace std; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -48,11 +48,11 @@ int main(int argc, char *argv[]) class MockPipelineContract : public PipelineContract { public: - MockPipelineContract(std::map &items, std::map &devices) + MockPipelineContract(std::map& items, std::map& devices) : m_dataItems(items), m_devices(devices) {} - DevicePtr findDevice(const std::string &name) override { return m_devices[name]; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DevicePtr findDevice(const std::string& name) override { return m_devices[name]; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_dataItems[name]; } @@ -63,14 +63,14 @@ class MockPipelineContract : public PipelineContract void deliverDevice(DevicePtr) override {} void deliverAssetCommand(entity::EntityPtr) override {} void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } int32_t getSchemaVersion() const override { return SCHEMA_VERSION(2, 3); }; bool isValidating() const override { return false; } - std::map &m_dataItems; - std::map &m_devices; + std::map& m_dataItems; + std::map& m_devices; }; class JsonMappingTest : public testing::Test @@ -90,7 +90,7 @@ class JsonMappingTest : public testing::Test m_devices.clear(); } - DataItemPtr makeDataItem(const std::string &device, const Properties &props) + DataItemPtr makeDataItem(const std::string& device, const Properties& props) { auto dev = m_devices.find(device); if (dev == m_devices.end()) @@ -105,7 +105,7 @@ class JsonMappingTest : public testing::Test if (errors.size() > 0) { cerr << "Errors occurred during make data item" << endl; - for (auto &e : errors) + for (auto& e : errors) { cerr << " " << e->getEntity() << ": " << e->what() << endl; } @@ -118,7 +118,7 @@ class JsonMappingTest : public testing::Test return di; } - DevicePtr makeDevice(const std::string &name, const Properties &props) + DevicePtr makeDevice(const std::string& name, const Properties& props) { ErrorList errors; Properties ps(props); @@ -135,7 +135,7 @@ class JsonMappingTest : public testing::Test std::map m_devices; }; -inline DataSetEntry operator""_E(const char *c, std::size_t) { return DataSetEntry(c); } +inline DataSetEntry operator""_E(const char* c, std::size_t) { return DataSetEntry(c); } using namespace date::literals; /// @test verify the json mapper can map an object with a timestamp and a series of observations @@ -628,7 +628,7 @@ TEST_F(JsonMappingTest, should_parse_data_sets) ASSERT_EQ("VariableDataSet", obs->getName()); ASSERT_EQ("a", obs->getDataItem()->getId()); - auto &set1 = obs->getDataSet(); + auto& set1 = obs->getDataSet(); ASSERT_EQ(3, set1.size()); auto dsi = set1.begin(); @@ -649,7 +649,7 @@ TEST_F(JsonMappingTest, should_parse_data_sets) ASSERT_EQ("VariableDataSet", obs->getName()); ASSERT_EQ("a", obs->getDataItem()->getId()); - auto &set2 = obs->getDataSet(); + auto& set2 = obs->getDataSet(); ASSERT_EQ(3, set2.size()); ASSERT_EQ("NEW", obs->get("resetTriggered")); @@ -672,7 +672,7 @@ TEST_F(JsonMappingTest, should_parse_data_sets) ASSERT_EQ("VariableDataSet", obs->getName()); ASSERT_EQ("a", obs->getDataItem()->getId()); - auto &set3 = obs->getDataSet(); + auto& set3 = obs->getDataSet(); ASSERT_EQ(3, set3.size()); dsi = set3.begin(); @@ -743,14 +743,14 @@ TEST_F(JsonMappingTest, should_parse_tables) ASSERT_EQ("WorkOffsetsTable", obs->getName()); ASSERT_EQ("a", obs->getDataItem()->getId()); - auto &set1 = obs->getDataSet(); + auto& set1 = obs->getDataSet(); ASSERT_EQ(2, set1.size()); auto dsi = set1.begin(); ASSERT_EQ("r1", dsi->m_key); ASSERT_TRUE(holds_alternative(dsi->m_value)); - const auto &row1 = get(dsi->m_value); + const auto& row1 = get(dsi->m_value); ASSERT_EQ(1, row1.size()); auto ri = row1.begin(); @@ -758,7 +758,7 @@ TEST_F(JsonMappingTest, should_parse_tables) ASSERT_EQ(123.45, get(ri->m_value)); dsi++; - const auto &row2 = get(dsi->m_value); + const auto& row2 = get(dsi->m_value); ASSERT_EQ(2, row2.size()); ri = row2.begin(); @@ -775,7 +775,7 @@ TEST_F(JsonMappingTest, should_parse_tables) ASSERT_EQ("WorkOffsetsTable", obs->getName()); ASSERT_EQ("a", obs->getDataItem()->getId()); - auto &set2 = obs->getDataSet(); + auto& set2 = obs->getDataSet(); ASSERT_EQ(2, set2.size()); ASSERT_EQ("NEW", obs->get("resetTriggered")); @@ -785,7 +785,7 @@ TEST_F(JsonMappingTest, should_parse_tables) ASSERT_EQ("r1", dsi->m_key); ASSERT_TRUE(holds_alternative(dsi->m_value)); - const auto &row3 = get(dsi->m_value); + const auto& row3 = get(dsi->m_value); ASSERT_EQ(2, row3.size()); ri = row3.begin(); diff --git a/test_package/json_parser_test.cpp b/test_package/json_parser_test.cpp index 50b45cbc..e9dbc2ff 100644 --- a/test_package/json_parser_test.cpp +++ b/test_package/json_parser_test.cpp @@ -37,7 +37,7 @@ using namespace mtconnect; using namespace mtconnect::entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/json_printer_asset_test.cpp b/test_package/json_printer_asset_test.cpp index a7ff58fe..9573ba2a 100644 --- a/test_package/json_printer_asset_test.cpp +++ b/test_package/json_printer_asset_test.cpp @@ -48,7 +48,7 @@ using namespace mtconnect::buffer; using namespace mtconnect::asset; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -74,11 +74,11 @@ class JsonPrinterAssetTest : public testing::Test m_parser.reset(); } - AssetPtr parseAsset(const std::string &xml, entity::ErrorList &errors) + AssetPtr parseAsset(const std::string& xml, entity::ErrorList& errors) { auto entity = m_parser->parse(Asset::getRoot(), xml, errors); AssetPtr asset; - for (auto &error : errors) + for (auto& error : errors) { cout << error->what() << endl; } diff --git a/test_package/json_printer_error_test.cpp b/test_package/json_printer_error_test.cpp index 9a50b371..9df20f42 100644 --- a/test_package/json_printer_error_test.cpp +++ b/test_package/json_printer_error_test.cpp @@ -43,7 +43,7 @@ using namespace mtconnect::sink::rest_sink; using json = nlohmann::json; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/json_printer_probe_test.cpp b/test_package/json_printer_probe_test.cpp index b84793f2..e06bd463 100644 --- a/test_package/json_printer_probe_test.cpp +++ b/test_package/json_printer_probe_test.cpp @@ -45,7 +45,7 @@ using namespace mtconnect; using json = nlohmann::json; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/json_printer_stream_test.cpp b/test_package/json_printer_stream_test.cpp index 148a318b..998d0536 100644 --- a/test_package/json_printer_stream_test.cpp +++ b/test_package/json_printer_stream_test.cpp @@ -46,7 +46,7 @@ using namespace mtconnect::observation; using namespace mtconnect::entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -71,9 +71,9 @@ class JsonPrinterStreamTest : public testing::Test m_printer.reset(); } - DataItemPtr getDataItem(const char *name) + DataItemPtr getDataItem(const char* name) { - for (auto &device : m_devices) + for (auto& device : m_devices) { auto di = device->getDeviceDataItem(name); if (di) @@ -82,7 +82,7 @@ class JsonPrinterStreamTest : public testing::Test return nullptr; } - void addObservationToCheckpoint(Checkpoint &checkpoint, const char *name, uint64_t sequence, + void addObservationToCheckpoint(Checkpoint& checkpoint, const char* name, uint64_t sequence, Properties props, Timestamp time = chrono::system_clock::now(), std::optional duration = nullopt) { @@ -99,7 +99,7 @@ class JsonPrinterStreamTest : public testing::Test checkpoint.addObservation(event); } - void addObservationToList(ObservationList &list, const char *name, uint64_t sequence, + void addObservationToList(ObservationList& list, const char* name, uint64_t sequence, Properties props, Timestamp time = chrono::system_clock::now(), std::optional duration = nullopt) { @@ -130,7 +130,7 @@ Properties operator""_value(unsigned long long value) Properties operator""_value(long double value) { return Properties {{"VALUE", double(value)}}; } -Properties operator""_value(const char *value, size_t s) +Properties operator""_value(const char* value, size_t s) { return Properties {{"VALUE", string(value)}}; } diff --git a/test_package/json_printer_test.cpp b/test_package/json_printer_test.cpp index cdb14d81..e53e4ad5 100644 --- a/test_package/json_printer_test.cpp +++ b/test_package/json_printer_test.cpp @@ -45,7 +45,7 @@ using namespace mtconnect; using namespace mtconnect::entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/kinematics_test.cpp b/test_package/kinematics_test.cpp index 08730e87..7cf13901 100644 --- a/test_package/kinematics_test.cpp +++ b/test_package/kinematics_test.cpp @@ -36,10 +36,10 @@ using namespace std; using namespace mtconnect; using namespace mtconnect::entity; -inline DataSetEntry operator""_E(const char *c, std::size_t) { return DataSetEntry(c); } +inline DataSetEntry operator""_E(const char* c, std::size_t) { return DataSetEntry(c); } // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -71,7 +71,7 @@ TEST_F(KinematicsTest, z_axis_kinematics_motion_attributes_are_parsed_correctly) auto linear = m_device->getComponentById("z"); ASSERT_TRUE(linear); - auto &ent = linear->get("Configuration"); + auto& ent = linear->get("Configuration"); ASSERT_TRUE(ent); auto motion = ent->get("Motion"); @@ -102,7 +102,7 @@ TEST_F(KinematicsTest, c_axis_rotary_kinematics_motion_is_parsed_with_transforma ASSERT_NE(nullptr, m_device); auto rot = m_device->getComponentById("c"); - auto &ent = rot->get("Configuration"); + auto& ent = rot->get("Configuration"); ASSERT_TRUE(ent); auto motion = ent->get("Motion"); @@ -263,7 +263,7 @@ TEST_F(KinematicsTest, should_parse_kinematic_data_sets) ASSERT_NE(nullptr, m_device); auto rot = m_device->getComponentById("c"); - auto &ent = rot->get("Configuration"); + auto& ent = rot->get("Configuration"); ASSERT_TRUE(ent); auto motion = ent->get("Motion"); diff --git a/test_package/message_mapping_test.cpp b/test_package/message_mapping_test.cpp index d084982b..6a248b4c 100644 --- a/test_package/message_mapping_test.cpp +++ b/test_package/message_mapping_test.cpp @@ -27,8 +27,8 @@ #include "mtconnect/pipeline/pipeline_context.hpp" // adapter_pipeline.hpp defines source::adapter::Handler, and message_mapper.hpp // references bare `string`/`Handler`, so both must be visible before it is parsed. -#include "mtconnect/source/adapter/adapter_pipeline.hpp" #include "mtconnect/pipeline/message_mapper.hpp" +#include "mtconnect/source/adapter/adapter_pipeline.hpp" using namespace std; using namespace mtconnect; @@ -39,7 +39,7 @@ using namespace device_model; using namespace data_item; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -48,11 +48,11 @@ int main(int argc, char *argv[]) class MockPipelineContract : public PipelineContract { public: - MockPipelineContract(std::map &items, std::map &devices) + MockPipelineContract(std::map& items, std::map& devices) : m_dataItems(items), m_devices(devices) {} - DevicePtr findDevice(const std::string &name) override { return m_devices[name]; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DevicePtr findDevice(const std::string& name) override { return m_devices[name]; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_dataItems[name]; } @@ -63,14 +63,14 @@ class MockPipelineContract : public PipelineContract void deliverDevice(DevicePtr) override {} void deliverAssetCommand(entity::EntityPtr) override {} void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } int32_t getSchemaVersion() const override { return IntDefaultSchemaVersion(); } bool isValidating() const override { return false; } - std::map &m_dataItems; - std::map &m_devices; + std::map& m_dataItems; + std::map& m_devices; }; /// @brief records every entity forwarded to it so tests can inspect what the @@ -80,7 +80,7 @@ class CaptureTransform : public Transform { public: CaptureTransform() : Transform("CaptureTransform") { m_guard = TypeGuard(RUN); } - entity::EntityPtr operator()(entity::EntityPtr &&entity) override + entity::EntityPtr operator()(entity::EntityPtr&& entity) override { m_last = entity; m_count++; @@ -109,13 +109,13 @@ class MessageMappingTest : public testing::Test m_devices.clear(); } - DataItemPtr makeDataItem(const std::string &device, const Properties &props) + DataItemPtr makeDataItem(const std::string& device, const Properties& props) { auto dev = m_devices.find(device); EXPECT_NE(m_devices.end(), dev) << "Cannot find device: " << device; if (dev == m_devices.end()) return nullptr; - + Properties ps(props); ErrorList errors; auto di = DataItem::make(ps, errors); @@ -124,7 +124,7 @@ class MessageMappingTest : public testing::Test return di; } - DevicePtr makeDevice(const std::string &name, const Properties &props) + DevicePtr makeDevice(const std::string& name, const Properties& props) { ErrorList errors; Properties ps(props); @@ -134,7 +134,7 @@ class MessageMappingTest : public testing::Test return d; } - std::shared_ptr makeMessage(const Properties &props) + std::shared_ptr makeMessage(const Properties& props) { Properties ps(props); return make_shared("DataMessage", ps); diff --git a/test_package/mqtt_adapter_test.cpp b/test_package/mqtt_adapter_test.cpp index 5f3e7c61..80a6ef5e 100644 --- a/test_package/mqtt_adapter_test.cpp +++ b/test_package/mqtt_adapter_test.cpp @@ -42,7 +42,7 @@ namespace asio = boost::asio; using namespace std::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -52,8 +52,8 @@ class MockPipelineContract : public PipelineContract { public: MockPipelineContract(int32_t schemaVersion) : m_schemaVersion(schemaVersion) {} - DevicePtr findDevice(const std::string &) override { return nullptr; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DevicePtr findDevice(const std::string&) override { return nullptr; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return nullptr; } @@ -65,9 +65,9 @@ class MockPipelineContract : public PipelineContract int32_t getSchemaVersion() const override { return m_schemaVersion; } void deliverAssetCommand(entity::EntityPtr) override {} void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } bool isValidating() const override { return false; } int32_t m_schemaVersion; diff --git a/test_package/mqtt_isolated_test.cpp b/test_package/mqtt_isolated_test.cpp index facb79ba..b30e123c 100644 --- a/test_package/mqtt_isolated_test.cpp +++ b/test_package/mqtt_isolated_test.cpp @@ -52,7 +52,7 @@ const string ServerDhFile {TEST_RESOURCE_DIR "/dh2048.pem"}; const string ClientCA(TEST_RESOURCE_DIR "/clientca.crt"); // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -96,7 +96,7 @@ class MqttIsolatedUnitTest : public testing::Test } } - void createServer(const ConfigOptions &options) + void createServer(const ConfigOptions& options) { bool withTlsOption = IsOptionSet(options, configuration::MqttTls); @@ -113,7 +113,7 @@ class MqttIsolatedUnitTest : public testing::Test } template - bool waitFor(const chrono::duration &time, function pred) + bool waitFor(const chrono::duration& time, function pred) { boost::asio::steady_timer timer(m_agentTestHelper->m_ioContext); timer.expires_after(time); @@ -147,7 +147,7 @@ class MqttIsolatedUnitTest : public testing::Test } } - void createClient(const ConfigOptions &options, unique_ptr &&handler, + void createClient(const ConfigOptions& options, unique_ptr&& handler, const std::optional willTopic = std::nullopt, const std::optional willPayload = std::nullopt) { @@ -253,7 +253,7 @@ TEST_F(MqttIsolatedUnitTest, mqtt_tcp_client_should_receive_loopback_publication client->set_suback_handler( [&client, &pid_sub1](std::uint16_t packet_id, std::vector results) { std::cout << "suback received. packet_id: " << packet_id << std::endl; - for (auto const &e : results) + for (auto const& e : results) { std::cout << "subscribe result: " << e << std::endl; } @@ -425,7 +425,7 @@ TEST_F(MqttIsolatedUnitTest, mqtt_tcp_client_authenticates_with_credentials) client->set_clean_session(true); client->set_keep_alive_sec(30); - MqttAuthorization *mqttAuct = new MqttAuthorization(options); + MqttAuthorization* mqttAuct = new MqttAuthorization(options); MqttTopicPermission permission = mqttAuct->getPermissionsForClient("mqtt_tcp_client_cpp/topic1"); client->set_connack_handler([&](bool sp, mqtt::connect_return_code connack_return_code) { @@ -436,7 +436,7 @@ TEST_F(MqttIsolatedUnitTest, mqtt_tcp_client_authenticates_with_credentials) { pid_sub1 = client->acquire_unique_packet_id(); - MqttAuthentication *mqttAuth = new MqttAuthentication(options); + MqttAuthentication* mqttAuth = new MqttAuthentication(options); if (!mqttAuth->checkCredentials()) { @@ -467,7 +467,7 @@ TEST_F(MqttIsolatedUnitTest, mqtt_tcp_client_authenticates_with_credentials) [&client, &pid_sub1, &permission](std::uint16_t packet_id, std::vector results) { std::cout << "suback received. packet_id: " << packet_id << std::endl; - for (auto const &e : results) + for (auto const& e : results) { std::cout << "subscribe result: " << e << std::endl; } diff --git a/test_package/mqtt_sink_test.cpp b/test_package/mqtt_sink_test.cpp index d80ac03e..83789d79 100644 --- a/test_package/mqtt_sink_test.cpp +++ b/test_package/mqtt_sink_test.cpp @@ -43,7 +43,7 @@ using namespace mtconnect::configuration; using namespace mtconnect::mqtt_client; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -101,7 +101,7 @@ class MqttSinkTest : public testing::Test m_agentTestHelper->getAgent()->start(); } - void createServer(const ConfigOptions &options) + void createServer(const ConfigOptions& options) { using namespace mtconnect::configuration; ConfigOptions opts(options); @@ -116,7 +116,7 @@ class MqttSinkTest : public testing::Test } template - bool waitFor(const chrono::duration &time, function pred) + bool waitFor(const chrono::duration& time, function pred) { boost::asio::steady_timer timer(m_agentTestHelper->m_ioContext); timer.expires_after(time); @@ -150,7 +150,7 @@ class MqttSinkTest : public testing::Test } } - void createClient(const ConfigOptions &options, unique_ptr &&handler) + void createClient(const ConfigOptions& options, unique_ptr&& handler) { ConfigOptions opts(options); MergeOptions(opts, {{MqttHost, "127.0.0.1"s}, @@ -211,7 +211,7 @@ TEST_F(MqttSinkTest, mqtt_sink_publishes_probe_response) auto handler = make_unique(); bool gotDevice = false; handler->m_receive = [&gotDevice, &parser](std::shared_ptr client, - const std::string &topic, const std::string &payload) { + const std::string& topic, const std::string& payload) { EXPECT_EQ("MTConnect/Probe/000", topic); ErrorList list; @@ -251,7 +251,7 @@ TEST_F(MqttSinkTest, mqtt_sink_publishes_sample_on_data_change) bool gotSample = false; bool first = true; handler->m_receive = [&gotSample, &first](std::shared_ptr client, - const std::string &topic, const std::string &payload) { + const std::string& topic, const std::string& payload) { if (first) { first = false; @@ -294,8 +294,8 @@ TEST_F(MqttSinkTest, mqtt_sink_publishes_current_on_connection) auto handler = make_unique(); bool gotCurrent = false; - handler->m_receive = [&gotCurrent](std::shared_ptr client, const std::string &topic, - const std::string &payload) { + handler->m_receive = [&gotCurrent](std::shared_ptr client, const std::string& topic, + const std::string& payload) { EXPECT_EQ("MTConnect/Current/000", topic); auto jdoc = json::parse(payload); @@ -332,7 +332,7 @@ TEST_F(MqttSinkTest, mqtt_sink_publishes_probe_with_uuid_first_in_topic) auto handler = make_unique(); bool gotDevice = false; handler->m_receive = [&gotDevice, &parser](std::shared_ptr client, - const std::string &topic, const std::string &payload) { + const std::string& topic, const std::string& payload) { EXPECT_EQ("MTConnect/000/Probe", topic); ErrorList list; @@ -371,7 +371,7 @@ TEST_F(MqttSinkTest, mqtt_sink_publishes_probe_without_device_in_topic) auto handler = make_unique(); bool gotDevice = false; handler->m_receive = [&gotDevice, &parser](std::shared_ptr client, - const std::string &topic, const std::string &payload) { + const std::string& topic, const std::string& payload) { EXPECT_EQ("MTConnect/Probe/000", topic); ErrorList list; @@ -413,8 +413,8 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_agent_device) auto handler = make_unique(); bool gotDevice = false; handler->m_receive = [&gotDevice, &parser, &agent_topic, &ad](std::shared_ptr client, - const std::string &topic, - const std::string &payload) { + const std::string& topic, + const std::string& payload) { EXPECT_EQ(agent_topic, topic); gotDevice = true; }; diff --git a/test_package/mtconnect_xml_transform_test.cpp b/test_package/mtconnect_xml_transform_test.cpp index 6f3c220e..fdd5256a 100644 --- a/test_package/mtconnect_xml_transform_test.cpp +++ b/test_package/mtconnect_xml_transform_test.cpp @@ -34,7 +34,7 @@ using namespace std; using namespace std::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -44,8 +44,8 @@ class MockPipelineContract : public PipelineContract { public: MockPipelineContract(DevicePtr device) : m_device(device) {} - DevicePtr findDevice(const std::string &) override { return m_device; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DevicePtr findDevice(const std::string&) override { return m_device; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_device->getDeviceDataItem(name); } @@ -57,9 +57,9 @@ class MockPipelineContract : public PipelineContract void deliverDevice(DevicePtr) override {} void deliverAssetCommand(entity::EntityPtr) override {} void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } bool isValidating() const override { return false; } DevicePtr m_device; @@ -122,7 +122,7 @@ TEST_F(MTConnectXmlTransformTest, should_return_errors) EXPECT_THROW((*m_xform)(std::move(entity)), std::system_error); ASSERT_EQ(1, m_feedback.m_errors.size()); - auto &error = m_feedback.m_errors.front(); + auto& error = m_feedback.m_errors.front(); ASSERT_EQ("OUT_OF_RANGE", error.m_code); ASSERT_EQ("'at' must be greater than 4871368", error.m_message); } diff --git a/test_package/observation_test.cpp b/test_package/observation_test.cpp index c55ebadd..554b1ccc 100644 --- a/test_package/observation_test.cpp +++ b/test_package/observation_test.cpp @@ -45,7 +45,7 @@ using namespace date::literals; using namespace nlohmann; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -96,13 +96,13 @@ class ObservationTest : public testing::Test pipeline::ConvertSample m_converter; // Helper to test values - void testValueHelper(std::map &attributes, const std::string &units, - const std::string &nativeUnits, float expected, const double value, - const char *file, int line) + void testValueHelper(std::map& attributes, const std::string& units, + const std::string& nativeUnits, float expected, const double value, + const char* file, int line) { ErrorList errors; Properties ps; - for (auto &p : attributes) + for (auto& p : attributes) ps.emplace(p.first, p.second); ps["nativeUnits"] = nativeUnits; ps["units"] = units; @@ -278,7 +278,7 @@ TEST_F(ObservationTest, should_treat_events_with_non_count_units_as_doubles) ASSERT_TRUE(dynamic_pointer_cast(event)); ASSERT_EQ(0, errors.size()); - auto &value = event->getValue(); + auto& value = event->getValue(); ASSERT_TRUE(holds_alternative(value)); ASSERT_EQ(123.555, get(value)); @@ -319,7 +319,7 @@ TEST_F(ObservationTest, should_treat_events_with_count_as_integer) ASSERT_TRUE(dynamic_pointer_cast(event)); ASSERT_EQ(0, errors.size()); - auto &value = event->getValue(); + auto& value = event->getValue(); ASSERT_TRUE(holds_alternative(value)); ASSERT_EQ(123.0, get(value)); @@ -363,10 +363,10 @@ TEST_F(ObservationTest, should_use_three_space_sample_for_3_space_events) ASSERT_TRUE(dynamic_pointer_cast(event)); ASSERT_EQ(0, errors.size()); - auto &value = event->getValue(); + auto& value = event->getValue(); ASSERT_TRUE(holds_alternative(value)); - auto &vector = get(value); + auto& vector = get(value); ASSERT_EQ(3, vector.size()); ASSERT_EQ(1.2, vector[0]); ASSERT_EQ(2.3, vector[1]); @@ -418,7 +418,7 @@ TEST_F(ObservationTest, should_represent_inf_values_in_json_correctly) ASSERT_TRUE(dynamic_pointer_cast(sample)); ASSERT_EQ(0, errors.size()); - auto &value = sample->getValue(); + auto& value = sample->getValue(); ASSERT_TRUE(holds_alternative(value)); ASSERT_TRUE(std::isinf(get(value))); ASSERT_FALSE(std::signbit(get(value))); @@ -462,7 +462,7 @@ TEST_F(ObservationTest, should_represent_nan_values_in_json_correctly) ASSERT_TRUE(dynamic_pointer_cast(sample)); ASSERT_EQ(0, errors.size()); - auto &value = sample->getValue(); + auto& value = sample->getValue(); ASSERT_TRUE(holds_alternative(value)); ASSERT_TRUE(std::isnan(get(value))); @@ -505,7 +505,7 @@ TEST_F(ObservationTest, should_represent_negative_inf_values_in_json_correctly) ASSERT_TRUE(dynamic_pointer_cast(sample)); ASSERT_EQ(0, errors.size()); - auto &value = sample->getValue(); + auto& value = sample->getValue(); ASSERT_TRUE(holds_alternative(value)); ASSERT_TRUE(std::isinf(get(value))); ASSERT_TRUE(std::signbit(get(value))); diff --git a/test_package/observation_validation_test.cpp b/test_package/observation_validation_test.cpp index b54f85b7..49bb5cb1 100644 --- a/test_package/observation_validation_test.cpp +++ b/test_package/observation_validation_test.cpp @@ -43,7 +43,7 @@ using namespace date::literals; using namespace std::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -52,11 +52,11 @@ int main(int argc, char *argv[]) class MockPipelineContract : public PipelineContract { public: - MockPipelineContract(int32_t schemaVersion, DataItemPtr &dataItem) + MockPipelineContract(int32_t schemaVersion, DataItemPtr& dataItem) : m_schemaVersion(schemaVersion), m_dataItem(dataItem) {} - DevicePtr findDevice(const std::string &) override { return m_device; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DevicePtr findDevice(const std::string&) override { return m_device; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_dataItem; } @@ -69,12 +69,12 @@ class MockPipelineContract : public PipelineContract bool isValidating() const override { return m_validation; } void deliverAssetCommand(entity::EntityPtr) override {} void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } int32_t m_schemaVersion; - DataItemPtr &m_dataItem; + DataItemPtr& m_dataItem; DevicePtr m_device; bool m_validation {true}; }; @@ -179,7 +179,7 @@ TEST_F(ObservationValidationTest, should_not_set_deprecated_flag_when_deprecated m_dataItem = DataItem::make({{"id", "exec"s}, {"category", "EVENT"s}, {"type", "EXECUTION"s}}, errors); - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); contract->m_schemaVersion = SCHEMA_VERSION(1, 3); auto event = Observation::make(m_dataItem, {{"VALUE", "PROGRAM_OPTIONAL_STOP"s}}, m_time, errors); @@ -235,7 +235,7 @@ TEST_F(ObservationValidationTest, should_be_invalid_if_entry_has_not_been_introd m_dataItem = DataItem::make({{"id", "exec"s}, {"category", "EVENT"s}, {"type", "EXECUTION"s}}, errors); - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); contract->m_schemaVersion = SCHEMA_VERSION(1, 4); auto event = Observation::make(m_dataItem, {{"VALUE", "WAIT"s}}, m_time, errors); @@ -248,7 +248,7 @@ TEST_F(ObservationValidationTest, should_be_invalid_if_entry_has_not_been_introd TEST_F(ObservationValidationTest, should_validate_invalid_sample_value) { - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); contract->m_schemaVersion = SCHEMA_VERSION(2, 5); shared_ptr mapper; @@ -266,7 +266,7 @@ TEST_F(ObservationValidationTest, should_validate_invalid_sample_value) ts->setProperty("timestamp", ts->m_timestamp); auto observations = (*mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -286,7 +286,7 @@ TEST_F(ObservationValidationTest, should_validate_invalid_sample_value) TEST_F(ObservationValidationTest, should_validate_sample) { - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); contract->m_schemaVersion = SCHEMA_VERSION(2, 5); shared_ptr mapper; @@ -304,7 +304,7 @@ TEST_F(ObservationValidationTest, should_validate_sample) ts->setProperty("timestamp", ts->m_timestamp); auto observations = (*mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -338,7 +338,7 @@ TEST_F(ObservationValidationTest, should_validate_sample_with_int64_value) TEST_F(ObservationValidationTest, should_not_validate_if_validation_is_off) { - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); contract->m_schemaVersion = SCHEMA_VERSION(2, 5); contract->m_validation = false; @@ -357,7 +357,7 @@ TEST_F(ObservationValidationTest, should_not_validate_if_validation_is_off) ts->setProperty("timestamp", ts->m_timestamp); auto observations = (*mapper)(ts); - auto &r = *observations; + auto& r = *observations; ASSERT_EQ(typeid(Observations), typeid(r)); auto oblist = observations->getValue(); @@ -380,7 +380,7 @@ TEST_F(ObservationValidationTest, should_validate_json_data_item_types) using namespace mtconnect::device_model; ErrorList errors; - auto contract = static_cast(m_context->m_contract.get()); + auto contract = static_cast(m_context->m_contract.get()); contract->m_schemaVersion = SCHEMA_VERSION(2, 5); Properties dev { {"id", "3"s}, {"name", "DeviceTest2"s}, {"uuid", "UnivUniqId2"s}, {"iso841Class", "6"s}}; diff --git a/test_package/pallet_test.cpp b/test_package/pallet_test.cpp index 2eb241fc..d4b55673 100644 --- a/test_package/pallet_test.cpp +++ b/test_package/pallet_test.cpp @@ -48,7 +48,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -95,7 +95,7 @@ TEST_F(PalletTest, minimal_pallet_definition) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("7ae770f0-c11e-013a-c34c-4e7f553bbb76", asset->getAssetId()); diff --git a/test_package/part_test.cpp b/test_package/part_test.cpp index 98cd6a52..11b3f5e4 100644 --- a/test_package/part_test.cpp +++ b/test_package/part_test.cpp @@ -45,7 +45,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -94,7 +94,7 @@ TEST_F(PartAssetTest, should_parse_a_part_archetype) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("PartArchetype", asset->getName()); @@ -167,7 +167,7 @@ TEST_F(PartAssetTest, process_archetype_can_have_multiple_customers) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("PartArchetype", asset->getName()); @@ -211,7 +211,7 @@ TEST_F(PartAssetTest, customers_are_optional) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("PartArchetype", asset->getName()); @@ -253,7 +253,7 @@ TEST_F(PartAssetTest, should_generate_json) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("PartArchetype", asset->getName()); @@ -331,7 +331,7 @@ TEST_F(PartAssetTest, part_archetype_should_be_extensible) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("PartArchetype", asset->getName()); @@ -378,7 +378,7 @@ TEST_F(PartAssetTest, should_parse_a_part) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("Part", asset->getName()); @@ -451,7 +451,7 @@ TEST_F(PartAssetTest, part_identifiers_are_optional) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("Part", asset->getName()); @@ -488,7 +488,7 @@ TEST_F(PartAssetTest, part_identifiers_type_must_be_unique_or_group) auto it = errors.begin(); { - auto error = dynamic_cast(it->get()); + auto error = dynamic_cast(it->get()); ASSERT_TRUE(error); EXPECT_EQ("Identifier(type): Invalid value for 'type': 'OTHER_IDENTIFIER' is not allowed"s, error->what()); @@ -533,7 +533,7 @@ TEST_F(PartAssetTest, part_should_be_extensible) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); auto workOrder = asset->get("WorkOrder"); @@ -573,7 +573,7 @@ TEST_F(PartAssetTest, part_should_generate_json) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); // Round trip test diff --git a/test_package/period_filter_test.cpp b/test_package/period_filter_test.cpp index 409d3113..457f38b6 100644 --- a/test_package/period_filter_test.cpp +++ b/test_package/period_filter_test.cpp @@ -41,7 +41,7 @@ using namespace std::literals; using namespace std::chrono_literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -51,9 +51,9 @@ using WorkGuard = boost::asio::executor_work_guard &items) : m_dataItems(items) {} - DevicePtr findDevice(const std::string &device) override { return nullptr; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + MockPipelineContract(std::map& items) : m_dataItems(items) {} + DevicePtr findDevice(const std::string& device) override { return nullptr; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_dataItems[name]; } @@ -68,12 +68,12 @@ struct MockPipelineContract : public PipelineContract void deliverAssetCommand(entity::EntityPtr) override {} int32_t getSchemaVersion() const override { return IntDefaultSchemaVersion(); } void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } bool isValidating() const override { return false; } - std::map &m_dataItems; + std::map& m_dataItems; std::vector m_observations; }; @@ -151,9 +151,9 @@ class PeriodFilterTest : public testing::Test return rate; } - auto &observations() + auto& observations() { - return static_cast(m_context->m_contract.get())->m_observations; + return static_cast(m_context->m_contract.get())->m_observations; } shared_ptr m_mapper; @@ -205,7 +205,7 @@ TEST_F(PeriodFilterTest, test_simple_time_series) m_ioContext.run_for(1s); - auto &obs = observations(); + auto& obs = observations(); ASSERT_EQ(3, obs.size()); ASSERT_EQ(1.0, obs[0]->getValue()); ASSERT_EQ(3.0, obs[1]->getValue()); @@ -325,7 +325,7 @@ TEST_F(PeriodFilterTest, delayed_delivery_with_cancel) m_ioContext.run_for(1s); - auto &obs = observations(); + auto& obs = observations(); ASSERT_EQ(4, obs.size()); ASSERT_EQ(1.0, obs[0]->getValue()); ASSERT_EQ(2.0, obs[1]->getValue()); @@ -362,7 +362,7 @@ TEST_F(PeriodFilterTest, deliver_after_delayed_delivery) // Deliver previous m_ioContext.run_for(750ms); - auto &obs = observations(); + auto& obs = observations(); { ASSERT_EQ(2, obs.size()); ASSERT_EQ(1.0, obs[0]->getValue()); @@ -458,7 +458,7 @@ TEST_F(PeriodFilterTest, streaming_observations_closely_packed) makeFilter(); Timestamp now = chrono::system_clock::now(); - auto &obs = observations(); + auto& obs = observations(); { auto os = observe({"a", "1"}, now + 100ms); @@ -552,7 +552,7 @@ TEST_F(PeriodFilterTest, time_moving_backward) m_ioContext.run_for(1s); - auto &obs = observations(); + auto& obs = observations(); ASSERT_EQ(2, obs.size()); ASSERT_EQ(1.0, obs[0]->getValue()); ASSERT_EQ(4.0, obs[1]->getValue()); @@ -564,7 +564,7 @@ TEST_F(PeriodFilterTest, exact_period_spacing) makeFilter(); Timestamp now = chrono::system_clock::now(); - auto &obs = observations(); + auto& obs = observations(); { auto os = observe({"a", "1"}, now + 0ms); @@ -597,7 +597,7 @@ TEST_F(PeriodFilterTest, streaming_observations_spaced_temporally) makeFilter(); Timestamp now = chrono::system_clock::now(); - auto &obs = observations(); + auto& obs = observations(); { auto os = observe({"a", "1"}, now + 100ms); @@ -686,7 +686,7 @@ TEST_F(PeriodFilterTest, unavailable_behavior) Timestamp now = chrono::system_clock::now(); - auto &obs = observations(); + auto& obs = observations(); { auto os = observe({"a", "UNAVAILABLE"}, now + 100ms); diff --git a/test_package/physical_asset_test.cpp b/test_package/physical_asset_test.cpp index 7d55b6d2..6b31532f 100644 --- a/test_package/physical_asset_test.cpp +++ b/test_package/physical_asset_test.cpp @@ -49,7 +49,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -91,7 +91,7 @@ TEST_F(PhysicalAssetTest, minimal_physical_asset_definition) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("7ae770f0-c11e-013a-c34c-4e7f553bbb76", asset->getAssetId()); diff --git a/test_package/pipeline_deliver_test.cpp b/test_package/pipeline_deliver_test.cpp index cc32c2e1..290e84a7 100644 --- a/test_package/pipeline_deliver_test.cpp +++ b/test_package/pipeline_deliver_test.cpp @@ -40,7 +40,7 @@ using namespace std::chrono_literals; using namespace mtconnect::sink::rest_sink; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -67,7 +67,7 @@ class PipelineDeliverTest : public testing::Test TEST_F(PipelineDeliverTest, observation_is_delivered_to_circular_buffer_with_correct_values) { m_agentTestHelper->addAdapter(); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); m_agentTestHelper->m_adapter->processData("2021-01-22T12:33:45.123Z|Xpos|100.0"); ASSERT_EQ(seq + 1, circ.getSequence()); @@ -82,7 +82,7 @@ TEST_F(PipelineDeliverTest, duplicate_filter_suppresses_repeated_values_in_circu { ConfigOptions options {{configuration::FilterDuplicates, true}}; m_agentTestHelper->addAdapter(options); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); m_agentTestHelper->m_adapter->processData("2021-01-22T12:33:45.123Z|Xpos|100.0"); ASSERT_EQ(seq + 1, circ.getSequence()); @@ -106,7 +106,7 @@ TEST_F(PipelineDeliverTest, upcase_filter_converts_event_values_to_uppercase) { ConfigOptions options {{configuration::UpcaseDataItemValue, true}}; m_agentTestHelper->addAdapter(options); - auto &circ = m_agentTestHelper->getAgent()->getCircularBuffer(); + auto& circ = m_agentTestHelper->getAgent()->getCircularBuffer(); auto seq = circ.getSequence(); m_agentTestHelper->m_adapter->processData("2021-01-22T12:33:45.123Z|a01c7f30|active"); ASSERT_EQ(seq + 1, circ.getSequence()); diff --git a/test_package/pipeline_edit_test.cpp b/test_package/pipeline_edit_test.cpp index abb4a3d1..e6ebae6a 100644 --- a/test_package/pipeline_edit_test.cpp +++ b/test_package/pipeline_edit_test.cpp @@ -41,27 +41,27 @@ using namespace std::chrono_literals; using namespace mtconnect::sink::rest_sink; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } -using TransformFun = std::function; +using TransformFun = std::function; class TestTransform : public Transform { public: - TestTransform(const std::string &name, TransformFun fun, Guard guard) + TestTransform(const std::string& name, TransformFun fun, Guard guard) : Transform(name), m_function(fun) { m_guard = guard; } - TestTransform(const std::string &name, Guard guard) : Transform(name) { m_guard = guard; } - TestTransform(const std::string &name) : Transform(name) {} + TestTransform(const std::string& name, Guard guard) : Transform(name) { m_guard = guard; } + TestTransform(const std::string& name) : Transform(name) {} - EntityPtr operator()(EntityPtr &&ptr) override { return m_function(std::move(ptr)); } + EntityPtr operator()(EntityPtr&& ptr) override { return m_function(std::move(ptr)); } - void setGuard(Guard &guard) { m_guard = guard; } + void setGuard(Guard& guard) { m_guard = guard; } TransformFun m_function; }; using TestTransformPtr = shared_ptr; @@ -71,7 +71,7 @@ class TestPipeline : public Pipeline public: using Pipeline::Pipeline; - void build(const ConfigOptions &options) override {} + void build(const ConfigOptions& options) override {} TransformPtr getStart() { return m_start; } }; @@ -85,14 +85,14 @@ class PipelineEditTest : public testing::Test m_pipeline = make_unique(m_context, strand); TestTransformPtr ta = make_shared("A"s, EntityNameGuard("X", RUN)); - ta->m_function = [ta](EntityPtr &&entity) { + ta->m_function = [ta](EntityPtr&& entity) { EntityPtr ret = shared_ptr(new Entity(*entity)); ret->setValue(ret->getValue() + "A"s); return ta->next(std::move(ret)); }; TestTransformPtr tb = make_shared("B"s, EntityNameGuard("X", RUN)); - tb->m_function = [tb](EntityPtr &&entity) { + tb->m_function = [tb](EntityPtr&& entity) { EntityPtr ret = shared_ptr(new Entity(*entity)); ret->setValue(ret->getValue() + "B"s); return tb->next(std::move(ret)); @@ -132,7 +132,7 @@ TEST_F(PipelineEditTest, run_three_transforms) TEST_F(PipelineEditTest, insert_R_before_B) { TestTransformPtr tr = make_shared("R"s, EntityNameGuard("X", RUN)); - tr->m_function = [&tr](EntityPtr &&entity) { + tr->m_function = [&tr](EntityPtr&& entity) { EntityPtr ret = shared_ptr(new Entity(*entity)); ret->setValue(ret->getValue() + "R"s); return tr->next(std::move(ret)); @@ -149,7 +149,7 @@ TEST_F(PipelineEditTest, insert_R_before_B) TEST_F(PipelineEditTest, insert_R_after_B) { TestTransformPtr tr = make_shared("R"s, EntityNameGuard("X", RUN)); - tr->m_function = [&tr](EntityPtr &&entity) { + tr->m_function = [&tr](EntityPtr&& entity) { EntityPtr ret = shared_ptr(new Entity(*entity)); ret->setValue(ret->getValue() + "R"s); return tr->next(std::move(ret)); diff --git a/test_package/process_test.cpp b/test_package/process_test.cpp index 065caaee..4260e051 100644 --- a/test_package/process_test.cpp +++ b/test_package/process_test.cpp @@ -45,7 +45,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -111,7 +111,7 @@ TEST_F(ProcessAssetTest, should_parse_a_process_archetype) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("ProcessArchetype", asset->getName()); @@ -257,7 +257,7 @@ TEST_F(ProcessAssetTest, process_archetype_can_have_multiple_routings) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); auto routings = asset->getList("Routings"); @@ -329,7 +329,7 @@ TEST_F(ProcessAssetTest, process_steps_can_be_optional) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); auto routings = asset->getList("Routings"); @@ -374,7 +374,7 @@ TEST_F(ProcessAssetTest, process_archetype_must_have_at_least_one_routing) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(1, errors.size()); - auto error = dynamic_cast(errors.front().get()); + auto error = dynamic_cast(errors.front().get()); ASSERT_EQ("ProcessArchetype(Routings): Property Routings is required and not provided"s, error->what()); @@ -408,7 +408,7 @@ TEST_F(ProcessAssetTest, process_archetype_routing_must_have_a_process_step) auto it = errors.begin(); { - auto error = dynamic_cast(it->get()); + auto error = dynamic_cast(it->get()); ASSERT_TRUE(error); EXPECT_EQ("Routing(ProcessStep): Property ProcessStep is required and not provided"s, error->what()); @@ -426,7 +426,7 @@ TEST_F(ProcessAssetTest, process_archetype_routing_must_have_a_process_step) it++; { - auto error = dynamic_cast(it->get()); + auto error = dynamic_cast(it->get()); ASSERT_TRUE(error); EXPECT_EQ( "Routings(Routing): Entity list requirement Routing must have at least 1 entries, 0 found"s, @@ -445,7 +445,7 @@ TEST_F(ProcessAssetTest, process_archetype_routing_must_have_a_process_step) it++; { - auto error = dynamic_cast(it->get()); + auto error = dynamic_cast(it->get()); ASSERT_TRUE(error); EXPECT_EQ("ProcessArchetype(Routings): Property Routings is required and not provided"s, error->what()); @@ -480,7 +480,7 @@ TEST_F(ProcessAssetTest, activity_can_have_a_sequence_precedence_and_be_optional auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); auto routings = asset->getList("Routings"); @@ -743,7 +743,7 @@ TEST_F(ProcessAssetTest, process_can_only_have_one_routings) auto it = errors.begin(); { - auto error = dynamic_cast(it->get()); + auto error = dynamic_cast(it->get()); ASSERT_TRUE(error); EXPECT_EQ( "Routings(Routing): Entity list requirement Routing must have at least 1 and no more than 1 entries, 2 found"s, @@ -762,7 +762,7 @@ TEST_F(ProcessAssetTest, process_can_only_have_one_routings) it++; { - auto error = dynamic_cast(it->get()); + auto error = dynamic_cast(it->get()); ASSERT_TRUE(error); EXPECT_EQ("Process(Routings): Property Routings is required and not provided"s, error->what()); EXPECT_EQ("Process", error->getEntity()); diff --git a/test_package/qif_document_test.cpp b/test_package/qif_document_test.cpp index 66d5b97e..c186f78a 100644 --- a/test_package/qif_document_test.cpp +++ b/test_package/qif_document_test.cpp @@ -49,7 +49,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -120,7 +120,7 @@ TEST_F(QIFDocumentTest, minimal_qif_definition) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("30d278e0-c150-013a-c34d-4e7f553bbb76", asset->getAssetId()); @@ -192,7 +192,7 @@ TEST_F(QIFDocumentTest, qif_document_is_round_tripped_to_xml) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); entity::XmlPrinter printer; @@ -240,7 +240,7 @@ TEST_F(QIFDocumentTest, should_generate_json) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); entity::JsonEntityPrinter jsonPrinter(1, true); @@ -331,7 +331,7 @@ TEST_F(QIFDocumentTest, should_parse_document_with_multiple_same_named_elements) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); auto qif = asset->get("QIFDocument"); @@ -339,10 +339,10 @@ TEST_F(QIFDocumentTest, should_parse_document_with_multiple_same_named_elements) auto product = qif->get("Product"); ASSERT_TRUE(product); - auto &partSetList = product->getListProperty(); + auto& partSetList = product->getListProperty(); ASSERT_EQ(2, partSetList.size()); - auto &partSet = *partSetList.begin(); + auto& partSet = *partSetList.begin(); ASSERT_EQ("2"s, partSet->get("N")); auto parts = partSet->getListProperty(); ASSERT_EQ(2, parts.size()); diff --git a/test_package/qname_test.cpp b/test_package/qname_test.cpp index a9662d69..c6d55c5d 100644 --- a/test_package/qname_test.cpp +++ b/test_package/qname_test.cpp @@ -25,7 +25,7 @@ using namespace mtconnect::entity; using namespace std; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/raw_material_test.cpp b/test_package/raw_material_test.cpp index bccc37cc..52965a87 100644 --- a/test_package/raw_material_test.cpp +++ b/test_package/raw_material_test.cpp @@ -49,7 +49,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -104,7 +104,7 @@ TEST_F(RawMaterialTest, minimal_raw_material_definition) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("7ae770f0-c11e-013a-c34c-4e7f553bbb76", asset->getAssetId()); @@ -146,7 +146,7 @@ TEST_F(RawMaterialTest, should_parse_raw_material_and_material) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); ASSERT_EQ("7ae770f0-c11e-013a-c34c-4e7f553bbb76", asset->getAssetId()); diff --git a/test_package/references_test.cpp b/test_package/references_test.cpp index ecc63041..429903d6 100644 --- a/test_package/references_test.cpp +++ b/test_package/references_test.cpp @@ -39,7 +39,7 @@ using namespace mtconnect::source::adapter; using namespace entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -67,7 +67,7 @@ class ReferencesTest : public testing::Test m_agentTestHelper.reset(); } - Adapter *m_adapter {nullptr}; + Adapter* m_adapter {nullptr}; std::string m_agentId; DevicePtr m_device; std::unique_ptr m_agentTestHelper; @@ -81,7 +81,7 @@ TEST_F(ReferencesTest, component_data_item_references_are_parsed_with_name_and_i ASSERT_NE(nullptr, m_component); - const auto &references = m_component->getList("References"); + const auto& references = m_component->getList("References"); ASSERT_TRUE(references); ASSERT_EQ(3, references->size()); auto reference = references->begin(); @@ -100,7 +100,7 @@ TEST_F(ReferencesTest, should_map_references_to_new_ids) ASSERT_NE(nullptr, m_component); - const auto &references = m_component->getList("References"); + const auto& references = m_component->getList("References"); ASSERT_TRUE(references); ASSERT_EQ(3, references->size()); auto reference = references->begin(); diff --git a/test_package/relationship_test.cpp b/test_package/relationship_test.cpp index c4bb10a4..a33b3838 100644 --- a/test_package/relationship_test.cpp +++ b/test_package/relationship_test.cpp @@ -40,7 +40,7 @@ using namespace entity; using namespace device_model; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -61,7 +61,7 @@ class RelationshipTest : public testing::Test void TearDown() override { m_agentTestHelper.reset(); } - source::adapter::Adapter *m_adapter {nullptr}; + source::adapter::Adapter* m_adapter {nullptr}; std::string m_agentId; ComponentPtr m_component {nullptr}; @@ -72,7 +72,7 @@ TEST_F(RelationshipTest, component_device_and_asset_relationships_are_parsed_wit { ASSERT_NE(nullptr, m_component); - const auto &clc = m_component->get("Configuration"); + const auto& clc = m_component->get("Configuration"); ASSERT_TRUE(clc); auto rels = clc->getList("Relationships"); diff --git a/test_package/response_document_test.cpp b/test_package/response_document_test.cpp index 0a452e02..f64fbc70 100644 --- a/test_package/response_document_test.cpp +++ b/test_package/response_document_test.cpp @@ -37,7 +37,7 @@ using namespace date::literals; using namespace std::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -47,8 +47,8 @@ class MockPipelineContract : public PipelineContract { public: MockPipelineContract(DevicePtr device) : m_device(device) {} - DevicePtr findDevice(const std::string &) override { return m_device; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DevicePtr findDevice(const std::string&) override { return m_device; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_device->getDeviceDataItem(name); } @@ -60,9 +60,9 @@ class MockPipelineContract : public PipelineContract void deliverAssetCommand(entity::EntityPtr) override {} int32_t getSchemaVersion() const override { return IntDefaultSchemaVersion(); } void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } bool isValidating() const override { return false; } DevicePtr m_device; @@ -202,7 +202,7 @@ TEST_F(ResponseDocumentTest, should_parse_data_sets) ent++; ASSERT_EQ(4, (*ent)->get("count")); - const auto &ds = (*ent)->getValue(); + const auto& ds = (*ent)->getValue(); ASSERT_EQ(4, ds.size()); auto dse = ds.begin(); @@ -283,14 +283,14 @@ TEST_F(ResponseDocumentTest, should_parse_tables) ASSERT_TRUE(obs->isUnavailable()); ent++; - const auto &ds = (*ent)->getValue(); + const auto& ds = (*ent)->getValue(); ASSERT_EQ(4, ds.size()); auto dse = ds.begin(); ASSERT_EQ("W1", dse->m_key); ASSERT_FALSE(dse->m_removed); - const auto &v1 = get(dse->m_value); + const auto& v1 = get(dse->m_value); ASSERT_EQ(3, v1.size()); auto v1i = v1.begin(); @@ -307,7 +307,7 @@ TEST_F(ResponseDocumentTest, should_parse_tables) ASSERT_EQ("W2", dse->m_key); ASSERT_FALSE(dse->m_removed); - const auto &v2 = get(dse->m_value); + const auto& v2 = get(dse->m_value); ASSERT_EQ(3, v2.size()); auto v2i = v2.begin(); @@ -324,7 +324,7 @@ TEST_F(ResponseDocumentTest, should_parse_tables) ASSERT_EQ("W3", dse->m_key); ASSERT_FALSE(dse->m_removed); - const auto &v3 = get(dse->m_value); + const auto& v3 = get(dse->m_value); ASSERT_EQ(3, v3.size()); auto v3i = v3.begin(); @@ -353,7 +353,7 @@ TEST_F(ResponseDocumentTest, should_parse_assets) str.seekg(0, std::ios_base::end); size_t size = str.tellg(); str.seekg(0); - char *buffer = new char[size + 1]; + char* buffer = new char[size + 1]; memset(buffer, 0, size); str.read(buffer, size); buffer[size] = '\0'; @@ -404,7 +404,7 @@ TEST_F(ResponseDocumentTest, should_parse_legacy_error) ResponseDocument::parse(data, *m_doc, m_context); ASSERT_EQ(1, m_doc->m_errors.size()); - auto &error = m_doc->m_errors.front(); + auto& error = m_doc->m_errors.front(); ASSERT_EQ("OUT_OF_RANGE", error.m_code); ASSERT_EQ("'at' must be greater than 4871368", error.m_message); } diff --git a/test_package/routing_test.cpp b/test_package/routing_test.cpp index 0a0a2b27..cd9c266a 100644 --- a/test_package/routing_test.cpp +++ b/test_package/routing_test.cpp @@ -36,7 +36,7 @@ using namespace mtconnect::sink::rest_sink; using verb = boost::beast::http::verb; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -108,7 +108,7 @@ TEST_F(RoutingTest, parses_current_at_query_parameter) EXPECT_EQ("device", pp.m_name); EXPECT_EQ(PATH, pp.m_part); - auto &qp = *r.getQueryParameters().begin(); + auto& qp = *r.getQueryParameters().begin(); EXPECT_EQ("at", qp.m_name); EXPECT_EQ(UNSIGNED_INTEGER, qp.m_type); EXPECT_EQ(QUERY, qp.m_part); @@ -221,7 +221,7 @@ TEST_F(RoutingTest, should_throw_a_rest_error_with_an_invalid_parameter) { r.matches(0, request); } - catch (RestError &e) + catch (RestError& e) { auto errors = e.getErrors(); ASSERT_EQ(1, errors.size()); @@ -252,7 +252,7 @@ TEST_F(RoutingTest, should_throw_a_rest_error_with_multiple_invalid_parameters) { r.matches(0, request); } - catch (RestError &e) + catch (RestError& e) { auto errors = e.getErrors(); ASSERT_EQ(2, errors.size()); diff --git a/test_package/sensor_configuration_test.cpp b/test_package/sensor_configuration_test.cpp index 5b14a7e0..6d617f26 100644 --- a/test_package/sensor_configuration_test.cpp +++ b/test_package/sensor_configuration_test.cpp @@ -38,7 +38,7 @@ using namespace mtconnect::source::adapter; using namespace entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -57,7 +57,7 @@ class SensorConfigurationTest : public testing::Test void TearDown() override { m_agentTestHelper.reset(); } - Adapter *m_adapter {nullptr}; + Adapter* m_adapter {nullptr}; std::string m_agentId; DevicePtr m_device {nullptr}; std::unique_ptr m_agentTestHelper; @@ -67,7 +67,7 @@ TEST_F(SensorConfigurationTest, sensor_configuration_channels_are_parsed_with_na { ASSERT_NE(nullptr, m_device); - auto &clc = m_device->get("Configuration"); + auto& clc = m_device->get("Configuration"); ASSERT_TRUE(clc); auto config = clc->get("SensorConfiguration"); diff --git a/test_package/shdr_tokenizer_test.cpp b/test_package/shdr_tokenizer_test.cpp index 0315454a..dc2f4a8d 100644 --- a/test_package/shdr_tokenizer_test.cpp +++ b/test_package/shdr_tokenizer_test.cpp @@ -32,7 +32,7 @@ using namespace std; using namespace std::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -52,19 +52,19 @@ class ShdrTokenizerTest : public testing::Test shared_ptr m_tokenizer; }; -inline std::list extract(const Properties &props) +inline std::list extract(const Properties& props) { std::list list; - for (auto &p : props) + for (auto& p : props) list.emplace_back(get(p.second)); return list; } template -inline bool isOfType(const EntityPtr &p) +inline bool isOfType(const EntityPtr& p) { - const auto &o = *p; + const auto& o = *p; return typeid(T) == typeid(o); } @@ -80,7 +80,7 @@ TEST_F(ShdrTokenizerTest, should_handle_simple_tokens) {"hello", R"D(xxx={b="12345", c="xxxxx"}})D", "bbb"}}, }; - for (const auto &test : data) + for (const auto& test : data) { auto data = std::make_shared("Data", Properties {{"VALUE", test.first}}); auto entity = (*m_tokenizer)(std::move(data)); @@ -144,7 +144,7 @@ TEST_F(ShdrTokenizerTest, should_handle_escaped_characters_in_SHDR_line) data[R"(y|"a\|"z)"] = {"y", "\"a\\", "\"z"}; data["x|y||z"] = {"x", "y", "", "z"}; - for (const auto &test : data) + for (const auto& test : data) { auto data = std::make_shared("Data", Properties {{"VALUE", test.first}}); auto entity = (*m_tokenizer)(std::move(data)); diff --git a/test_package/solid_model_test.cpp b/test_package/solid_model_test.cpp index 6a1fce07..e2014700 100644 --- a/test_package/solid_model_test.cpp +++ b/test_package/solid_model_test.cpp @@ -38,7 +38,7 @@ using namespace mtconnect::source::adapter; using namespace entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -57,7 +57,7 @@ class SolidModelTest : public testing::Test void TearDown() override { m_agentTestHelper.reset(); } - Adapter *m_adapter {nullptr}; + Adapter* m_adapter {nullptr}; std::string m_agentId; DevicePtr m_device; std::unique_ptr m_agentTestHelper; @@ -67,7 +67,7 @@ TEST_F(SolidModelTest, device_solid_model_attributes_and_scale_are_parsed) { ASSERT_NE(nullptr, m_device); - auto &clc = m_device->get("Configuration"); + auto& clc = m_device->get("Configuration"); ASSERT_TRUE(clc); auto model = clc->get("SolidModel"); @@ -90,7 +90,7 @@ TEST_F(SolidModelTest, rotary_solid_model_with_transformation_and_references_is_ ASSERT_NE(nullptr, m_device); auto rot = m_device->getComponentById("c"); - auto &clc = rot->get("Configuration"); + auto& clc = rot->get("Configuration"); ASSERT_TRUE(clc); auto model = clc->get("SolidModel"); diff --git a/test_package/specification_test.cpp b/test_package/specification_test.cpp index 05d50268..66d45428 100644 --- a/test_package/specification_test.cpp +++ b/test_package/specification_test.cpp @@ -39,7 +39,7 @@ using namespace entity; using namespace device_model; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -62,7 +62,7 @@ class SpecificationTest : public testing::Test m_component.reset(); } - mtconnect::source::adapter::Adapter *m_adapter {nullptr}; + mtconnect::source::adapter::Adapter* m_adapter {nullptr}; ComponentPtr m_component; std::unique_ptr m_agentTestHelper; }; @@ -71,10 +71,10 @@ TEST_F(SpecificationTest, specification_attributes_and_limits_are_parsed_for_com { ASSERT_NE(nullptr, m_component); - auto &ent = m_component->get("Configuration"); + auto& ent = m_component->get("Configuration"); ASSERT_TRUE(ent); - const auto &specs = ent->getList("Specifications"); + const auto& specs = ent->getList("Specifications"); ASSERT_TRUE(specs); ASSERT_EQ(3, specs->size()); @@ -102,10 +102,10 @@ TEST_F(SpecificationTest, test_1_6_specification_without_id) auto device = m_agentTestHelper->m_agent->getDeviceByName("LinuxCNC"); m_component = device->getComponentById("power"); - auto &ent = m_component->get("Configuration"); + auto& ent = m_component->get("Configuration"); ASSERT_TRUE(ent); - const auto &specs = ent->getList("Specifications"); + const auto& specs = ent->getList("Specifications"); ASSERT_TRUE(specs); ASSERT_EQ(1, specs->size()); @@ -248,11 +248,11 @@ TEST_F(SpecificationTest, version_1_7_specification_values_including_limits_and_ { ASSERT_NE(nullptr, m_component); - auto &ent = m_component->get("Configuration"); + auto& ent = m_component->get("Configuration"); ASSERT_TRUE(ent); // Get the second configuration. - const auto &specs = ent->getList("Specifications"); + const auto& specs = ent->getList("Specifications"); ASSERT_TRUE(specs); ASSERT_EQ(3, specs->size()); @@ -282,10 +282,10 @@ TEST_F(SpecificationTest, process_specification_with_spec_control_and_alarm_limi { ASSERT_NE(nullptr, m_component); - auto &ent = m_component->get("Configuration"); + auto& ent = m_component->get("Configuration"); ASSERT_TRUE(ent); - const auto &specs = ent->getList("Specifications"); + const auto& specs = ent->getList("Specifications"); ASSERT_TRUE(specs); ASSERT_EQ(3, specs->size()); auto si = specs->begin(); diff --git a/test_package/table_test.cpp b/test_package/table_test.cpp index f189da0f..9b62d153 100644 --- a/test_package/table_test.cpp +++ b/test_package/table_test.cpp @@ -44,7 +44,7 @@ using namespace chrono_literals; using namespace date::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -80,8 +80,8 @@ class TableTest : public testing::Test std::unique_ptr m_agentTestHelper; }; -inline DataSetEntry operator""_E(const char *c, std::size_t) { return DataSetEntry(c); } -inline TableCell operator""_C(const char *c, std::size_t) { return TableCell(c); } +inline DataSetEntry operator""_E(const char* c, std::size_t) { return DataSetEntry(c); } +inline TableCell operator""_C(const char* c, std::size_t) { return TableCell(c); } TEST_F(TableTest, data_item_is_identified_as_table_and_data_set_representation) { @@ -98,7 +98,7 @@ TEST_F(TableTest, test_simple_table_formats) ASSERT_TRUE(s1.parse("abc={a=1 b=2.0 c='abc'}", true)); ASSERT_EQ(1, s1.size()); - const auto &abc1 = get(s1.find("abc"_E)->m_value); + const auto& abc1 = get(s1.find("abc"_E)->m_value); ASSERT_EQ(3, abc1.size()); ASSERT_EQ(1, get(abc1.find("a"_C)->m_value)); ASSERT_EQ(2.0, get(abc1.find("b"_C)->m_value)); @@ -111,7 +111,7 @@ TEST_F(TableTest, test_simple_table_formats_with_whitespace) ASSERT_TRUE(s1.parse("abc={ a=1 b=2.0 c='abc' }", true)); ASSERT_EQ(1, s1.size()); - const auto &abc1 = get(s1.find("abc"_E)->m_value); + const auto& abc1 = get(s1.find("abc"_E)->m_value); ASSERT_EQ(3, abc1.size()); ASSERT_EQ(1, get(abc1.find("a"_C)->m_value)); ASSERT_EQ(2.0, get(abc1.find("b"_C)->m_value)); @@ -124,7 +124,7 @@ TEST_F(TableTest, test_simple_table_formats_with_quotes) ASSERT_TRUE(s1.parse("abc=' a=1 b=2.0 c='abc''", true)); ASSERT_EQ(1, s1.size()); - const auto &abc1 = get(s1.find("abc"_E)->m_value); + const auto& abc1 = get(s1.find("abc"_E)->m_value); ASSERT_EQ(3, abc1.size()); ASSERT_EQ(1, get(abc1.find("a"_C)->m_value)); ASSERT_EQ(2.0, get(abc1.find("b"_C)->m_value)); @@ -137,7 +137,7 @@ TEST_F(TableTest, test_simple_table_formats_with_double_quotes) ASSERT_TRUE(s1.parse("abc=\" a=1 b=2.0 c='abc'\"", true)); ASSERT_EQ(1, s1.size()); - const auto &abc1 = get(s1.find("abc"_E)->m_value); + const auto& abc1 = get(s1.find("abc"_E)->m_value); ASSERT_EQ(3, abc1.size()); ASSERT_EQ(1, get(abc1.find("a"_C)->m_value)); ASSERT_EQ(2.0, get(abc1.find("b"_C)->m_value)); @@ -150,7 +150,7 @@ TEST_F(TableTest, test_simple_table_formats_with_nested_braces) ASSERT_TRUE(s1.parse("abc={ a=1 b=2.0 c={abc}}", true)); ASSERT_EQ(1, s1.size()); - const auto &abc1 = get(s1.find("abc"_E)->m_value); + const auto& abc1 = get(s1.find("abc"_E)->m_value); ASSERT_EQ(3, abc1.size()); ASSERT_EQ(1, get(abc1.find("a"_C)->m_value)); ASSERT_EQ(2.0, get(abc1.find("b"_C)->m_value)); @@ -163,7 +163,7 @@ TEST_F(TableTest, test_simple_table_formats_with_removed_key) s1.parse("abc={ a=1 b=2.0 c={abc} d= e}", true); ASSERT_EQ(1, s1.size()); - const auto &abc1 = get(s1.find("abc"_E)->m_value); + const auto& abc1 = get(s1.find("abc"_E)->m_value); ASSERT_EQ(5, abc1.size()); ASSERT_EQ(1, get(abc1.find("a"_C)->m_value)); ASSERT_EQ(2.0, get(abc1.find("b"_C)->m_value)); @@ -178,7 +178,7 @@ TEST_F(TableTest, test_mulitple_entries) ASSERT_TRUE(s1.parse("abc={ a=1 b=2.0 c={abc} d= e} def={x=1.0 y=2.0}", true)); ASSERT_EQ(2, s1.size()); - const auto &abc = get(s1.find("abc"_E)->m_value); + const auto& abc = get(s1.find("abc"_E)->m_value); ASSERT_EQ(5, abc.size()); ASSERT_EQ(1, get(abc.find("a"_C)->m_value)); ASSERT_EQ(2.0, get(abc.find("b"_C)->m_value)); @@ -186,7 +186,7 @@ TEST_F(TableTest, test_mulitple_entries) ASSERT_TRUE(abc.find("d"_C)->m_removed); ASSERT_TRUE(abc.find("e"_C)->m_removed); - const auto &def = get(s1.find("def"_E)->m_value); + const auto& def = get(s1.find("def"_E)->m_value); ASSERT_EQ(2, def.size()); ASSERT_EQ(1.0, get(def.find("x"_C)->m_value)); ASSERT_EQ(2.0, get(def.find("y"_C)->m_value)); @@ -231,19 +231,19 @@ TEST_F(TableTest, initial_table_set_parses_rows_with_multiple_cells) ASSERT_EQ(3, set1.size()); ASSERT_EQ(3, ce->get("count")); - const auto &g531 = get(set1.find("G53.1"_E)->m_value); + const auto& g531 = get(set1.find("G53.1"_E)->m_value); ASSERT_EQ((size_t)3, g531.size()); ASSERT_EQ(1.0, get(g531.find("X"_C)->m_value)); ASSERT_EQ(2.0, get(g531.find("Y"_C)->m_value)); ASSERT_EQ(3.0, get(g531.find("Z"_C)->m_value)); - const auto &g532 = get(set1.find("G53.2"_E)->m_value); + const auto& g532 = get(set1.find("G53.2"_E)->m_value); ASSERT_EQ((size_t)3, g532.size()); ASSERT_EQ(4.0, get(g532.find("X"_C)->m_value)); ASSERT_EQ(5.0, get(g532.find("Y"_C)->m_value)); ASSERT_EQ(6.0, get(g532.find("Z"_C)->m_value)); - const auto &g533 = get(set1.find("G53.3"_E)->m_value); + const auto& g533 = get(set1.find("G53.3"_E)->m_value); ASSERT_EQ((size_t)4, g533.size()); ASSERT_EQ(7.0, get(g533.find("X"_C)->m_value)); ASSERT_EQ(8.0, get(g533.find("Y"_C)->m_value)); @@ -329,7 +329,7 @@ TEST_F(TableTest, json_current_response_includes_table_rows_with_nested_cell_val ASSERT_EQ(4_S, streams.size()); json stream; - for (auto &s : streams) + for (auto& s : streams) { auto id = s.at("/ComponentStream/componentId"_json_pointer); ASSERT_TRUE(id.is_string()); @@ -344,7 +344,7 @@ TEST_F(TableTest, json_current_response_includes_table_rows_with_nested_cell_val auto events = stream.at("/ComponentStream/Events"_json_pointer); ASSERT_TRUE(events.is_array()); json offsets; - for (auto &o : events) + for (auto& o : events) { ASSERT_TRUE(o.is_object()); auto v = o.begin().key(); @@ -385,7 +385,7 @@ TEST_F(TableTest, json_current_response_handles_string_values_with_spaces_in_cel ASSERT_EQ(4_S, streams.size()); json stream; - for (auto &s : streams) + for (auto& s : streams) { auto id = s.at("/ComponentStream/componentId"_json_pointer); ASSERT_TRUE(id.is_string()); @@ -400,7 +400,7 @@ TEST_F(TableTest, json_current_response_handles_string_values_with_spaces_in_cel auto events = stream.at("/ComponentStream/Events"_json_pointer); ASSERT_TRUE(events.is_array()); json offsets; - for (auto &o : events) + for (auto& o : events) { ASSERT_TRUE(o.is_object()); auto v = o.begin().key(); diff --git a/test_package/target_test.cpp b/test_package/target_test.cpp index e525bf14..a1a6cb47 100644 --- a/test_package/target_test.cpp +++ b/test_package/target_test.cpp @@ -48,7 +48,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -350,7 +350,7 @@ TEST_F(TargetTest, verify_target_requirement) auto rowIt = table.begin(); ASSERT_EQ("R1", rowIt->m_key); ASSERT_TRUE(holds_alternative(rowIt->m_value)); - auto &row = get(rowIt->m_value); + auto& row = get(rowIt->m_value); ASSERT_EQ(1, row.size()); auto cellIt = row.begin(); @@ -361,7 +361,7 @@ TEST_F(TargetTest, verify_target_requirement) rowIt++; ASSERT_EQ("R2", rowIt->m_key); ASSERT_TRUE(holds_alternative(rowIt->m_value)); - auto &row2 = get(rowIt->m_value); + auto& row2 = get(rowIt->m_value); ASSERT_EQ(1, row2.size()); cellIt = row2.begin(); diff --git a/test_package/task_test.cpp b/test_package/task_test.cpp index 63e16f24..ef974952 100644 --- a/test_package/task_test.cpp +++ b/test_package/task_test.cpp @@ -46,7 +46,7 @@ using namespace mtconnect::asset; using namespace mtconnect::printer; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -125,7 +125,7 @@ TEST_F(TaskAssetTest, should_parse_a_part_archetype) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); EXPECT_EQ("TaskArchetype", asset->getName()); @@ -199,11 +199,11 @@ TEST_F(TaskAssetTest, should_parse_a_part_archetype) auto table = (*tit)->getValue(); ASSERT_EQ(2, table.size()); - const auto &row1 = get(table.find(DataSetEntry("PAYLOAD"))->m_value); + const auto& row1 = get(table.find(DataSetEntry("PAYLOAD"))->m_value); ASSERT_EQ(1, row1.size()); EXPECT_EQ(1000, get(row1.find(TableCell("maximum"))->m_value)); - const auto &row2 = get(table.find(DataSetEntry("REACH"))->m_value); + const auto& row2 = get(table.find(DataSetEntry("REACH"))->m_value); ASSERT_EQ(1, row2.size()); EXPECT_EQ(1500, get(row2.find(TableCell("minimum"))->m_value)); @@ -650,7 +650,7 @@ TEST_F(TaskAssetTest, task_archetype_should_have_optional_fields_for_sub_task_re auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); auto subtasks = asset->getList("SubTaskRefs"); @@ -713,7 +713,7 @@ TEST_F(TaskAssetTest, should_parse_simple_task) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); EXPECT_EQ("Task", asset->getName()); @@ -820,7 +820,7 @@ TEST_F(TaskAssetTest, should_parse_simple_task_with_subtasks) auto entity = parser.parse(Asset::getRoot(), doc, errors); ASSERT_EQ(0, errors.size()); - auto asset = dynamic_cast(entity.get()); + auto asset = dynamic_cast(entity.get()); ASSERT_NE(nullptr, asset); auto subtasks = asset->getList("SubTasks"); @@ -1254,7 +1254,7 @@ TEST_F(TaskAssetTest, task_should_accept_all_task_states) list states {"INACTIVE", "PREPARING", "COMMITTING", "COMMITTED", "COMPLETE", "FAIL"}; - for (const auto &state : states) + for (const auto& state : states) { ErrorList errors; entity::XmlParser parser; @@ -1288,7 +1288,7 @@ TEST_F(TaskAssetTest, task_should_not_accept_invalid_task_states) list states {"BAD", "STATE", "123", "DONE", ""}; - for (const auto &state : states) + for (const auto& state : states) { ErrorList errors; entity::XmlParser parser; diff --git a/test_package/test_utilities.hpp b/test_package/test_utilities.hpp index 89d7caf9..a90ea9cc 100644 --- a/test_package/test_utilities.hpp +++ b/test_package/test_utilities.hpp @@ -49,7 +49,7 @@ inline std::string getFile(std::string file) } // Fill the error -inline void fillErrorText(std::string &errorXml, const std::string &text) +inline void fillErrorText(std::string& errorXml, const std::string& text) { using namespace std; @@ -77,8 +77,8 @@ inline void fillErrorText(std::string &errorXml, const std::string &text) } // Search the xml and insert a value into an attribute (attribute="") -inline void fillAttribute(std::string &xmlString, const std::string &attribute, - const std::string &value) +inline void fillAttribute(std::string& xmlString, const std::string& attribute, + const std::string& value) { using namespace std; @@ -113,20 +113,20 @@ inline void fillAttribute(std::string &xmlString, const std::string &attribute, #define DUMP_XML(doc) dumpXml(doc) -inline void failIf(bool condition, const std::string &message, const std::string &file, int line) +inline void failIf(bool condition, const std::string& message, const std::string& file, int line) { ASSERT_FALSE(condition) << file << "(" << line << "): Failed " << message; } -inline void failNotEqualIf(bool condition, const std::string &expected, const std::string &actual, - const std::string &message, const std::string &file, int line) +inline void failNotEqualIf(bool condition, const std::string& expected, const std::string& actual, + const std::string& message, const std::string& file, int line) { ASSERT_FALSE(condition) << file << "(" << line << "): Failed not equal " << message << "\n" << " Expected: " << expected << "\n" << " Actual: " << actual; } -inline void assertIf(bool condition, const std::string &message, const std::string &file, int line) +inline void assertIf(bool condition, const std::string& message, const std::string& file, int line) { ASSERT_TRUE(condition) << file << "(" << line << "): Failed " << message; } @@ -136,16 +136,16 @@ using ValueResponse = std::pair, std::optionaltype == XML_TEXT_NODE) { - string res = (const char *)child->content; + string res = (const char*)child->content; has_content = !mtconnect::trim(res).empty(); } } @@ -229,7 +229,7 @@ inline ValueResponse xpathValue(xmlDocPtr doc, const char *xpath, const std::str else { message << "Xpath " << xpath << " was not supposed to have an attribute."; - xmlChar *text = xmlGetProp(first, BAD_CAST attribute.c_str()); + xmlChar* text = xmlGetProp(first, BAD_CAST attribute.c_str()); if (text) { @@ -249,7 +249,7 @@ inline ValueResponse xpathValue(xmlDocPtr doc, const char *xpath, const std::str } string actual; - xmlChar *text = nullptr; + xmlChar* text = nullptr; switch (first->type) { @@ -269,18 +269,18 @@ inline ValueResponse xpathValue(xmlDocPtr doc, const char *xpath, const std::str if (text) { - actual = (const char *)text; + actual = (const char*)text; xmlFree(text); } break; case XML_ATTRIBUTE_NODE: - actual = (const char *)first->content; + actual = (const char*)first->content; break; case XML_TEXT_NODE: - actual = (const char *)first->content; + actual = (const char*)first->content; break; default: @@ -295,8 +295,8 @@ inline ValueResponse xpathValue(xmlDocPtr doc, const char *xpath, const std::str return ValueResponse(actual, std::nullopt); } -inline void xpathTest(xmlDocPtr doc, const char *xpath, const char *expected, - const std::string &file, int line) +inline void xpathTest(xmlDocPtr doc, const char* xpath, const char* expected, + const std::string& file, int line) { using namespace std; @@ -326,7 +326,7 @@ inline void xpathTest(xmlDocPtr doc, const char *xpath, const char *expected, } } -inline void xpathTestCount(xmlDocPtr doc, const char *xpath, int expected, const std::string &file, +inline void xpathTestCount(xmlDocPtr doc, const char* xpath, int expected, const std::string& file, int line) { diff --git a/test_package/testadapter_service.hpp b/test_package/testadapter_service.hpp index 2af0148b..5975c61f 100644 --- a/test_package/testadapter_service.hpp +++ b/test_package/testadapter_service.hpp @@ -32,9 +32,9 @@ namespace mtconnect { class adapter_plugin_test : public source::Source { public: - adapter_plugin_test(const std::string &name, boost::asio::io_context &io, - pipeline::PipelineContextPtr pipelineContext, const ConfigOptions &options, - const boost::property_tree::ptree &block) + adapter_plugin_test(const std::string& name, boost::asio::io_context& io, + pipeline::PipelineContextPtr pipelineContext, const ConfigOptions& options, + const boost::property_tree::ptree& block) : Source(name, io), m_pipeline(pipelineContext, m_strand) { @@ -51,22 +51,22 @@ namespace mtconnect { void stop() override { m_pipeline.clear(); } // Factory method - static source::SourcePtr create(const std::string &name, boost::asio::io_context &io, + static source::SourcePtr create(const std::string& name, boost::asio::io_context& io, pipeline::PipelineContextPtr pipelineContext, - const ConfigOptions &options, - const boost::property_tree::ptree &block) + const ConfigOptions& options, + const boost::property_tree::ptree& block) { return std::make_shared(name, io, pipelineContext, options, block); } - static void register_factory(const boost::property_tree::ptree &block, - configuration::AgentConfiguration &config) + static void register_factory(const boost::property_tree::ptree& block, + configuration::AgentConfiguration& config) { config.getSourceFactory().registerFactory("adapter_plugin_test", &adapter_plugin_test::create); } - Pipeline *getPipeline() override { return &m_pipeline; } + Pipeline* getPipeline() override { return &m_pipeline; } protected: source::adapter::AdapterPipeline m_pipeline; diff --git a/test_package/testsink_service.hpp b/test_package/testsink_service.hpp index b16fb370..01d76ccd 100644 --- a/test_package/testsink_service.hpp +++ b/test_package/testsink_service.hpp @@ -27,8 +27,8 @@ namespace mtconnect { class sink_plugin_test : public sink::Sink { public: - sink_plugin_test(const string &name, boost::asio::io_context &context, - sink::SinkContractPtr &&contract, const ConfigOptions &config) + sink_plugin_test(const string& name, boost::asio::io_context& context, + sink::SinkContractPtr&& contract, const ConfigOptions& config) : sink::Sink(name, std::move(contract)) {} @@ -38,18 +38,18 @@ namespace mtconnect { void start() override {} void stop() override {} - bool publish(observation::ObservationPtr &observation) override { return false; } + bool publish(observation::ObservationPtr& observation) override { return false; } bool publish(asset::AssetPtr asset) override { return false; } - static sink::SinkPtr create(const std::string &name, boost::asio::io_context &io, - sink::SinkContractPtr &&contract, const ConfigOptions &options, - const boost::property_tree::ptree &block) + static sink::SinkPtr create(const std::string& name, boost::asio::io_context& io, + sink::SinkContractPtr&& contract, const ConfigOptions& options, + const boost::property_tree::ptree& block) { return std::make_shared(name, io, std::move(contract), options); } - static void register_factory(const boost::property_tree::ptree &block, - configuration::AgentConfiguration &config) + static void register_factory(const boost::property_tree::ptree& block, + configuration::AgentConfiguration& config) { config.getSinkFactory().registerFactory("sink_plugin_test", &sink_plugin_test::create); } diff --git a/test_package/timestamp_extractor_test.cpp b/test_package/timestamp_extractor_test.cpp index 885b6cbc..2c49349d 100644 --- a/test_package/timestamp_extractor_test.cpp +++ b/test_package/timestamp_extractor_test.cpp @@ -32,7 +32,7 @@ using namespace std::literals; using namespace date; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/topic_mapping_test.cpp b/test_package/topic_mapping_test.cpp index 2032a849..9546e6da 100644 --- a/test_package/topic_mapping_test.cpp +++ b/test_package/topic_mapping_test.cpp @@ -35,7 +35,7 @@ using namespace data_item; using namespace std; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -44,11 +44,11 @@ int main(int argc, char *argv[]) class MockPipelineContract : public PipelineContract { public: - MockPipelineContract(std::map &items, std::map &devices) + MockPipelineContract(std::map& items, std::map& devices) : m_dataItems(items), m_devices(devices) {} - DevicePtr findDevice(const std::string &name) override { return m_devices[name]; } - DataItemPtr findDataItem(const std::string &device, const std::string &name) override + DevicePtr findDevice(const std::string& name) override { return m_devices[name]; } + DataItemPtr findDataItem(const std::string& device, const std::string& name) override { return m_dataItems[name]; } @@ -60,13 +60,13 @@ class MockPipelineContract : public PipelineContract void deliverAssetCommand(entity::EntityPtr) override {} int32_t getSchemaVersion() const override { return IntDefaultSchemaVersion(); } void deliverCommand(entity::EntityPtr) override {} - void deliverConnectStatus(entity::EntityPtr, const StringList &, bool) override {} - void sourceFailed(const std::string &id) override {} - const ObservationPtr checkDuplicate(const ObservationPtr &obs) const override { return obs; } + void deliverConnectStatus(entity::EntityPtr, const StringList&, bool) override {} + void sourceFailed(const std::string& id) override {} + const ObservationPtr checkDuplicate(const ObservationPtr& obs) const override { return obs; } bool isValidating() const override { return false; } - std::map &m_dataItems; - std::map &m_devices; + std::map& m_dataItems; + std::map& m_devices; }; class TopicMappingTest : public testing::Test @@ -86,7 +86,7 @@ class TopicMappingTest : public testing::Test m_devices.clear(); } - DataItemPtr makeDataItem(const std::string &device, const Properties &props) + DataItemPtr makeDataItem(const std::string& device, const Properties& props) { auto dev = m_devices.find(device); if (dev == m_devices.end()) @@ -105,7 +105,7 @@ class TopicMappingTest : public testing::Test return di; } - DevicePtr makeDevice(const std::string &name, const Properties &props) + DevicePtr makeDevice(const std::string& name, const Properties& props) { ErrorList errors; Properties ps(props); @@ -118,13 +118,13 @@ class TopicMappingTest : public testing::Test /// @brief add a data item to a device WITHOUT registering it in the /// findDataItem lookup map (forces resolution via the device scan path) - DataItemPtr makeDeviceOnlyDataItem(const std::string &device, const Properties &props) + DataItemPtr makeDeviceOnlyDataItem(const std::string& device, const Properties& props) { auto dev = m_devices.find(device); EXPECT_NE(m_devices.end(), dev) << "Cannot find device: " << device; if (dev == m_devices.end()) return nullptr; - + Properties ps(props); ErrorList errors; auto di = DataItem::make(ps, errors); @@ -133,7 +133,7 @@ class TopicMappingTest : public testing::Test } /// @brief build a TopicMapper with the given default device, bound to a pass-through - std::shared_ptr makeMapper(const std::string &defaultDevice = "") + std::shared_ptr makeMapper(const std::string& defaultDevice = "") { auto m = make_shared(m_context, defaultDevice); m->bind(make_shared(TypeGuard(RUN))); @@ -141,7 +141,7 @@ class TopicMappingTest : public testing::Test } /// @brief run a message body (and optional topic) through a mapper - PipelineMessagePtr map(std::shared_ptr &mapper, const std::string &body, + PipelineMessagePtr map(std::shared_ptr& mapper, const std::string& body, std::optional topic = std::nullopt) { Properties props {{"VALUE", body}}; @@ -157,7 +157,7 @@ class TopicMappingTest : public testing::Test std::map m_devices; }; -inline DataSetEntry operator""_E(const char *c, std::size_t) { return DataSetEntry(c); } +inline DataSetEntry operator""_E(const char* c, std::size_t) { return DataSetEntry(c); } TEST_F(TopicMappingTest, should_find_data_item_for_topic) { diff --git a/test_package/unit_conversion_test.cpp b/test_package/unit_conversion_test.cpp index 5b8af08c..e809306d 100644 --- a/test_package/unit_conversion_test.cpp +++ b/test_package/unit_conversion_test.cpp @@ -29,7 +29,7 @@ using namespace mtconnect::device_model::data_item; using namespace mtconnect::entity; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/url_parser_test.cpp b/test_package/url_parser_test.cpp index f7e8fee9..14b48624 100644 --- a/test_package/url_parser_test.cpp +++ b/test_package/url_parser_test.cpp @@ -27,7 +27,7 @@ using namespace mtconnect::url; using namespace std::literals; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test_package/utilities_test.cpp b/test_package/utilities_test.cpp index e05e19ff..78783633 100644 --- a/test_package/utilities_test.cpp +++ b/test_package/utilities_test.cpp @@ -28,7 +28,7 @@ using namespace std; using namespace mtconnect; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -135,7 +135,7 @@ TEST(UtilitiesTest, get_current_time_returns_parseable_formatted_strings) char tzs[32] = {0}; int n = sscanf(human.c_str(), "%3s, %2d %3s %4d %2d:%2d:%2d %5s", wday, &day, mon, &year, &hour, - &min, &sec, (char *)&tzs); + &min, &sec, (char*)&tzs); ASSERT_EQ(8, n); } diff --git a/test_package/xml_parser_test.cpp b/test_package/xml_parser_test.cpp index ad25ca1c..1f0f7688 100644 --- a/test_package/xml_parser_test.cpp +++ b/test_package/xml_parser_test.cpp @@ -36,7 +36,7 @@ using namespace device_model; using namespace data_item; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); @@ -56,7 +56,7 @@ class XmlParserTest : public testing::Test m_devices = m_xmlParser->parseFile(TEST_RESOURCE_DIR "/samples/test_config.xml", printer.get()); } - catch (exception &) + catch (exception&) { FAIL() << "Could not locate test xml: " << PROJECT_ROOT_DIR << " /test/resources/samples/test_config.xml"; @@ -72,7 +72,7 @@ class XmlParserTest : public testing::Test } } - parser::XmlParser *m_xmlParser {nullptr}; + parser::XmlParser* m_xmlParser {nullptr}; std::list m_devices; }; @@ -102,19 +102,19 @@ TEST_F(XmlParserTest, parse_file_returns_devices_with_description_and_data_items const auto device = m_devices.front(); // Check for Description - auto &description = device->get("Description"); + auto& description = device->get("Description"); ASSERT_TRUE(description); ASSERT_EQ((string) "Linux CNC Device", description->getValue()); list dataItems; - const auto &dataItemsMap = device->getDeviceDataItems(); + const auto& dataItemsMap = device->getDeviceDataItems(); - for (auto const &mapItem : dataItemsMap) + for (auto const& mapItem : dataItemsMap) dataItems.emplace_back(mapItem.lock()); bool hasExec = false, hasZcom = false; - for (auto const &dataItem : dataItems) + for (auto const& dataItem : dataItems) { if (dataItem->getId() == "p5" && dataItem->getName() == "execution") hasExec = true; @@ -132,7 +132,7 @@ TEST_F(XmlParserTest, data_item_with_condition_category_is_parsed) ASSERT_EQ((size_t)1, m_devices.size()); const auto device = m_devices.front(); - const auto &dataItemsMap = device->getDeviceDataItems(); + const auto& dataItemsMap = device->getDeviceDataItems(); const auto item = dataItemsMap.find("clc")->lock(); ASSERT_TRUE(item); @@ -190,7 +190,7 @@ TEST_F(XmlParserTest, get_data_items_supports_extended_namespace_prefixes) m_xmlParser = new parser::XmlParser(); m_xmlParser->parseFile(TEST_RESOURCE_DIR "/samples/extension.xml", printer.get()); } - catch (exception &) + catch (exception&) { FAIL() << "Could not locate test xml: " << PROJECT_ROOT_DIR << "/test/resources/samples/extension.xml"; @@ -219,7 +219,7 @@ TEST_F(XmlParserTest, parse_file_with_extended_schema_loads_namespaced_component m_xmlParser = new parser::XmlParser(); m_devices = m_xmlParser->parseFile(TEST_RESOURCE_DIR "/samples/extension.xml", printer.get()); } - catch (exception &) + catch (exception&) { FAIL() << "Could not locate test xml: " << PROJECT_ROOT_DIR << "/test/resources/samples/extension.xml"; @@ -230,7 +230,7 @@ TEST_F(XmlParserTest, parse_file_with_extended_schema_loads_namespaced_component const auto device = m_devices.front(); // Check for Description - auto &description = device->get("Description"); + auto& description = device->get("Description"); ASSERT_TRUE(description); ASSERT_EQ((string) "Extended Schema.", description->getValue()); @@ -268,9 +268,9 @@ TEST_F(XmlParserTest, component_configuration_property_is_present) ASSERT_TRUE(dev); EntityPtr power; - const auto &children = dev->getChildren(); + const auto& children = dev->getChildren(); - for (auto const &iter : *children) + for (auto const& iter : *children) { if (iter->get("name") == "power") power = iter; @@ -305,7 +305,7 @@ TEST_F(XmlParserTest, data_item_minimum_delta_filter_is_parsed_from_1_3_schema) m_devices = m_xmlParser->parseFile(TEST_RESOURCE_DIR "/samples/filter_example_1.3.xml", printer.get()); } - catch (exception &) + catch (exception&) { FAIL() << "Could not locate test xml: " << PROJECT_ROOT_DIR << "/test/resources/samples/filter_example_1.3.xml"; @@ -333,7 +333,7 @@ TEST_F(XmlParserTest, data_item_minimum_delta_and_period_filters_are_parsed) m_devices = m_xmlParser->parseFile(TEST_RESOURCE_DIR "/samples/filter_example.xml", printer.get()); } - catch (exception &) + catch (exception&) { FAIL() << "Could not locate test xml: " << PROJECT_ROOT_DIR << "/test/resources/samples/filter_example.xml"; @@ -366,7 +366,7 @@ TEST_F(XmlParserTest, component_data_item_and_component_references_are_resolved) m_devices = m_xmlParser->parseFile(TEST_RESOURCE_DIR "/samples/reference_example.xml", printer.get()); } - catch (exception &) + catch (exception&) { FAIL() << "Could not locate test xml: " << PROJECT_ROOT_DIR << "/test/resources/samples/reference_example.xml"; @@ -429,7 +429,7 @@ TEST_F(XmlParserTest, data_item_source_has_data_item_id_and_component_id) m_devices = m_xmlParser->parseFile(TEST_RESOURCE_DIR "/samples/reference_example.xml", printer.get()); } - catch (exception &) + catch (exception&) { FAIL() << "Could not locate test xml: " << PROJECT_ROOT_DIR << "/test/resources/samples/reference_example.xml"; @@ -459,13 +459,13 @@ TEST_F(XmlParserTest, data_item_relationships_contain_type_and_id_ref) m_devices = m_xmlParser->parseFile(TEST_RESOURCE_DIR "/samples/relationship_test.xml", printer.get()); - const auto &device = m_devices.front(); - const auto &dataItemsMap = device->getDeviceDataItems(); + const auto& device = m_devices.front(); + const auto& dataItemsMap = device->getDeviceDataItems(); const auto item1 = dataItemsMap.find("xlc")->lock(); ASSERT_TRUE(item1 != nullptr); - const auto &relations = item1->getList("Relationships"); + const auto& relations = item1->getList("Relationships"); ASSERT_TRUE(relations); ASSERT_EQ((size_t)2, relations->size()); @@ -485,7 +485,7 @@ TEST_F(XmlParserTest, data_item_relationships_contain_type_and_id_ref) const auto item2 = dataItemsMap.find("xlcpl")->lock(); ASSERT_TRUE(item2 != nullptr); - const auto &relations2 = item2->getList("Relationships"); + const auto& relations2 = item2->getList("Relationships"); ASSERT_EQ((size_t)1, relations2->size()); diff --git a/test_package/xml_printer_test.cpp b/test_package/xml_printer_test.cpp index 9a6f4db6..e69368be 100644 --- a/test_package/xml_printer_test.cpp +++ b/test_package/xml_printer_test.cpp @@ -40,13 +40,13 @@ using namespace mtconnect::parser; using namespace mtconnect::sink::rest_sink; // main -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } -Properties operator""_value(const char *value, size_t s) +Properties operator""_value(const char* value, size_t s) { return Properties {{"VALUE", string(value)}}; } @@ -70,19 +70,19 @@ class XmlPrinterTest : public testing::Test m_printer = nullptr; } - mtconnect::parser::XmlParser *m_config {nullptr}; - mtconnect::printer::XmlPrinter *m_printer {nullptr}; + mtconnect::parser::XmlParser* m_config {nullptr}; + mtconnect::printer::XmlPrinter* m_printer {nullptr}; std::list m_devices; // Construct a component event and set it as the data item's latest event - ObservationPtr addEventToCheckpoint(Checkpoint &checkpoint, const char *name, uint64_t sequence, - const Properties &props); + ObservationPtr addEventToCheckpoint(Checkpoint& checkpoint, const char* name, uint64_t sequence, + const Properties& props); - ObservationPtr newEvent(const char *name, uint64_t sequence, const Properties &props); + ObservationPtr newEvent(const char* name, uint64_t sequence, const Properties& props); }; -ObservationPtr XmlPrinterTest::newEvent(const char *name, uint64_t sequence, - const Properties &props) +ObservationPtr XmlPrinterTest::newEvent(const char* name, uint64_t sequence, + const Properties& props) { // Make sure the data item is there const auto device = m_devices.front(); @@ -97,8 +97,8 @@ ObservationPtr XmlPrinterTest::newEvent(const char *name, uint64_t sequence, return o; } -ObservationPtr XmlPrinterTest::addEventToCheckpoint(Checkpoint &checkpoint, const char *name, - uint64_t sequence, const Properties &props) +ObservationPtr XmlPrinterTest::addEventToCheckpoint(Checkpoint& checkpoint, const char* name, + uint64_t sequence, const Properties& props) { auto event = newEvent(name, sequence, props); checkpoint.addObservation(event); @@ -887,9 +887,9 @@ TEST_F(XmlPrinterTest, StreamsStyle) PARSE_XML(m_printer->printSample(123, 131072, 10254805, 10123733, 10123800, list)); xmlNodePtr pi = doc->children; - ASSERT_EQ(string("xml-stylesheet"), string((const char *)pi->name)); + ASSERT_EQ(string("xml-stylesheet"), string((const char*)pi->name)); ASSERT_EQ(string("type=\"text/xsl\" href=\"/styles/Streams.xsl\""), - string((const char *)pi->content)); + string((const char*)pi->content)); m_printer->setStreamStyle(""); } @@ -901,9 +901,9 @@ TEST_F(XmlPrinterTest, DevicesStyle) PARSE_XML(m_printer->printProbe(123, 9999, 1, 1024, 10, m_devices)); xmlNodePtr pi = doc->children; - ASSERT_EQ(string("xml-stylesheet"), string((const char *)pi->name)); + ASSERT_EQ(string("xml-stylesheet"), string((const char*)pi->name)); ASSERT_EQ(string("type=\"text/xsl\" href=\"/styles/Devices.xsl\""), - string((const char *)pi->content)); + string((const char*)pi->content)); m_printer->setDevicesStyle(""); } @@ -916,9 +916,9 @@ TEST_F(XmlPrinterTest, ErrorStyle) PARSE_XML(m_printer->printError(123, 9999, 1, error, true)); xmlNodePtr pi = doc->children; - ASSERT_EQ(string("xml-stylesheet"), string((const char *)pi->name)); + ASSERT_EQ(string("xml-stylesheet"), string((const char*)pi->name)); ASSERT_EQ(string("type=\"text/xsl\" href=\"/styles/Error.xsl\""), - string((const char *)pi->content)); + string((const char*)pi->content)); m_printer->setErrorStyle(""); } From 777a10531e7a0f6a0e0f3a6f4dc57ec5e1220a1e Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 12:50:08 +0200 Subject: [PATCH 6/9] Fixed message_mapper missing include file --- src/mtconnect/pipeline/message_mapper.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mtconnect/pipeline/message_mapper.hpp b/src/mtconnect/pipeline/message_mapper.hpp index bd5d60f2..83f1f753 100644 --- a/src/mtconnect/pipeline/message_mapper.hpp +++ b/src/mtconnect/pipeline/message_mapper.hpp @@ -26,6 +26,7 @@ #include "mtconnect/device_model/device.hpp" #include "mtconnect/entity/entity.hpp" #include "mtconnect/observation/observation.hpp" +#include "mtconnect/source/adapter/adapter_pipeline.hpp" #include "shdr_tokenizer.hpp" #include "timestamp_extractor.hpp" #include "topic_mapper.hpp" From 4af92dc6838f173834e2d8234b14ca1014a6628c Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 12:52:23 +0200 Subject: [PATCH 7/9] Removed Win32 warning about file size --- src/mtconnect/sink/rest_sink/file_cache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mtconnect/sink/rest_sink/file_cache.cpp b/src/mtconnect/sink/rest_sink/file_cache.cpp index 2a7d5a43..d5f9e35b 100644 --- a/src/mtconnect/sink/rest_sink/file_cache.cpp +++ b/src/mtconnect/sink/rest_sink/file_cache.cpp @@ -274,7 +274,7 @@ namespace mtconnect::sink::rest_sink { if (fs::exists(path)) { - auto size = fs::file_size(path); + size_t size = (size_t) fs::file_size(path); auto ext = path.extension().string(); auto file = From 599b90ad003ea372395632f9b442100605b82e85 Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 14:35:06 +0200 Subject: [PATCH 8/9] Use cmake > 4.3 for building --- conan/profiles/vs32 | 4 ++-- conan/profiles/vs32debug | 5 +++-- conan/profiles/vs32shared | 5 ++--- conan/profiles/vs64 | 4 ++-- conan/profiles/vs64debug | 4 ++-- conan/profiles/vs64shared | 4 ++-- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/conan/profiles/vs32 b/conan/profiles/vs32 index 80588e5e..38eb1b6a 100644 --- a/conan/profiles/vs32 +++ b/conan/profiles/vs32 @@ -9,7 +9,7 @@ compiler.runtime_type=Release build_type=Release [platform_tool_requires] -cmake/4.3.1 +cmake/>4.3 [replace_tool_requires] -cmake/*: cmake/4.3.1 +cmake/*: cmake/>4.3 diff --git a/conan/profiles/vs32debug b/conan/profiles/vs32debug index 89406213..45d05b20 100644 --- a/conan/profiles/vs32debug +++ b/conan/profiles/vs32debug @@ -9,8 +9,9 @@ compiler.runtime_type=Debug build_type=Debug + [platform_tool_requires] -cmake/4.3.1 +cmake/>4.3 [replace_tool_requires] -cmake/*: cmake/4.3.1 +cmake/*: cmake/>4.3 diff --git a/conan/profiles/vs32shared b/conan/profiles/vs32shared index 80c97deb..c59c43ed 100644 --- a/conan/profiles/vs32shared +++ b/conan/profiles/vs32shared @@ -8,9 +8,8 @@ compiler.runtime=dynamic compiler.runtime_type=Release build_type=Release - [platform_tool_requires] -cmake/4.3.1 +cmake/>4.3 [replace_tool_requires] -cmake/*: cmake/4.3.1 +cmake/*: cmake/>4.3 diff --git a/conan/profiles/vs64 b/conan/profiles/vs64 index 1db3bdcc..d7c4c371 100644 --- a/conan/profiles/vs64 +++ b/conan/profiles/vs64 @@ -9,7 +9,7 @@ compiler.runtime_type=Release build_type=Release [platform_tool_requires] -cmake/4.3 +cmake/>4.3 [replace_tool_requires] -cmake/*: cmake/4.3 \ No newline at end of file +cmake/*: cmake/>4.3 diff --git a/conan/profiles/vs64debug b/conan/profiles/vs64debug index dcba5cbb..5398ab11 100644 --- a/conan/profiles/vs64debug +++ b/conan/profiles/vs64debug @@ -9,7 +9,7 @@ compiler.runtime_type=Debug build_type=Debug [platform_tool_requires] -cmake/4.3 +cmake/>4.3 [replace_tool_requires] -cmake/*: cmake/4.3 \ No newline at end of file +cmake/*: cmake/>4.3 diff --git a/conan/profiles/vs64shared b/conan/profiles/vs64shared index 553587fc..c0a59f58 100644 --- a/conan/profiles/vs64shared +++ b/conan/profiles/vs64shared @@ -12,7 +12,7 @@ build_type=Release shared=True [platform_tool_requires] -cmake/4.3.1 +cmake/>4.3 [replace_tool_requires] -cmake/*: cmake/4.3.1 +cmake/*: cmake/>4.3 From 3289c362925dfc4303cea990318b27905d7a73db Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Wed, 2 Sep 2026 15:06:35 +0200 Subject: [PATCH 9/9] Remove fixing Mac OS to version 15 and remove warning for libxml2. --- CMakeLists.txt | 1 - conan/profiles/macos | 3 +-- src/mtconnect/entity/xml_parser.cpp | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 07b02bd4..54682969 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,7 +27,6 @@ set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CXX_COMPILE_FEATURES cxx_std_20) -set(CMAKE_OSX_DEPLOYMENT_TARGET 15.0) project(cppagent LANGUAGES C CXX) diff --git a/conan/profiles/macos b/conan/profiles/macos index 27f17361..3cb7d740 100644 --- a/conan/profiles/macos +++ b/conan/profiles/macos @@ -3,10 +3,9 @@ include(default) [settings] compiler=apple-clang compiler.cppstd=20 -os.version=15.0 [platform_tool_requires] -cmake/>3.26.0 +cmake/>4.0 diff --git a/src/mtconnect/entity/xml_parser.cpp b/src/mtconnect/entity/xml_parser.cpp index d3f2affd..62da6283 100644 --- a/src/mtconnect/entity/xml_parser.cpp +++ b/src/mtconnect/entity/xml_parser.cpp @@ -81,7 +81,7 @@ namespace mtconnect::entity { auto count = xmlNodeDump(buf, child->doc, child, 0, 0); if (count > 0) { - str << (const char*)buf->content; + str << string((const char*)xmlBufferContent(buf), xmlBufferLength(buf)); } xmlBufferFree(buf); }