-
Notifications
You must be signed in to change notification settings - Fork 1
/
ModelDataClient.js
88 lines (80 loc) · 2.8 KB
/
ModelDataClient.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict';
const signalR = require("@microsoft/signalr");
const W3CWebSocket = require('websocket').w3cwebsocket;
const url = require('url');
const ModelController = require('./ModelController');
class ModelDataClient {
constructor(url, connected, callback) {
this.url = url;
this.connected = connected;
this.callback = callback;
this.connection = new signalR.HubConnectionBuilder().withUrl(this.url).build();
}
doNothing(obj) {
}
sendObject(object) {
// console.log('sendobject');
this.connection.invoke("ModelUpdated", object).catch(function (err) {
return console.error(err.toString());
});
}
verifyConnection() {
this.connection.invoke("AfterConnected").catch(function (err) {
return console.error(err.toString());
});
}
startSession() {
this.connection.on("Connected", (message) => {
// console.log("connected");
this.connected = true;
});
this.connection.on("Update", (obj) => {
// console.log("in update");
// console.log(obj);
return this.callback(obj)
});
this.connection.start()
.then(function (val) {
}).then(res => this.verifyConnection())
.catch(function (err) {
setTimeout(() => this.connection.start(), 5000);
return console.error(err.toString());
});
this.connection.onclose( () => {
// console.log('closed');
this.connected = false;
});
}
_addDataSource(port, dataIndex) {
let connectionString = `ws://localhost:${port}/`
console.log(`Attempting to connect to ${connectionString}`)
this.ws = new W3CWebSocket(connectionString, 'lws-minimal');
this.ws.onopen = function () {
console.log("WS connection successful");
console.log(`port number is: ${port}`)
}
this.ws.onerror = function () {
console.log("WS connection error");
}
this.ws.onclose = function () {
console.log("WS connection closed");
}
this.ws.onmessage = function incoming(data) {
let dataPacket = {}
dataPacket.index = dataIndex
dataPacket.value = data.data;
console.log(dataPacket)
this.connection.invoke("SendDataPacket", [dataPacket]).catch(function (err) {
return console.error(err.toString());
});
};
this.ws.onmessage = this.ws.onmessage.bind(this);
}
addDataSource(port, dataIndex) {
setTimeout(this._addDataSource.bind(this), 3000, port, dataIndex);
}
removeDataSource(){
this.ws.close();
}
}
module.exports = ModelDataClient