diff --git a/src/utils/JSHubPort.cxx b/src/utils/JSHubPort.cxx index 6aa7e2768..7a3dd923d 100644 --- a/src/utils/JSHubPort.cxx +++ b/src/utils/JSHubPort.cxx @@ -34,7 +34,18 @@ #ifdef __EMSCRIPTEN__ +#include + extern int JSHubPort_debug_port_num; int JSHubPort_debug_port_num = 0; +/// Invokes a function pointer. +extern "C" void __attribute__((used)) invoke_fnp(std::function *fp) +{ + if (fp && *fp) + { + (*fp)(); + } +} + #endif // __EMSCRIPTEN__ diff --git a/src/utils/JSSerialPort.hxx b/src/utils/JSSerialPort.hxx index b09593923..461c14770 100644 --- a/src/utils/JSSerialPort.hxx +++ b/src/utils/JSSerialPort.hxx @@ -46,8 +46,14 @@ class JSSerialPort { public: - JSSerialPort(CanHubFlow *hflow, string device) + /// Constructor + /// @param hflow the CAN hub object in the local binary to add this port to. + /// @param device the serial device name (see list_ports output) + /// @param cb will be invoked when the connection succeeds + JSSerialPort(CanHubFlow *hflow, string device, + std::function cb = []() {}) : canHub_(hflow) + , connectCallback_(std::move(cb)) { string script = "Module.serial_device = '" + device + "';\n"; emscripten_run_script(script.c_str()); @@ -96,9 +102,10 @@ public: client_port.abandon(); }); c.on('data', function(data) { client_port.recv(data.toString()); }); + _invoke_fnp($1); }); }, - (unsigned long)canHub_); + (unsigned long)canHub_, (unsigned long)&connectCallback_); } static void list_ports() { @@ -119,6 +126,8 @@ public: private: CanHubFlow *canHub_; + /// This function will be invoked when the connection succeeds. + std::function connectCallback_; }; #endif // __EMSCRIPTEN__ diff --git a/src/utils/JSTcpClient.hxx b/src/utils/JSTcpClient.hxx index 30ed27c31..54046ce91 100644 --- a/src/utils/JSTcpClient.hxx +++ b/src/utils/JSTcpClient.hxx @@ -47,11 +47,20 @@ class JSTcpClient { public: - JSTcpClient(CanHubFlow *hflow, string host, int port) + /// Constructor + /// @param hflow the CAN hub object in the local binary to add this port to. + /// @param host the IP address or name of the remote host + /// @param port the TCP port number to connect to + /// @param cb will be invoked when the connection succeeds + JSTcpClient( + CanHubFlow *hflow, string host, int port, + std::function cb = []() {}) : canHub_(hflow) + , connectCallback_(std::move(cb)) { string script = "Module.remote_server = '" + host + "';\n"; emscripten_run_script(script.c_str()); + EM_ASM_( { var net = require('net'); @@ -73,13 +82,16 @@ public: client_port.abandon(); }); c.on('data', function(data) { client_port.recv(data); }); + _invoke_fnp($2); }); }, - port, (unsigned long)canHub_); + port, (unsigned long)canHub_, (unsigned long)&connectCallback_); } private: CanHubFlow *canHub_; + /// This function will be invoked when the connection succeeds. + std::function connectCallback_; }; #endif // __EMSCRIPTEN__