diff options
| author | Felix Morgner <felix.morgner@gmail.com> | 2018-11-29 18:29:34 +0100 |
|---|---|---|
| committer | Felix Morgner <felix.morgner@gmail.com> | 2018-11-29 18:29:34 +0100 |
| commit | ca992f4f76d09965e4e62c805daa02b23266a224 (patch) | |
| tree | 07eaeae4e288832306c353dd46cd3c2e52b8b5db /src/control_connection.cpp | |
| parent | d018603b1ff8e93902e8c9c904199f54076154c4 (diff) | |
| download | wanda-ca992f4f76d09965e4e62c805daa02b23266a224.tar.xz wanda-ca992f4f76d09965e4e62c805daa02b23266a224.zip | |
control: begin control interface implementation
Diffstat (limited to 'src/control_connection.cpp')
| -rw-r--r-- | src/control_connection.cpp | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/src/control_connection.cpp b/src/control_connection.cpp new file mode 100644 index 0000000..88a136e --- /dev/null +++ b/src/control_connection.cpp @@ -0,0 +1,86 @@ +#include "control_connection.hpp" + +namespace wanda +{ + +control_connection::pointer make_control_connection(control_connection::protocol::socket &&socket) +{ + return std::make_shared<control_connection>(control_connection::key{}, std::move(socket)); +} + +control_connection::control_connection(control_connection::key key, control_connection::protocol::socket socket) + : keyed{key}, + m_socket{std::move(socket)} +{ +} + +bool control_connection::add(std::shared_ptr<control_connection::listener> listener) +{ + auto [_, inserted] = m_listeners.insert(listener); + return inserted; +} + +bool control_connection::remove(std::shared_ptr<control_connection::listener> listener) +{ + return m_listeners.erase(listener); +} + +void control_connection::start() +{ + if (!m_running) + { + m_running = true; + perform_read(); + } +} + +void control_connection::close() +{ + if (auto error = boost::system::error_code{}; m_socket.cancel(error)) + { + for (auto &listener : m_listeners) + { + listener->on_error(shared_from_this(), error); + } + } + + if (auto error = boost::system::error_code{}; m_socket.close(error)) + { + for (auto &listener : m_listeners) + { + listener->on_error(shared_from_this(), error); + } + } + + for (auto &listener : m_listeners) + { + listener->on_close(shared_from_this()); + } + m_listeners.clear(); +} + +void control_connection::perform_read() +{ + boost::asio::async_read_until(m_socket, m_in, '\n', [that = shared_from_this(), this](auto const &error, auto const length) { + if (error) + { + for (auto &listener : m_listeners) + { + listener->on_error(shared_from_this(), error); + } + close(); + } + else + { + std::string message{}; + std::getline(m_input, message); + for (auto &listener : m_listeners) + { + listener->on_received(shared_from_this(), message); + } + perform_read(); + } + }); +} + +} // namespace wanda
\ No newline at end of file |
