-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c67bff7
commit f90cd8f
Showing
2 changed files
with
54 additions
and
5 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,56 @@ | ||
const WebSocket = require('ws'); | ||
|
||
const url = require('url'); | ||
const wss = new WebSocket.Server({ | ||
port: 3000 | ||
}); | ||
|
||
wss.on('connection', (ws) => { | ||
console.log('New User Connected'); | ||
ws.on('message', (data) => { | ||
console.log(data); | ||
const clients = []; | ||
const webClients = []; | ||
const DATA = {}; | ||
|
||
wss.on('connection', (ws, req) => { | ||
const { query: { token, type } } = url.parse(req.url, true); | ||
if(token && type && type === 'web'){ | ||
ws.id = token; | ||
webClients.push(ws); | ||
console.log('New Web Client Connected', 'Clients: ' + clients.length, 'Web Clients: ' + webClients.length); | ||
} | ||
|
||
if(token && type && type === 'bridge') { | ||
ws.id = token; | ||
clients.push(ws); | ||
console.log('New User Connected:' + token, 'Clients: ' + clients.length, 'Web Clients: ' + webClients.length); | ||
} | ||
|
||
ws.on('message', (data) => { | ||
data = JSON.parse(data); | ||
DATA[ws.id] = data; | ||
const eegs = Object.values(DATA).map(e => e.rawEeg); | ||
const average = { | ||
rawEeg: eegs.reduce((r, a) => { | ||
a.forEach((b, i) => { | ||
r[i] = (r[i] || 0) + b; | ||
}); | ||
return r; | ||
}, []).map(e => e / clients.length), | ||
timestamp: new Date().getTime() | ||
} | ||
webClients.forEach((ws) => { | ||
ws.send(JSON.stringify(average)); | ||
}); | ||
}); | ||
ws.on('close', () => { | ||
if(clients.findIndex(w => w.id === ws.id) > -1) { | ||
clients.splice(clients.findIndex(w => w.id === ws.id), 1); | ||
} | ||
if(webClients.findIndex(w => w.id === ws.id) > -1) { | ||
webClients.splice(webClients.findIndex(w => w.id === ws.id), 1); | ||
} | ||
try { | ||
delete DATA[ws.id]; | ||
console.log('User Disconnected:' + ws.id, 'Clients: ' + clients.length, 'Web Clients: ' + webClients.length); | ||
} catch (error) { | ||
|
||
} | ||
}); | ||
}); |