13#include "spdlog/sinks/rotating_file_sink.h"
15#include <asio/error.hpp>
16#include <asio/executor_work_guard.hpp>
17#include <asio/strand.hpp>
24#include <fmt/format.h>
25#include <fmt/ranges.h>
28#include <initializer_list>
31#include <source_location>
32#include <spdlog/common.h>
33#include <spdlog/logger.h>
34#include <spdlog/sinks/stdout_color_sinks.h>
35#include <spdlog/spdlog.h>
39#include <system_error>
52 auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
55 console_sink->set_pattern(
"[%H:%M:%S][%^%=6l%$][%t] %v");
59 console_sink->set_pattern(
"[%H:%M:%S][%^%=6l%$] %v");
61 auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
63 file_sink->set_level(spdlog::level::trace);
64 file_sink->set_pattern(
"[%Y-%m-%d %H:%M:%S][%l][%t] %v");
67 std::make_shared<spdlog::logger>(
"multi_sink", spdlog::sinks_init_list{ console_sink, file_sink });
68 logger->set_level(spdlog::level::trace);
70 console_sink->set_level(spdlog::level::off);
74 console_sink->set_level(spdlog::level::trace);
76 spdlog::register_logger(logger);
77 spdlog::set_default_logger(logger);
80 spdlog::info(
"Welcome to SRS Application");
97 switch_off_status == std::future_status::ready)
99 spdlog::info(fmt::format(fg(fmt::color::light_green) | fmt::emphasis::bold,
100 "🥳 FECs have been switched off successfully!"));
102 else if (switch_off_status == std::future_status::timeout)
104 spdlog::warn(
"Application: TIMEOUT while waiting for switching off process to finish.");
106 else if (switch_off_status == std::future_status::deferred)
108 spdlog::warn(
"Application: Switching off of FECs is pending.");
110 else if (not switch_off_status.has_value())
112 spdlog::debug(
"Application: FECs don't need switching off due to: {}", switch_off_status.error().message());
119 spdlog::debug(
"Application: Wait until working thread finishes ...");
121 spdlog::debug(
"Application: All tasks in main io_context are finished.");
145 fmt::format(fmt::emphasis::bold,
146 "📢 Application is running in non-stop mode. Press \"Ctrl-C\" to stop the application!"));
148 [
this](
const std::error_code& error,
auto)
152 spdlog::info(
"Calling SIGINT from the user input");
153 if (error == asio::error::operation_aborted)
162 spdlog::info(fmt::format(fmt::emphasis::bold,
163 "📢 Application is running in stop mode and will stop after {} seconds!",
167 [
this](
const std::error_code&)
187 auto current_loc = std::source_location::current();
188 auto monitoring_action = [
this, current_loc]()
192 auto _ =
ExitLogger{
"io_context join", current_loc };
195 catch (
const std::exception& ex)
197 spdlog::critical(
"Application: Exception on working thread occurred: {}", ex.what());
209 if (socket ==
nullptr)
215 if (status.has_value() and status.value() == std::future_status::timeout)
217 spdlog::warn(
"Application: TIMEOUT during waiting for the closing of input data stream.");
225 spdlog::debug(
"Application: exiting ...");
227 spdlog::default_logger()->flush();
228 spdlog::flush_every(std::chrono::seconds{ 1 });
230 auto err = std::error_code{};
237 switch_on_status == std::future_status::ready)
239 spdlog::debug(
"Application: FECs have been switched on successfully.");
242 else if (switch_on_status == std::future_status::timeout)
245 "Application: TIMEOUT during waiting for FECs to be switched on. Skipping switching off process.");
247 else if (switch_on_status == std::future_status::deferred)
249 spdlog::warn(
"Application: Switching on of FECs is pending. Skipping switching off process.");
253 spdlog::info(
"FECs were not switched on. Skipping switching off process.");
256 std::this_thread::sleep_for(std::chrono::milliseconds{
config_.time_wait_after_acq_off_ms });
267 config_.output_filenames = filenames;
268 config_.output_split = n_lines;
274 spdlog::info(
"Add the remote FEC with ip: {} and port: {}", remote_ip, port_number);
275 auto udp_endpoints = resolver.resolve(udp::v4(), remote_ip, fmt::format(
"{}", port_number));
277 if (udp_endpoints.begin() == udp_endpoints.end())
279 spdlog::debug(
"Application: Failed to add the FEC remote point");
285 template <
typename T>
291 [
this, connection_name](
const std::shared_ptr<connection::FecCommandSocket>& socket)
293 socket->set_report(
report_.get());
296 spdlog::info(
"Switching {} FEC device with remote endpoint {} ...", T::tag, remote_endpoint);
297 auto fec_connection = std::make_shared<T>(connection_name);
298 fec_connection->set_remote_endpoint(remote_endpoint);
299 fec_connection->send_message_from(socket);
301 auto res_fut = socket->cancel_listen_after(
io_context_);
302 socket->launch_send_actions();
311 spdlog::info(fmt::format(fmt::emphasis::bold,
"❗ Please wait until FEC devices are switched off"));
317 const auto& data_ports =
config_.fec_data_receive_ports;
319 if (
auto port = std::ranges::find(data_ports,
config_.fec_control_local_port); port != data_ports.end())
321 throw std::runtime_error(
322 std::format(
"Application: port number {} used for input data stream is not allowed to be the same "
323 "port number used for the local control port {}.",
325 config_.fec_control_local_port));
332 spdlog::info(
"Starting input data stream from local port number(s): [{}]...",
333 fmt::join(
config_.fec_data_receive_ports,
", "));
334 for (
const auto port_num :
config_.fec_data_receive_ports)
342 socket->set_report(
report_.get());
343 spdlog::debug(
"data stream is using the buffer size: {}",
config_.data_buffer_size);
347 if (not status.has_value())
349 spdlog::critical(
"Application: Cannot establish the connection for the input data stream because the "
351 "{} is not available.",
362 spdlog::info(
"Starting input data analysis workflow ...");
369 if (not switch_future->valid())
371 return std::unexpected{ asio::error::make_error_code(asio::error::basic_errors::invalid_argument) };
373 return switch_future.transform(
374 [](
const std::future<void>& switch_fut)
376 if (switch_fut.valid())
380 return std::future_status::ready;
386 for (
const auto& fec_ips :
config_.remote_fec_ips)
~App() noexcept
Destructor of the App class.
asio::executor_work_guard< io_context_type::executor_type > io_work_guard_
Asio io_context work guard.
void init()
Initialization of internal members.
SwitchFutureType switch_on_future_
void read_data(bool is_non_stop=true)
Start reading the input data stream from the port specified by srs::Config::fec_data_receive_port....
void set_output_filenames(const std::vector< std::string > &filenames, std::size_t n_lines=1)
Set the output filenames.
void add_remote_fec_endpoint(std::string_view remote_ip, int port_number)
asio::signal_set signal_set_
User signal handler for interrupts.
std::vector< udp::endpoint > remote_fec_endpoints_
Remote endpoints of FEC devices.
void exit_and_switch_off()
void start_workflow()
Start data analysis workflow, triggering data conversions.
std::jthread working_thread_
Main working thread.
void set_print_mode(common::DataPrintMode mode)
Set the print mode.
void switch_off()
Establish the communications to the available FECs to stop the data acquisition.
asio::steady_timer cancel_timer_
Cancelling timer.
std::vector< std::shared_ptr< connection::DataSocket > > data_sockets_
Communication to the main input data stream.
std::unique_ptr< AppReport > report_
std::unique_ptr< workflow::AnalysisHandle > workflow_handler_
The handler to the analysis working flow.
asio::strand< io_context_type::executor_type > fec_strand_
FEC communication strand for synchronous communications.
auto check_port_number_validity() -> bool
void set_remote_fec_endpoints()
static auto wait_for_switch_action(const SwitchFutureType &switch_future) -> SwitchFutureStatusType
SwitchFutureType switch_off_future_
io_context_type io_context_
Asio io_context that manages the task scheduling and network IO.
void print_statistics() const
std::jthread workflow_thread_
Main thread to run workflow.
void switch_on()
Establish the communications to the available FECs to start the data acquisition.
App(Config config)
Constructor of the App class.
std::size_t runtime_sec_
Time duration (seconds) to stop the application. If value is zero, the application is in non-stop mod...
auto switch_FECs(std::string_view connection_name) -> SwitchFutureType
std::expected< std::future< void >, std::error_code > SwitchFutureType
void wait_for_reading_finish()
std::expected< std::future_status, std::error_code > SwitchFutureStatusType
void action_after_destructor()
static auto create(int port_number, io_context_type &io_context, Args &&... args) -> std::expected< std::shared_ptr< SocketType >, std::error_code >
~AppExitHelper() noexcept
Destructor calling srs::App::end_of_work method.
constexpr auto file_logger_new_instance_str
constexpr auto rotating_file_nums
constexpr auto file_max_size
file size limited to 10 MB.
constexpr auto DEFAULT_STATUS_WAITING_TIME_SECONDS
DataPrintMode
Print mode of the status line.
auto get_default_log_path() -> std::filesystem::path
constexpr auto DEFAULT_SRS_CONTROL_PORT
Main configuration struct.