-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstart.js
1353 lines (1234 loc) · 47.4 KB
/
start.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const WebSocket = require('ws');
const path = require('path');
// Requires:
const { convertArrayToCSV } = require('convert-array-to-csv');
const converter = require('convert-array-to-csv');
var dir_path="";
var means_marker = [];
const express = require ('express');
const app = express();
var http = require('http').Server(app);
const port = 3000;
app.use(express.static('public'))
const server = http.listen(port, () => {
console.log(`Server is running on port ${port}!`)
});
app.get('/socket.io-file-client.js', (req, res, next) => {
return res.sendFile(__dirname + '/node_modules/socket.io-file-client/socket.io-file-client.js');
});
var io = require('socket.io')(http,{path:'/connection/eeg'});
var fs = require('fs');
const SocketIOFile = require('socket.io-file');
/**
* Looks for all the instances of a word, and replaces it
* @param {String} search word that will be searched
* @param {String} replacement Word that will be the replacement
* @returns Changes the document to a new version with the words replaced
*/
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
var experiment = "";
var id = "";
var on_record = false;
var duration = 0;
var record_name = "";
var on_wait = false;
var ready = false;
var writer;
var to_record_data = [];
var to_record_data_ML = [];
var finished = true;
var number_of_step = 0;
var r_lat = false;
var lat = 0;
var state = ["","", ""];
/**
* This class handle:
* - create websocket connection
* - handle request for : headset , request access, control headset ...
* - handle 2 main flows : sub and train flow
* - use async/await and Promise for request need to be run on sync
*/
class Cortex {
constructor (user, socketUrl) {
// create socket
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
this.socket = new WebSocket(socketUrl)
// read user infor
this.user = user
}
queryHeadsetId(){
const QUERY_HEADSET_ID = 2
let socket = this.socket
let queryHeadsetRequest = {
"jsonrpc": "2.0",
"id": QUERY_HEADSET_ID,
"method": "queryHeadsets",
"params": {}
}
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(queryHeadsetRequest));
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==QUERY_HEADSET_ID){
// console.log(data)
// console.log(JSON.parse(data)['result'].length)
if(JSON.parse(data)['result'].length > 0){
let headsetId = JSON.parse(data)['result'][0]['id']
resolve(headsetId)
}
else{
console.log('No have any headset, please connect headset with your pc.')
}
}
} catch (error) {}
})
})
}
requestAccess(){
let socket = this.socket
let user = this.user
return new Promise(function(resolve, reject){
const REQUEST_ACCESS_ID = 1
let requestAccessRequest = {
"jsonrpc": "2.0",
"method": "requestAccess",
"params": {
"clientId": user.clientId,
"clientSecret": user.clientSecret
},
"id": REQUEST_ACCESS_ID
}
// console.log('start send request: ',requestAccessRequest)
socket.send(JSON.stringify(requestAccessRequest));
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==REQUEST_ACCESS_ID){
resolve(data)
}
} catch (error) {}
})
})
}
authorize(){
let socket = this.socket
let user = this.user
return new Promise(function(resolve, reject){
const AUTHORIZE_ID = 4
let authorizeRequest = {
"jsonrpc": "2.0", "method": "authorize",
"params": {
"clientId": user.clientId,
"clientSecret": user.clientSecret,
"license": user.license,
"debit": user.debit
},
"id": AUTHORIZE_ID
}
socket.send(JSON.stringify(authorizeRequest))
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==AUTHORIZE_ID){
let cortexToken = JSON.parse(data)['result']['cortexToken']
resolve(cortexToken)
}
} catch (error) {}
})
})
}
controlDevice(headsetId){
let socket = this.socket
const CONTROL_DEVICE_ID = 3
let controlDeviceRequest = {
"jsonrpc": "2.0",
"id": CONTROL_DEVICE_ID,
"method": "controlDevice",
"params": {
"command": "connect",
"headset": headsetId
}
}
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(controlDeviceRequest));
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==CONTROL_DEVICE_ID){
resolve(data)
}
} catch (error) {}
})
})
}
createSession(authToken, headsetId){
let socket = this.socket
const CREATE_SESSION_ID = 5
let createSessionRequest = {
"jsonrpc": "2.0",
"id": CREATE_SESSION_ID,
"method": "createSession",
"params": {
"cortexToken": authToken,
"headset": headsetId,
"status": "active"
}
}
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(createSessionRequest));
socket.on('message', (data)=>{
// console.log(data)
try {
if(JSON.parse(data)['id']==CREATE_SESSION_ID){
let sessionId = JSON.parse(data)['result']['id']
resolve(sessionId)
}
} catch (error) {}
})
})
}
startRecord(authToken, sessionId, recordName){
let socket = this.socket
const CREATE_RECORD_REQUEST_ID = 11
let createRecordRequest = {
"jsonrpc": "2.0",
"method": "updateSession",
"params": {
"cortexToken": authToken,
"session": sessionId,
"status": "startRecord",
"title": recordName,
"description":"test_marker",
"groupName": "QA"
},
"id": CREATE_RECORD_REQUEST_ID
}
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(createRecordRequest));
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==CREATE_RECORD_REQUEST_ID){
console.log('CREATE RECORD RESULT --------------------------------')
console.log(data)
resolve(data)
}
} catch (error) {}
})
})
}
injectMarkerRequest(authToken, sessionId, label, value, port, time){
let socket = this.socket
const INJECT_MARKER_REQUEST_ID = 13
let injectMarkerRequest = {
"jsonrpc": "2.0",
"id": INJECT_MARKER_REQUEST_ID,
"method": "injectMarker",
"params": {
"cortexToken": authToken,
"session": sessionId,
"label": label,
"value": value,
"port": port,
"time": time
}
}
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(injectMarkerRequest));
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==INJECT_MARKER_REQUEST_ID){
console.log('INJECT MARKER RESULT --------------------------------')
console.log(data)
resolve(data)
}
} catch (error) {}
})
})
}
stopRecord(authToken, sessionId, recordName){
let socket = this.socket
const STOP_RECORD_REQUEST_ID = 12
let stopRecordRequest = {
"jsonrpc": "2.0",
"method": "updateSession",
"params": {
"cortexToken": authToken,
"session": sessionId,
"status": "stopRecord",
"title": recordName,
"description":"test_marker",
"groupName": "QA"
},
"id": STOP_RECORD_REQUEST_ID
}
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(stopRecordRequest));
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==STOP_RECORD_REQUEST_ID){
console.log('STOP RECORD RESULT --------------------------------')
console.log(data)
resolve(data)
}
} catch (error) {}
})
})
}
addMarker(){
this.socket.on('open',async ()=>{
await this.checkGrantAccessAndQuerySessionInfo()
let recordName = 'test_marker'
await this.startRecord(this.authToken, this.sessionId, recordName)
let thisInjectMarker = this
let numberOfMarker = 10
for (let numMarker=0; numMarker<numberOfMarker; numMarker++){
setTimeout(async function(){
// injectMarkerRequest(authToken, sessionId, label, value, port, time)
let markerLabel = "marker_number_" + numTrain
let markerTime = Date.now()
let marker = {
label:markerLabel,
value:"test",
port:"test",
time:markerTime
}
await thisInjectMarker.injectMarkerRequest( thisInjectMarker.authToken,
thisInjectMarker.sessionId,
marker.label,
marker.value,
marker.port,
marker.time)
}, 3000)
}
await thisStopRecord.stopRecord(thisStopRecord.authToken, thisStopRecord.sessionId, recordName)
})
}
subRequest(stream, authToken, sessionId){
let socket = this.socket
const SUB_REQUEST_ID = 6
let subRequest = {
"jsonrpc": "2.0",
"method": "subscribe",
"params": {
"cortexToken": authToken,
"session": sessionId,
"streams": stream
},
"id": SUB_REQUEST_ID
}
console.log('sub eeg request: ', subRequest)
socket.send(JSON.stringify(subRequest))
socket.on('message', (data)=>{
try {
// to show:
// if(JSON.parse(data)['id']==SUB_REQUEST_ID){
//console.log('SUB REQUEST RESULT --------------------------------')
//console.log(data)
//console.log('\r\n')
// }
} catch (error) {}
})
}
mentalCommandActiveActionRequest(authToken, sessionId, profile, action){
let socket = this.socket
const MENTAL_COMMAND_ACTIVE_ACTION_ID = 10
let mentalCommandActiveActionRequest = {
"jsonrpc": "2.0",
"method": "mentalCommandActiveAction",
"params": {
"cortexToken": authToken,
"status": "set",
"session": sessionId,
"profile": profile,
"actions": action
},
"id": MENTAL_COMMAND_ACTIVE_ACTION_ID
}
// console.log(mentalCommandActiveActionRequest)
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(mentalCommandActiveActionRequest))
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==MENTAL_COMMAND_ACTIVE_ACTION_ID){
console.log('MENTAL COMMAND ACTIVE ACTION RESULT --------------------')
console.log(data)
console.log('\r\n')
resolve(data)
}
} catch (error) {
}
})
})
}
/**
* - query headset infor
* - connect to headset with control device request
* - authentication and get back auth token
* - create session and get back session id
*/
async querySessionInfo(){
let headsetId=""
await this.queryHeadsetId().then((headset)=>{headsetId = headset})
this.headsetId = headsetId
let ctResult=""
await this.controlDevice(headsetId).then((result)=>{ctResult=result})
this.ctResult = ctResult
console.log(ctResult)
let authToken=""
await this.authorize().then((auth)=>{authToken = auth})
this.authToken = authToken
let sessionId = ""
await this.createSession(authToken, headsetId).then((result)=>{sessionId=result})
this.sessionId = sessionId
console.log('HEADSET ID -----------------------------------')
console.log(this.headsetId)
console.log('\r\n')
console.log('CONNECT STATUS -------------------------------')
console.log(this.ctResult)
console.log('\r\n')
console.log('AUTH TOKEN -----------------------------------')
console.log(this.authToken)
console.log('\r\n')
console.log('SESSION ID -----------------------------------')
console.log(this.sessionId)
console.log('\r\n')
}
/**
* - check if user logined
* - check if app is granted for access
* - query session info to prepare for sub and train
*/
async checkGrantAccessAndQuerySessionInfo(){
let requestAccessResult = ""
await this.requestAccess().then((result)=>{requestAccessResult=result})
let accessGranted = JSON.parse(requestAccessResult)
// check if user is logged in CortexUI
if ("error" in accessGranted){
console.log('You must login on CortexUI before request for grant access then rerun')
throw new Error('You must login on CortexUI before request for grant access')
}else{
console.log(accessGranted['result']['message'])
// console.log(accessGranted['result'])
if(accessGranted['result']['accessGranted']){
await this.querySessionInfo()
}
else{
console.log('You must accept access request from this app on CortexUI then rerun')
throw new Error('You must accept access request from this app on CortexUI')
}
}
}
/**
*
* - check login and grant access
* - subcribe for stream
* - logout data stream to console or file
*/
sub(streams){
this.socket.on('open',async ()=>{
await this.checkGrantAccessAndQuerySessionInfo()
this.subRequest(streams, this.authToken, this.sessionId)
this.socket.on('message', (data)=>{
// log stream data to file or console here
var json_data=JSON.parse(data);
io.sockets.emit('data',json_data.eeg);
if (json_data.eeg !== undefined){
if (on_record){
json_data.eeg[18] = means_marker + "." + number_of_step;
if (r_lat){
json_data.eeg[19] = lat;
}else{
json_data.eeg[19] = number_of_step;
}
to_record_data[record_index] = json_data.eeg;
record_index = record_index + 1;
}
}
if (json_data.dev!== undefined){
io.sockets.emit('dev', json_data.dev);
}
})
})
}
setupProfile(authToken, headsetId, profileName, status){
const SETUP_PROFILE_ID = 7
let setupProfileRequest = {
"jsonrpc": "2.0",
"method": "setupProfile",
"params": {
"cortexToken": authToken,
"headset": headsetId,
"profile": profileName,
"status": status
},
"id": SETUP_PROFILE_ID
}
// console.log(setupProfileRequest)
let socket = this.socket
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(setupProfileRequest));
socket.on('message', (data)=>{
if(status=='create'){
resolve(data)
}
try {
// console.log('inside setup profile', data)
if(JSON.parse(data)['id']==SETUP_PROFILE_ID){
if(JSON.parse(data)['result']['action']==status){
console.log('SETUP PROFILE -------------------------------------')
console.log(data)
console.log('\r\n')
resolve(data)
}
}
} catch (error) {
}
})
})
}
queryProfileRequest(authToken){
const QUERY_PROFILE_ID = 9
let queryProfileRequest = {
"jsonrpc": "2.0",
"method": "queryProfile",
"params": {
"cortexToken": authToken
},
"id": QUERY_PROFILE_ID
}
let socket = this.socket
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(queryProfileRequest))
socket.on('message', (data)=>{
try {
if(JSON.parse(data)['id']==QUERY_PROFILE_ID){
// console.log(data)
resolve(data)
}
} catch (error) {
}
})
})
}
/**
* - handle send training request
* - handle resolve for two difference status : start and accept
*/
trainRequest(authToken, sessionId, action, status){
const TRAINING_ID = 8
const SUB_REQUEST_ID = 6
let trainingRequest = {
"jsonrpc": "2.0",
"method": "training",
"params": {
"cortexToken": authToken,
"detection": "mentalCommand",
"session": sessionId,
"action": action,
"status": status
},
"id": TRAINING_ID
}
// console.log(trainingRequest)
// each train take 8 seconds for complete
console.log('YOU HAVE 8 SECONDS FOR THIS TRAIN')
console.log('\r\n')
let socket = this.socket
return new Promise(function(resolve, reject){
socket.send(JSON.stringify(trainingRequest))
socket.on('message', (data)=>{
// console.log('inside training ', data)
try {
if (JSON.parse(data)[id]==TRAINING_ID){
console.log(data)
}
} catch (error) {}
// incase status is start training, only resolve until see "MC_Succeeded"
if (status == 'start'){
try {
if(JSON.parse(data)['sys'][1]=='MC_Succeeded'){
console.log('START TRAINING RESULT --------------------------------------')
console.log(data)
console.log('\r\n')
resolve(data)
}
} catch (error) {}
}
// incase status is accept training, only resolve until see "MC_Completed"
if (status == 'accept'){
try {
if(JSON.parse(data)['sys'][1]=='MC_Completed'){
console.log('ACCEPT TRAINING RESULT --------------------------------------')
console.log(data)
console.log('\r\n')
resolve(data)
}
} catch (error) {}
}
})
})
}
/**
* - check login and grant access
* - create profile if not yet exist
* - load profile
* - sub stream 'sys' for training
* - train for actions, each action in number of time
*
*/
train(profileName, trainingActions, numberOfTrain){
this.socket.on('open',async ()=>{
console.log("start training flow")
// check login and grant access
await this.checkGrantAccessAndQuerySessionInfo()
// to training need subcribe 'sys' stream
this.subRequest(['sys'], this.authToken, this.sessionId)
// create profile
let status = "create";
let createProfileResult = ""
await this.setupProfile(this.authToken,
this.headsetId,
profileName, status).then((result)=>{createProfileResult=result})
// load profile
status = "load"
let loadProfileResult = ""
await this.setupProfile(this.authToken,
this.headsetId,
profileName, status).then((result)=>{loadProfileResult=result})
// training all actions
let self = this
for (let trainingAction of trainingActions){
for (let numTrain=0; numTrain<numberOfTrain; numTrain++){
// start training for 'neutral' action
console.log(`START TRAINING "${trainingAction}" TIME ${numTrain+1} ---------------`)
console.log('\r\n')
await self.trainRequest(self.authToken,
self.sessionId,
trainingAction,
'start')
//
// FROM HERE USER HAVE 8 SECONDS TO TRAIN SPECIFIC ACTION
//
// accept 'neutral' result
console.log(`ACCEPT "${trainingAction}" TIME ${numTrain+1} --------------------`)
console.log('\r\n')
await self.trainRequest(self.authToken,
self.sessionId,
trainingAction,
'accept')
}
let status = "save"
let saveProfileResult = ""
// save profile after train
await self.setupProfile(self.authToken,
self.headsetId,
profileName, status)
.then((result)=>{
saveProfileResult=result
console.log(`COMPLETED SAVE ${trainingAction} FOR ${profileName}`)
})
}
})
}
/**
*
* - load profile which trained before
* - sub 'com' stream (mental command)
* - user think specific thing which used while training, for example 'push' action
* - 'push' command should show up on mental command stream
*/
live(profileName) {
this.socket.on('open',async ()=>{
await this.checkGrantAccessAndQuerySessionInfo()
// load profile
let loadProfileResult=""
let status = "load"
await this.setupProfile(this.authToken,
this.headsetId,
profileName,
status).then((result)=>{loadProfileResult=result})
console.log(loadProfileResult)
// // sub 'com' stream and view live mode
this.subRequest(['com'], this.authToken, this.sessionId)
this.socket.on('message', (data)=>{
console.log(data)
})
})
}
}
// ---------------------------------------------------------
let socketUrl = 'wss://localhost:6868'
data = '';
let license = '',
client_id = '',
client_secret = '',
debit = 10000;
let raw_file_data = fs.readFileSync('login.data');
let license_data = JSON.parse(raw_file_data);
license = license_data['license']
client_id = license_data['clientId'];
client_secret = license_data['clientSecret'];
let user = {
"license": license,
"clientId": client_id,
"clientSecret": client_secret,
"debit":10000
}
let c = new Cortex(user, socketUrl)
// Cols name:
const header = [
"COUNTER",
"INTERPOLATED",
"AF3","F7","F3","FC5","T7","P7","O1","O2","P8","T8","FC6","F4","F8","AF4",
"RAW_CQ","MARKER_HARDWARE","MARKERS","STEP"];
// ---------- sub data stream
// have six kind of stream data ['fac', 'pow', 'eeg', 'mot', 'met', 'com']
// user could sub one or many stream at once
let streams = ['eeg','dev']
c.sub(streams)
//read JSON
const userData = require('./public/json/users.json');
const experiments = require('./public/json/experiments.json');
const ML_exp = require('./public/json/ML_sec.json');
//Colect all the CI's form the the file userData
var names = []
for(let i = 0; i < userData.length; i++){
names[i] = userData[i]['CI']
}
//define the directory path
const directoryPath = path.join(__dirname, 'Documents');
//const { SSL_OP_COOKIE_EXCHANGE } = require('constants');
////Find in JSON file
function userIden(userData, data){
return userData.find(userIden => userIden.CI === data.CI);
}
var result = {'CI': 0};
var exp = {};
var exp_ ={};
var mod = {'btn_ML': ''};
var py_server = 0;
var empezar = {'empezar': 0};
var y = 0;
var exp_ML = {};
/*
* Instructions to be followed in case of receiving messages from the clients
*/
io.on('connect', function(socket){
/* var uploader = new SocketIOFile(socket, {
// uploadDir: { // multiple directories
// music: 'data/music',
// document: 'data/document'
// },
uploadDir: 'public/data/'+experiment, // simple directory
// accepts: ['audio/mpeg', 'audio/mp3'], // chrome and some of browsers checking mp3 as 'audio/mp3', not 'audio/mpeg'
// maxFileSize: 4194304, // 4 MB. default is undefined(no limit)
chunkSize: 10240, // default is 10240(1KB)
transmissionDelay: 0, // delay of each transmission, higher value saves more cpu resources, lower upload speed. default is 0(no delay)
overwrite: false, // overwrite file if exists, default is true.
// rename: function(filename) {
// var split = filename.split('.'); // split filename by .(extension)
// var fname = split[0]; // filename without extension
// var ext = split[1];
// return `${fname}_${count++}.${ext}`;
// }
});
console.log(uploader.options.uploadDir); */
io.sockets.emit('py_server', {'py_server': py_server});
io.sockets.emit('userId', result); //Envia de antemano a todos los sockets
io.sockets.emit('model_ML', mod);
io.sockets.emit('pred', {'pred': y, 'first': 0})
io.sockets.emit('start', empezar);
io.sockets.emit('exp', exp);
io.sockets.emit('experiment', exp_);
io.sockets.emit('exp_ML', exp_ML);
/* socket.on('filter', (data) => {
io.sockets.emit('filter', data);
console.log(data.theta)
}); */
socket.on('start', (data) =>{
empezar = data;
console.log(empezar);
io.sockets.emit('start', empezar);
});
//Recibe los datos iniciales
socket.on('y_init', function(data){
io.sockets.emit('y_init', data);
});
//Recibe y_predict de python
socket.on('y_predict', function(data){
io.sockets.emit('y_predict', data);
if (on_record){
if (r_lat){
save_dat = data.data
save_dat[save_dat.length] = data.y_prev
save_dat[save_dat.length] = data.y
save_dat[save_dat.length] = number_of_step
save_dat[save_dat.length] = data.id_num
save_dat[save_dat.length] = data.id_prev
latency = Date.now()-data.lat;
save_dat[save_dat.length] = latency
}
to_record_data_ML[record_index_ML] = save_dat;
record_index_ML += 1;
io.sockets.emit('data_inst', {
y: data.y,
lat: latency,
y_true: number_of_step
});
}
});
socket.on('userCI', function(data) {
result = userIden(userData, data);
console.log(result);
if(result){ //Si no hay el usuario en JSON, no envia nada
io.sockets.emit('userId', result); //Emite la informacion del usuario.
exp_ML = ML_exp[result.ML_start[0]-1];
io.sockets.emit('exp_ML', exp_ML);
user_CI = result.CI;
}else{
result = {}; //Si el usuario ingresa el CI y no esta envia undefined
io.sockets.emit('userId', result); //Emite la informacion del usuario.
}
});
socket.on('button_exp', (data) =>{
exp = data.experiment;
io.sockets.emit('exp', exp);
exp_ = experiments[data.experiment-1];
io.sockets.emit('experiment', exp_);
});
socket.on('button_ML', function(data) {
mod = data;
console.log(mod);
io.sockets.emit('model_ML', mod);
model_num = mod.btn_ML;
});
socket.on('song_ML', (data) =>{
song_ml = data;
io.sockets.emit('song_ML', song_ml);
});
socket.on('sub_experiment', (data) => {
console.log(data);
io.sockets.emit('sub_experiment', data);
});
//Command sec
socket.on('ML_sec', function(code){
//console.log('Recive: ',code);
let func = code.command;
let args = code.args;
/*
* If the command read is'experiment', it recognizes the experiment and
* starts recording data
*/
if (func === "start"){
number_of_step = 'start';
finished = false;
console.log('Recognized experiment');
experiment = args;
io.emit('ML_sec','ready');
// we record as soon as we have the experiment defined
on_record = true;
to_record_data=[];
console.log('Starting to record');
record_index = 0;
r_lat = true
save_dat = []
record_index_ML = 0;
io.emit('start', {'empezar': 1}); // Emite start el python
}
/*
* If the command read is 'beep', it increases the number of step, sends a confirmation message,
* and sends a message of beep with args to generate beep
*/
else if (func === "beep"){
number_of_step = 'beep';
//console.log('Recognized beep '+args)
// send signal to beep
let first_arg = args.split(',')[0];
let second_arg = args.split(',')[1];
io.emit('beep_next', {'step': second_arg});
if (second_arg !== undefined){
number_of_step = second_arg;
}
io.emit('beep',parseInt(args,10))
setTimeout(function(){
io.emit('ML_sec','ready');
}, parseInt(args, 10)+20);
}
else if (func === "play"){
number_of_step = number_of_step + 1;
means_marker = "play";
//console.log('Recognized play '+args)
io.emit('play','./data/Musical/'+args);
io.emit('ML_sec','ready');
}
/*
* If the command read is 'wait', it increases the number of step, and after that sends a
* confirmation message when the time shown in args elapsed.
*/
else if (func === "wait"){
number_of_step = 'wait';
//console.log('Recognized wait '+args)
if (args!== undefined){
let first_arg = args.split(',')[0];
let second_arg = args.split(',')[1];
if (second_arg !== undefined){
number_of_step = second_arg;
}
//console.log('Waiting more than zero with '+first_arg+" and "+second_arg);
setTimeout(function(){
io.emit('ML_sec','ready');
},first_arg);
}else{
io.emit('ML_sec','ready');
}
}
/*
* If the command read is 'finish', it restart the number of step, saves a .csv document on
* the experiment/id folder with the date information on its name.
*/
else if (func === "finish"){
number_of_step = 'finish';
io.emit('start', {'empezar': 0});
if (finished == false){
finished = true;
means_marker = "finish";
on_record = false;
console.log(to_record_data.length);
console.log(to_record_data_ML.length);
let csvData = convertArrayToCSV(to_record_data, {
header,