-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket.js
243 lines (225 loc) · 7.24 KB
/
websocket.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
var express = require('express');
const classes = require('./classes');
var app = require('express')();
var path = require('path');
var http = require('http').Server(app);
const queue = require('async/queue');
const mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var times = {};
//mongoose.connect('mongodb://localhost/testdb');
config = {
DB: 'mongodb://localhost:27017/tryone',
};
mongoose.connect(config.DB, { useNewUrlParser: true, useFindAndModify: false, useUnifiedTopology: true }).then(
() => {
console.log('Database is connected');
},
(err) => {
console.log('Can not connect to the database' + err);
}
);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'Connection Error:'));
var io = require('socket.io');
var server = require('http').createServer(app);
var socket = io(server);
let collectionName = 'default';
socket.on('connection', (client) => {
let changeStream;
client.on('event', (msg) => {
saveEvent(msg);
});
client.on('clear', () => {
clearPlots();
});
client.on('db', (msg) => {
socket.emit(collectionName, 'connected to DB');
createDocsIfNotExists(msg, prefixes1);
collectionName = msg;
// changeStream = openChangeStream(msg);
// changeStream.on('change', (change) => {
// if (change.operationType === 'update') {
// socket.emit(collectionName, { type: change.documentKey._id, data: change.updateDescription.updatedFields });
// }
// });
});
console.log('user connected');
client.on('disconnect', () => {
console.log('user disconnected');
if (changeStream) {
changeStream.close();
}
});
});
db.once('open', () => {
server.listen(9090, () => {
console.log('listening on *:90');
});
});
app.use(express.static(path.join(__dirname, 'public')));
//adding the form page to collect patient data
app.get('/', function (req, res) {
// res.sendFile(__dirname + '/form.html');
res.sendFile(__dirname + '/plots_page.html');
});
app.get('/plots', function (req, res) {
res.sendFile(__dirname + '/plots_page.html');
});
app.post('/save', function (req, res) {
console.log(req.body);
});
//to save patient data entered in the form to mongodb
app.post('/patient-data', function (req, res) {
//console.log('req', req.body);
var myData = createNewUser(req.body);
console.log('mydata', myData);
myData.save(function (err, results) {
console.log(err);
let uid = results._id;
//console.log(results);
res.redirect('/plots?id=' + results.fname + results.lname);
});
});
//setting collectionName to patient name
function createNewUser(data) {
const nameSchema = new mongoose.Schema(
{
fname: String,
lname: String,
age: Number,
height: Number,
weight: Number,
gender: String,
phone: Number,
condition: String,
comment: String,
},
{ collectionName: data.fname + data.lname }
);
const User = mongoose.model('User', nameSchema);
return new User(data);
}
async function getName(uid) {
let document = await User.findById(uid);
console.log(document);
return document.fname + ' ' + document.lname;
}
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8011 });
const wss2 = new WebSocket.Server({ port: 8012 });
wss.on('connection', function connection(ws, req) {
const ip = req.socket.remoteAddress;
console.log('New connection from', ip);
let messengers = {}; // create front end messengers
prefixes1.forEach((signal) => {
messengers[signal] = new classes.Messenger(signal);
});
ws.on('message', function incoming(message) {
let msg;
try {
msg = JSON.parse(message);
Object.keys(msg).forEach((key) => {
// sending to the frontend
if (msg[key].length != 0) {
// avoid empty messages
let frontendMsg = messengers[key].send(msg[key]);
socket.emit('signals', frontendMsg);
}
});
processTransmission(msg, q);
} catch (err) {
msg = message;
console.log('processing error', err.message, msg);
}
});
ws.on('close', function informDisconnect() {
console.log('Device Disconnected');
});
ws.send('acknowledge connection');
});
// //npm install async
const q = queue(function (task, cb) {
// console.log(task);
db.collection(collectionName).updateOne(
{ _id: task.docname },
{ $push: { [task.field]: { $each: task.processed_data }, ['timeStamps']: { $each: task.time } } },
// { upsert: true },
(err) => {
if (err) console.log('DB error:', err);
cb();
}
);
}, 1);
var prefixes1 = ['PData', 'SData', 'TData', 'BData', 'EData', 'PCData', 'SCData', 'TCData', 'BCData', 'WData', 'WCData', 'YData', 'YCData']; // PAT,ECG,Temp,SpO2,BioZ
function openChangeStream(collection) {
const taskCollection = db.collection(collection);
const changeStream = taskCollection.watch();
return changeStream;
}
function processTransmission(req, que) {
// console.table(req);
const d = new Date();
let timeInt = d.getTime();
Object.keys(req).forEach((key) => {
// docname = collectionName + key.toString();
if (req[key].length != 0) {
const processed_data = req[key];
let time = Array(processed_data.length).fill(timeInt);
//pusing to database one by one
que.push({ processed_data: processed_data, docname: key.toString(), field: 'values', time: time });
}
});
}
async function saveEvent(name) {
const d = new Date();
let timeInt = d.getTime();
db.collection(collectionName).updateOne({ _id: 'events' }, { $push: { [name]: timeInt } }, { upsert: true }, (err) => {
if (err) console.log('DB error:', err);
});
console.log('Saved', name, timeInt, collectionName);
}
async function clearPlots() {
const model = mongoose.connection.models['Recording'];
// console.log(model)
let promises = [];
prefixes1.forEach((el) => {
promises.push(
model.deleteOne({ name: el }, {}, function (error, result) {
if (error) return;
// console.log('Patient Document :', result);
})
);
});
await Promise.all(promises);
createDocsIfNotExists(collectionName, prefixes1);
console.log('Collection: ', collectionName, ' reset');
}
async function createDocsIfNotExists(collectionName, prefixes) {
delete mongoose.connection.models['Recording'];
const recordingSchema = new mongoose.Schema(
{
_id: String,
timeStamps: [[Number]],
values: [[Number]],
name: String,
},
{ collection: collectionName }
);
const Recording = mongoose.model('Recording', recordingSchema);
var update = { expire: new Date() },
options = { upsert: true, new: true, setDefaultsOnInsert: true };
let promises = [];
prefixes.forEach((el) => {
promises.push(
Recording.findOneAndUpdate({ _id: el, name: el }, update, options, function (error, result) {
if (error) return;
console.log('Patient Document :', result);
})
);
});
await Promise.all(promises);
}