2#include <ossia/network/context.hpp>
3#include <ossia/network/sockets/udp_socket.hpp>
4#include <ossia/network/sockets/websocket_client.hpp>
6#include <ossia-qt/protocols/utils.hpp>
12#include <nano_observer.hpp>
18class qml_websocket_outbound_socket
20 ,
public Nano::Observer
21 ,
public protocols_sender
23 W_OBJECT(qml_websocket_outbound_socket)
28 std::unique_ptr<ossia::net::websocket_client> client;
29 std::atomic_bool alive{
true};
32 qml_websocket_outbound_socket(
33 const ossia::net::outbound_socket_configuration& conf,
34 boost::asio::io_context& ctx)
35 : m_state{std::make_shared<state>()}
37 m_state->url =
"ws://" + conf.host +
":" + std::to_string(conf.port);
39 auto self = QPointer{
this};
40 m_state->client = std::make_unique<ossia::net::websocket_client>(
41 ctx, [st, self](
auto hdl,
auto opcode,
const std::string& msg) {
44 if(
auto* ptr = self.get())
45 ptr->on_message(hdl, opcode, msg);
48 if(onOpen.isCallable())
49 m_state->client->on_open.connect<&qml_websocket_outbound_socket::on_open>(
this);
50 if(onClose.isCallable())
51 m_state->client->on_close.connect<&qml_websocket_outbound_socket::on_close>(
this);
52 if(onError.isCallable())
53 m_state->client->on_fail.connect<&qml_websocket_outbound_socket::on_fail>(
this);
56 ~qml_websocket_outbound_socket() { m_state->alive =
false; }
58 inline boost::asio::io_context& context() noexcept
60 return m_state->client->context();
63 void open() { m_state->client->connect(m_state->url); }
65 void on_message(
auto hdl,
auto opcode,
const std::string& msg)
67 if(opcode == websocketpp::frame::opcode::text && onTextMessage.isCallable())
69 onTextMessage.call({QString::fromStdString(msg)});
71 else if(opcode == websocketpp::frame::opcode::binary && onBinaryMessage.isCallable())
74 {qjsEngine(
this)->toScriptValue(QByteArray(msg.data(), msg.size()))});
83 this, [=,
this] { onOpen.call({qjsEngine(
this)->newQObject(
this)}); },
90 ossia::qt::run_async(
this, [=,
this] { onError.call(); }, Qt::AutoConnection);
96 ossia::qt::run_async(
this, [=,
this] { onClose.call(); }, Qt::AutoConnection);
99 void write(QString message)
102 boost::asio::dispatch(
103 st->client->context(),
104 [st, msg = message.toStdString()] {
106 st->client->send_message(msg);
111 void writeBinary(QByteArray buffer)
114 boost::asio::dispatch(
115 st->client->context(),
116 [st, buf = std::string(buffer.data(), buffer.size())] {
118 st->client->send_binary_message(buf);
125 m_state->client->stop();
126 if(onClose.isCallable())
138 QJSValue onTextMessage;
139 QJSValue onBinaryMessage;
142 std::shared_ptr<state> m_state;
Definition qml_device.cpp:43