Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
JSSerialPort.hxx
Go to the documentation of this file.
1
35#ifndef _UTILS_JSSERIALPORT_HXX_
36#define _UTILS_JSSERIALPORT_HXX_
37
38#ifdef __EMSCRIPTEN__
39
40#include <emscripten.h>
41#include <emscripten/val.h>
42
43#include "utils/Hub.hxx"
44#include "utils/JSHubPort.hxx"
45
46class JSSerialPort
47{
48public:
53 JSSerialPort(CanHubFlow *hflow, string device,
54 std::function<void()> cb = []() {})
55 : canHub_(hflow)
56 , connectCallback_(std::move(cb))
57 {
58 string script = "Module.serial_device = '" + device + "';\n";
59 emscripten_run_script(script.c_str());
60 EM_ASM_(
61 {
62 var SerialPort = require('serialport');
63 var portdev = Module.serial_device;
64 console.log('Opening ' + portdev);
65 var openerror = function(error) {
66 console.log(
67 'Failed to open serial port ' + portdev + ': ' + error);
68 console.log('Known serial ports:');
69 require('@serialport/bindings')
70 .list()
71 .then(function(ports) {
72 ports.forEach(function(port) {
73 console.log('port "' + port.path +
74 '" pnp id: ' + port.pnpId +
75 ' manufacturer: ' + port.manufacturer);
76 });
77 });
78 };
79 var c;
80 try {
81 c = new SerialPort(
82 Module.serial_device, {baudRate : 115200});
83 } catch(err) {
84 openerror(err);
85 return;
86 }
87 c.on("open", function(error) {
88 if (error) {
89 openerror(error);
90 return;
91 }
92 console.log('opened ' + c);
93 var client_port = new Module.JSHubPort(
94 $0, function(data) { c.write(data); });
95 c.on('close', function() {
96 console.log('serial port ' + portdev + ' closed.');
97 client_port.abandon();
98 });
99 c.on('error', function(err) {
100 console.log('error on serial port ' + portdev + ': ' + err);
101 c.close();
102 client_port.abandon();
103 });
104 c.on('data', function(data) { client_port.recv(data.toString()); });
105 _invoke_fnp($1);
106 });
107 },
108 (unsigned long)canHub_, (unsigned long)&connectCallback_);
109 }
110
111 static void list_ports() {
112 EM_ASM(
113 {
114 console.log('Known serial ports:');
115 require('@serialport/bindings').list().then(function(ports)
116 {
117 ports.forEach(function(port)
118 {
119 console.log('port "' + port.path +
120 '" pnp id: ' + port.pnpId +
121 ' manufacturer: ' + port.manufacturer);
122 });
123 });
124 });
125 }
126
127private:
128 CanHubFlow *canHub_;
130 std::function<void()> connectCallback_;
131};
132
133#endif // __EMSCRIPTEN__
134#endif // _UTILS_JSTCPCLIENT_HXX_