srs-control 0.2.2
Loading...
Searching...
No Matches
FECEmulator.cpp
Go to the documentation of this file.
1#include "FECEmulator.hpp"
10#include <algorithm>
11#include <asio/any_io_executor.hpp>
12#include <asio/as_tuple.hpp>
13#include <asio/awaitable.hpp>
14#include <asio/buffer.hpp>
15#include <asio/detached.hpp>
16#include <asio/impl/co_spawn.hpp>
17#include <asio/ip/address.hpp>
18#include <asio/ip/address_v4.hpp>
19#include <asio/ip/basic_endpoint.hpp>
20#include <asio/ip/udp.hpp>
21#include <asio/steady_timer.hpp>
22#include <asio/this_coro.hpp>
23#include <asio/use_awaitable.hpp>
24#include <asio/use_future.hpp>
25#include <chrono>
26#include <cstddef>
27#include <expected>
28#include <fmt/ranges.h>
29#include <magic_enum/magic_enum.hpp>
30#include <map>
31#include <random>
32#include <ranges>
33#include <spdlog/spdlog.h>
34#include <string>
35#include <string_view>
36#include <utility>
37#include <vector>
38
40{
41 namespace
42 {
43 auto get_msg_from_receive_type(FECEmulator::ReceiveType rec_type) -> std::string
44 {
45 using enum FECEmulator::ReceiveType;
46 switch (rec_type)
47 {
48 case invalid:
49 return {};
50 case acq_on:
51 {
52 auto acq_on_connect = connection::Starter{};
53 return std::string{ acq_on_connect.get_response_msg() };
54 }
55 case acq_off:
56 auto acq_off_connect = connection::Stopper{};
57 return std::string{ acq_off_connect.get_response_msg() };
58 }
59 return {};
60 }
61 auto get_send_msg_from_receive_type(FECEmulator::ReceiveType rec_type) -> std::string
62 {
63 auto buffer = process::SerializableMsgBuffer{};
64 using enum FECEmulator::ReceiveType;
65 switch (rec_type)
66 {
67 case invalid:
68 return {};
69 case acq_on:
70 {
71 auto acq_on_connect = connection::Starter{};
72 const auto& send_suffix = acq_on_connect.get_send_suffix();
73 buffer.serialize(send_suffix);
74 return std::string{ buffer.data() };
75 }
76 case acq_off:
77 auto acq_off_connect = connection::Stopper{};
78 const auto& send_suffix = acq_off_connect.get_send_suffix();
79 buffer.serialize(send_suffix);
80 return std::string{ buffer.data() };
81 }
82 return {};
83 }
84
85 auto check_receive_msg_type(std::string_view msg) -> FECEmulator::ReceiveType
86 {
87 using enum FECEmulator::ReceiveType;
88 static const auto msg_map = std::map<std::string, FECEmulator::ReceiveType>{
89 { get_send_msg_from_receive_type(acq_on), acq_on },
90 { get_send_msg_from_receive_type(acq_off), acq_off },
91 };
92 auto msg_iter = std::ranges::find_if(
93 msg_map, [msg](const auto& suffix_type) -> bool { return msg.ends_with(suffix_type.first); });
94 // auto msg_iter = msg_map.find_if(std::string{ msg }, );
95 spdlog::trace("msg_map available options {}",
96 fmt::join(msg_map | std::views::transform(
97 [](const auto& str_type) -> std::string
98 {
99 return fmt::format("{}: {:02x}",
100 magic_enum::enum_name(str_type.second),
101 fmt::join(str_type.first, " "));
102 }),
103 "\n"));
104 if (msg_iter == msg_map.end())
105 {
106 return invalid;
107 }
108 return msg_iter->second;
109 }
110 } // namespace
111
113 : io_context_{ &io_context }
114 , config_{ config }
115 , udp_socket_{ io_context,
116 asio::ip::udp::endpoint{ asio::ip::make_address_v4(config_.ip),
117 static_cast<asio::ip::port_type>(config_.port) } }
118 , struct_randomizer_{ Randomizer::Config{ .n_hits = config.n_hits, .n_markers = config.n_markers } }
119 , world_{ &world }
120 {
121 spdlog::debug("Emulator: binds to a local udp socket with port number: {} and ip address: {}",
122 udp_socket_.local_endpoint().port(),
123 udp_socket_.local_endpoint().address().to_string());
124 data_sender_wait_timer_->expires_at(std::chrono::system_clock::time_point::max());
125 }
126
128 {
129 spdlog::info("FEC with {} is active.", udp_socket_.local_endpoint());
130
131 if (config_.is_sent_data_only)
132 {
133 do_if_acq_on(io_context_->get_executor());
134 }
135 else
136 {
137 // NOLINTBEGIN (clang-analyzer-core.CallAndMessage)
138 asio::co_spawn(*io_context_, listen_coro(), asio::detached);
139 // NOLINTEND (clang-analyzer-core.CallAndMessage)
140 }
141 }
142
143 void FECEmulator::do_if_acq_on(asio::any_io_executor executor)
144 {
145 spdlog::info("FEC with {} is switched on. Start sending data.", udp_socket_.local_endpoint());
146 world_->reset_frame_counter();
147 is_switched_off_.store(false);
148 asio::co_spawn(executor, start_send_data(), asio::detached);
149 // spdlog::trace("Server: start_send_data spawned!");
150 }
151
153 {
154 spdlog::info("FEC with {} is switched off. Stop sending data.", udp_socket_.local_endpoint());
155 is_switched_off_.store(true);
156 }
157
158 auto FECEmulator::send_response(connection::udp::endpoint endpoint, ReceiveType result_type)
159 -> asio::awaitable<void>
160 {
161 const auto _ = ExitLogger{ config_.ip };
162 auto msg = get_msg_from_receive_type(result_type);
163 [[maybe_unused]] const auto size =
164 co_await udp_socket_.async_send_to(asio::buffer(msg), endpoint, asio::use_awaitable);
165 spdlog::trace("SRS server: sent the data {:02x} to the remote point {}", fmt::join(msg, " "), endpoint);
166 }
167
168 auto FECEmulator::listen_coro() -> asio::awaitable<void>
169 {
170 auto msg_buffer = std::vector<char>{};
171 msg_buffer.resize(common::SMALL_READ_MSG_BUFFER_SIZE);
172 auto executor = co_await asio::this_coro::executor;
173 for (;;)
174 {
175 spdlog::trace("Emulator: listening on the local port {}", udp_socket_.local_endpoint());
176 if (is_switched_off_.load())
177 {
178 spdlog::info("FEC with {} is ready for connections.", udp_socket_.local_endpoint());
179 }
180 auto remote_endpoint = asio::ip::udp::endpoint{};
181 auto msg_size =
182 co_await udp_socket_.async_receive_from(asio::buffer(msg_buffer), remote_endpoint, asio::use_awaitable);
183 auto msg = std::string_view{ msg_buffer.data(), msg_size };
184 auto result = check_receive_msg_type(msg);
185 spdlog::trace("Emulator: Request type {:?} received with the msg: {:02x} in ip: {}",
186 magic_enum::enum_name(result),
187 fmt::join(msg, " "),
188 config_.ip);
189 asio::co_spawn(*io_context_, send_response(std::move(remote_endpoint), result), asio::detached);
190
191 using enum ReceiveType;
192 switch (result)
193 {
194 case invalid:
195 break;
196 case acq_on:
197 do_if_acq_on(executor);
198 break;
199 case acq_off:
201 if (not world_->get_config().non_stop)
202 {
203 co_return;
204 }
205 break;
206 }
207 }
208 spdlog::info("Existing emulator");
209 }
210
211 auto FECEmulator::construct_binary_data() -> std::expected<std::size_t, std::string_view>
212 {
213 const auto frame_counter = world_->request_frame_counter();
214
215 struct_randomizer_.randomize_data_struct(data_struct_, { .frame_counter = frame_counter, .fec_id = fec_id_ });
216 return struct_serializer_.convert(&data_struct_);
217 }
218
219#if defined(__GNUC__) && !defined(__clang__)
220#pragma GCC diagnostic push
221#pragma GCC diagnostic ignored "-Wmismatched-new-delete"
222#endif
223 auto FECEmulator::start_send_data() -> asio::awaitable<void>
224 {
225 auto device = std::random_device{};
226 auto rand_gen = std::mt19937{ device() };
227 auto distrib = std::uniform_int_distribution<std::chrono::nanoseconds::rep>{ std::chrono::nanoseconds::rep{},
228 delay_time_ };
229 const auto _ = ExitLogger{ config_.ip };
230 auto total_size = std::size_t{ 0 };
232 asio::ip::udp::endpoint{ asio::ip::make_address("127.0.0.1"),
233 static_cast<asio::ip::port_type>(
234 config_.remote_data_port) } };
235
236 spdlog::debug(
237 "Emulator: Starting to send data to port {} from ip {} ...", config_.remote_data_port, config_.ip);
238 data_sending_control_.expires_after(std::chrono::seconds{ 1 });
239 co_await data_sending_control_.async_wait(asio::use_awaitable);
240
241 auto executor = co_await asio::this_coro::executor;
242
243 using asio::experimental::awaitable_operators::operator||;
244 auto cancel_timer_ = asio::steady_timer{ executor };
245 cancel_timer_.expires_at(asio::steady_timer::time_point::max());
246
247 while (not is_switched_off_.load())
248 {
249 const auto time_ns = distrib(rand_gen);
250 data_sending_control_.expires_after(std::chrono::nanoseconds{ time_ns });
251 co_await data_sending_control_.async_wait(asio::use_awaitable);
252
253 auto res = construct_binary_data();
254 if (not res)
255 {
256 spdlog::error("{}", res.error());
257 break;
258 }
259 auto read_str = struct_serializer_();
260
261 auto send_size = connection.send_sync_message(read_str);
262 total_size += send_size;
264
265 data_sending_control_.expires_after(std::chrono::nanoseconds{ delay_time_ - time_ns });
266 auto res_timer = co_await (data_sending_control_.async_wait(asio::use_awaitable) ||
267 cancel_timer_.async_wait(asio::use_awaitable));
268 if (res_timer.index() == 1)
269 {
270 spdlog::debug("Runtime has reached. Cancelling FEC data sending.");
271 break;
272 }
273 }
274 connection.close();
275 spdlog::debug(
276 "Emulator: reaching the end of send_data coroutine. Sent number of frames: {} and total data size: "
277 "{} from {}",
279 total_size,
280 udp_socket_.local_endpoint());
281 data_sender_wait_timer_->cancel();
282 data_sender_wait_timer_->expires_after(std::chrono::seconds{ 0 });
283 cancel_timer_.cancel();
284 cancel_timer_.expires_after(std::chrono::seconds{ 0 });
285 }
286#if defined(__GNUC__) && !defined(__clang__)
287#pragma GCC diagnostic pop
288#endif
289
290} // namespace srs::emulator
static auto get_send_suffix() -> const auto &
static auto get_send_suffix() -> const auto &
asio::steady_timer data_sending_control_
asio::ip::udp::socket udp_socket_
process::StructSerializer struct_serializer_
auto listen_coro() -> asio::awaitable< void >
auto start_send_data() -> asio::awaitable< void >
asio::thread_pool IOContextType
std::atomic< bool > is_switched_off_
void do_if_acq_on(asio::any_io_executor executor)
auto send_response(connection::udp::endpoint endpoint, ReceiveType result_type) -> asio::awaitable< void >
FECEmulator(const Config &config, World &world, IOContextType &io_context)
auto construct_binary_data() -> std::expected< std::size_t, std::string_view >
gsl::not_null< IOContextType * > io_context_
std::shared_ptr< asio::system_timer > data_sender_wait_timer_
gsl::not_null< World * > world_
std::chrono::nanoseconds::rep delay_time_
Emulators for FECs devices.
Definition World.hpp:17
constexpr auto SMALL_READ_MSG_BUFFER_SIZE