OSSIA
Open Scenario System for Interactive Application
Loading...
Searching...
No Matches
qml_udp_inbound_socket.hpp
1#pragma once
2#include <ossia/network/context.hpp>
3#include <ossia/network/sockets/udp_socket.hpp>
4
5#include <ossia-qt/protocols/utils.hpp>
6
7#include <QJSValue>
8#include <QObject>
9#include <QQmlEngine>
10
11#include <nano_observer.hpp>
12
13#include <verdigris>
14
15namespace ossia::qt
16{
17class qml_udp_inbound_socket
18 : public QObject
19 , public Nano::Observer
20{
21 W_OBJECT(qml_udp_inbound_socket)
22public:
23 struct state
24 {
25 ossia::net::udp_receive_socket socket;
26 std::atomic_bool alive{true};
27
28 state(
29 const ossia::net::inbound_socket_configuration& conf,
30 boost::asio::io_context& ctx)
31 : socket{conf, ctx}
32 {
33 }
34 };
35
36 qml_udp_inbound_socket(
37 const ossia::net::inbound_socket_configuration& conf, boost::asio::io_context& ctx)
38 : m_state{std::make_shared<state>(conf, ctx)}
39 {
40 }
41
42 ~qml_udp_inbound_socket() { m_state->alive = false; }
43
44 inline boost::asio::io_context& context() noexcept { return m_state->socket.m_context; }
45
46 void open()
47 {
48 if(onClose.isCallable())
49 m_state->socket.on_close.connect<&qml_udp_inbound_socket::on_close>(*this);
50
51 m_state->socket.open();
52 if(onOpen.isCallable())
53 onOpen.call({qjsEngine(this)->newQObject(this)});
54
55 auto st = m_state;
56 auto self = QPointer{this};
57 st->socket.receive([st, self](const char* data, std::size_t sz) {
58 if(!st->alive)
59 return;
60 ossia::qt::run_async(
61 self.get(),
62 [self, arg = QByteArray(data, sz)] {
63 if(!self.get())
64 return;
65 if(self->onMessage.isCallable())
66 {
67 self->onMessage.call({qjsEngine(self.get())->toScriptValue(arg)});
68 }
69 },
70 Qt::AutoConnection);
71 });
72 }
73
74 void on_close()
75 {
76 if(!m_state->alive)
77 return;
78 ossia::qt::run_async(this, [=, this] { onClose.call(); }, Qt::AutoConnection);
79 }
80
81 void close() { m_state->socket.close(); }
82 W_SLOT(close)
83
84 QJSValue onOpen;
85 QJSValue onClose;
86 QJSValue onError;
87 QJSValue onMessage;
88
89private:
90 std::shared_ptr<state> m_state;
91};
92
93}
Definition qml_device.cpp:43