Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
JSTcpClient.hxx
Go to the documentation of this file.
1
36#ifndef _UTILS_JSTCPCLIENT_HXX_
37#define _UTILS_JSTCPCLIENT_HXX_
38
39#ifdef __EMSCRIPTEN__
40
41#include <emscripten.h>
42#include <emscripten/val.h>
43
44#include "utils/Hub.hxx"
45#include "utils/JSHubPort.hxx"
46
47class JSTcpClient : private JSHubFeedback
48{
49public:
51 enum ConnectionFeedback {
52 CONNECTION_UP,
53 CONNECTION_DOWN,
54 CONNECTION_ERROR
55 };
56
62 JSTcpClient(CanHubFlow *hflow, string host, int port,
63 std::function<void(ConnectionFeedback)> cb = nullptr)
64 : canHub_(hflow)
65 , callback_(std::move(cb))
66 {
67 string script = "Module.remote_server = '" + host + "';\n";
68 emscripten_run_script(script.c_str());
69
70 EM_ASM_(
71 {
72 var net = require('net');
73 console.log(
74 'Connecting to ' + Module.remote_server + ": " + $0);
75 var c = net.connect($0, Module.remote_server, function() {
76 console.log('connected to hub: ' + c);
77 c.setEncoding('utf-8');
78 c.setTimeout(0);
79 c.setKeepAlive(true);
80 var client_port = new Module.JSHubPort(
81 $1, function(data) { c.write(data); }, $2);
82 c.on('close', function() {
83 console.log('connection lost');
84 client_port.fb_close();
85 client_port.abandon();
86 });
87 c.on('error', function(err) {
88 console.log('connection error -- disconnected');
89 client_port.fb_error(err.toString());
90 client_port.abandon();
91 });
92 c.on('data', function(data) { client_port.recv(data); });
93 });
94 c.on('error', function(err) {
95 console.log('Failed to connect.');
96 Module.JSHubFeedback.call_on_error($2, err.toString());
97 });
98 },
99 port, (unsigned long)canHub_, (unsigned long)((JSHubFeedback*)this));
100 }
101
103 bool is_connected()
104 {
105 return connected_;
106 }
107
108private:
109
111 void on_open() override
112 {
113 connected_ = true;
114 LOG(INFO, "connected");
115 if (callback_)
116 {
117 callback_(CONNECTION_UP);
118 }
119 }
120
122 void on_close() override
123 {
124 connected_ = false;
125 LOG(INFO, "closed");
126 if (callback_)
127 {
128 callback_(CONNECTION_DOWN);
129 }
130 }
131
133 void on_error(string error) override
134 {
135 LOG(INFO, "%s", error.c_str());
136 connected_ = false;
137 if (callback_)
138 {
139 callback_(CONNECTION_ERROR);
140 }
141 }
142
143 CanHubFlow *canHub_;
144 bool connected_ = false;
145 std::function<void(ConnectionFeedback)> callback_;
146};
147
148#endif // __EMSCRIPTEN__
149#endif // _UTILS_JSTCPCLIENT_HXX_
#define LOG(level, message...)
Conditionally write a message to the logging output.
Definition logging.h:99
static const int INFO
Loglevel that is printed by default, reporting some status information.
Definition logging.h:57