2
2
import pylsl
3
3
import numpy as np
4
4
import time
5
+ import sys
5
6
from pylsl import StreamInlet , resolve_streams , resolve_byprop
6
7
from scipy .signal import iirnotch , butter , lfilter
7
8
import math
12
13
streams = resolve_streams ()
13
14
available_streams = [s .name () for s in streams ]
14
15
16
+ last_data_time = None
17
+ stream_active = True
18
+ inlet = None # Initialize inlet variable
19
+
15
20
if not available_streams :
16
21
print ("No LSL streams found!" )
22
+ sys .exit (1 )
17
23
18
24
for stream_name in available_streams :
19
25
print (f"Trying to connect to { stream_name } ..." )
28
34
29
35
if inlet is None :
30
36
print ("Could not connect to any stream." )
37
+ sys .exit (1 )
38
+
31
39
sampling_rate = int (inlet .info ().nominal_srate ())
32
40
print (f"Sampling rate: { sampling_rate } Hz" )
33
41
@@ -70,6 +78,11 @@ def show_message(message, duration=3):
70
78
screen .blit (text , text_rect )
71
79
pygame .display .update ()
72
80
81
+ for event in pygame .event .get ():
82
+ if event .type == pygame .QUIT :
83
+ pygame .quit ()
84
+ sys .exit ()
85
+
73
86
# Apply filters
74
87
def apply_filters (eeg_point ):
75
88
filtered = lfilter (b_notch , a_notch , [eeg_point ])
@@ -97,7 +110,7 @@ def calculate_focus_level(eeg_data, sampling_rate=500):
97
110
pygame .display .set_caption ('Beetle Game' )
98
111
99
112
def calibrate ():
100
- global focus_threshold
113
+ global focus_threshold , last_data_time
101
114
calibration_data = []
102
115
103
116
font = pygame .font .SysFont ("Arial" , 36 , bold = True )
@@ -119,8 +132,19 @@ def calibrate():
119
132
120
133
sample , _ = inlet .pull_sample (timeout = 0.1 )
121
134
if sample :
135
+ last_data_time = time .time ()
122
136
filtered_sample = apply_filters (sample [0 ])
123
137
calibration_data .append (filtered_sample )
138
+ else :
139
+ if last_data_time and (time .time () - last_data_time ) > 2 :
140
+ show_message ("Connection lost! Exiting..." , 2 )
141
+ pygame .quit ()
142
+ sys .exit (1 )
143
+
144
+ for event in pygame .event .get ():
145
+ if event .type == pygame .QUIT :
146
+ pygame .quit ()
147
+ sys .exit ()
124
148
125
149
if len (calibration_data ) >= buffer_size : # Ensure enough data was collected
126
150
eeg_data = np .array (calibration_data )
@@ -170,8 +194,14 @@ def update_beetle_position(focus_level, is_focus_stable):
170
194
171
195
sample , _ = inlet .pull_sample (timeout = 0.1 )
172
196
if sample :
197
+ last_data_time = time .time ()
173
198
filtered_sample = apply_filters (sample [0 ])
174
199
buffer .append (filtered_sample )
200
+ else :
201
+ if last_data_time and (time .time () - last_data_time ) > 2 :
202
+ show_message ("Connection lost! Exiting..." , 2 )
203
+ running = False
204
+ break
175
205
176
206
current_time = time .time ()
177
207
0 commit comments