Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
JSWebsocketClient.hxx
Go to the documentation of this file.
1
36#ifndef _UTILS_JSWEBSOCKETCLIENT_HXX_
37#define _UTILS_JSWEBSOCKETCLIENT_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 JSWebsocketClient
48{
49public:
50 JSWebsocketClient(CanHubFlow* hflow, string server_js)
51 : canHub_(hflow) {
52 string script = "Module.ws_server = " + server_js + ";\n";
53 emscripten_run_script(script.c_str());
54 EM_ASM_(
55 {
56 var server_address = Module.ws_server;
57 try {
58 var WS = window.WebSocket || window.MozWebSocket;
59 } catch (err) {
60 var WS = require('websocket').w3cwebsocket;
61 }
62 /*var is_node = window ? false : true;
63 if (!is_node) {
64 console.log('using browser');
65 } else {
66 console.log('using nodejs');
67 }*/
68 var reconnect;
69 reconnect = function() {
70 console.log('NNNN connecting to ws server: ', server_address);
71 var connection = new WS(server_address);
72 var portnum;
73 var client_port = new Module.JSHubPort($0,
74 function(gc_text)
75 {
76 var json = JSON.stringify(
77 {type : 'gc_can_frame', data : gc_text});
78 if (connection.readyState == 1) {
79 connection.send(json);
80 } else {
81 console.log('Not sending frame ', gc_text,
82 ' because connection',portnum,'state = ',
83 connection.readyState);
84 }
85 });
86 portnum = client_port.get_port_num();
87 connection.onopen = function() {
88 console.log('ws connection',portnum,'established. starting stack.');
89 try {
90 Module.startStack();
91 } catch (e) {
92 if (e === 'SimulateInfiniteLoop') {
93 console.log('stack started.');
94 } else {
95 console.log('unknown exception ', e);
96 throw e;
97 }
98 }
99 };
100 connection.onerror = function (eee) {
101 console.log('Connection',portnum,'error: ', eee);
102 //client_port.abandon();
103 //connection.close();
104 //setTimeout(reconnect, 1000);
105 };
106 connection.onclose = function () {
107 console.log('Websocket',portnum,'closed.');
108 client_port.abandon();
109 connection.close();
110 delete connection;
111 console.log('Scheduling reconnect.');
112 setTimeout(reconnect, 1000);
113 };
114 connection.onmessage = function(message) {
115 try
116 {
117 var json = JSON.parse(message.data);
118 }
119 catch (e)
120 {
121 console.log(
122 'This doesnt look like a valid JSON: ',
123 message.data);
124 return;
125 }
126 if (json.type === 'gc_can_frame')
127 {
128 // Send can frame data to the hub port
129 client_port.recv(json.data);
130 } else {
131 console.log('Received data of unknown type: ',
132 json.type);
133 }
134 };
135 };
136 reconnect();
137 }, (unsigned long)canHub_);
138 }
139
140private:
141 CanHubFlow *canHub_;
142};
143
144#endif // __EMSCRIPTEN__
145#endif // _UTILS_JSWEBSOCKETCLIENT_HXX_