-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheeg_headset.py
More file actions
308 lines (256 loc) · 11 KB
/
eeg_headset.py
File metadata and controls
308 lines (256 loc) · 11 KB
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
# eeg_headset.py
import logging
import os
import time
from pathlib import Path
from typing import Any, Dict, List, Optional
import numpy as np
class EEGHeadset:
"""
Handles connection and data acquisition from BrainAccess headset.
Compatible with BrainAccess SDK 3.6.0
"""
def __init__(self, participant_id: str, logger: logging.Logger) -> None:
"""
Initialize the EEG headset interface.
Args:
participant_id (str): ID to use as folder name for saved data.
logger (logging.Logger): Logger for recording information and errors.
"""
self.logger = logger
self._is_connected = False
self._is_recording = False
self._participant_id = participant_id
self._data_folder_path = "data"
self._save_dir_path = os.path.join(self._data_folder_path, participant_id)
self._connection_attempts = 0
self._max_attempts = 3
self._annotations = []
self._recording_start_time = 0
self._eeg_manager = None
self._eeg_acquisition = None
# Create directories for data storage
self._create_dir_if_not_exist(self._data_folder_path)
self._create_dir_if_not_exist(self._save_dir_path)
try:
# Initialize BrainAccess library (SDK 3.6.0)
self.logger.info("Initializing BrainAccess library (SDK 3.6.0)...")
from brainaccess.core.eeg_manager import EEGManager
from brainaccess.utils import acquisition
self.EEGManager = EEGManager
self.acquisition = acquisition
except ImportError:
self.logger.error("BrainAccess library not installed. Use pip install brainaccess")
raise
def connect(self) -> bool:
"""
Connect to the BrainAccess headset using SDK 3.6.0 pattern.
Returns:
bool: True if connection was successful, False otherwise.
"""
if self._is_connected:
self.logger.info("Already connected to the headset.")
return True
from eeg_config import DEVICE_NAME, USED_DEVICE, SAMPLING_RATE
self.logger.info(f"Attempting to connect to BrainAccess device: {DEVICE_NAME}...")
self.logger.info(f"Sampling frequency: {SAMPLING_RATE} Hz")
while self._connection_attempts < self._max_attempts:
try:
# SDK 3.6.0: Create EEGManager instance (will be used as context manager internally)
self._eeg_manager = self.EEGManager()
self._eeg_acquisition = self.acquisition.EEG()
# SDK 3.6.0: setup() scans, connects and configures channels
# Pass sfreq parameter to set sampling frequency to 250 Hz
self._eeg_acquisition.setup(
self._eeg_manager,
device_name=DEVICE_NAME,
cap=USED_DEVICE,
sfreq=SAMPLING_RATE # 250 Hz as per eeg_config.py
)
# Check connection status
if self._eeg_manager.is_connected():
self._is_connected = True
# Log battery info
try:
battery_info = self._eeg_manager.get_battery_info()
self.logger.info(f"Battery level: {battery_info.level}%")
except Exception as e:
self.logger.warning(f"Could not get battery info: {e}")
self.logger.info("Successfully connected to BrainAccess device!")
return True
except Exception as e:
self._connection_attempts += 1
self.logger.warning(
f"Connection attempt {self._connection_attempts} failed: {str(e)}"
)
# Clean up failed connection attempt
self._cleanup_connection()
if self._connection_attempts < self._max_attempts:
self.logger.info(f"Retrying in {self._connection_attempts} seconds...")
time.sleep(self._connection_attempts)
self.logger.error("Failed to connect to the headset after multiple attempts.")
self.logger.error("Please check that:")
self.logger.error("1. The device is turned on and charged")
self.logger.error("2. The device is within Bluetooth range")
self.logger.error(f"3. The device name '{DEVICE_NAME}' is correct")
return False
def _cleanup_connection(self) -> None:
"""Clean up connection resources after a failed attempt."""
try:
if self._eeg_acquisition is not None:
try:
self._eeg_acquisition.close()
except:
pass
self._eeg_acquisition = None
if self._eeg_manager is not None:
try:
self._eeg_manager.disconnect()
except:
pass
self._eeg_manager = None
except:
pass
def disconnect(self) -> None:
"""
Disconnect from the BrainAccess headset (SDK 3.6.0 pattern).
"""
if not self._is_connected:
self.logger.info("Not connected to any headset.")
return
if self._is_recording:
self.stop_recording()
try:
# Stop acquisition if it's running
if self._eeg_acquisition is not None:
try:
self._eeg_acquisition.stop_acquisition()
except:
pass # Might already be stopped
try:
self._eeg_acquisition.close()
except:
pass # Clean up as much as possible
self._eeg_acquisition = None
# Disconnect the manager (SDK 3.6.0)
if self._eeg_manager is not None:
try:
self._eeg_manager.disconnect()
except:
pass
self._eeg_manager = None
self._is_connected = False
self._connection_attempts = 0 # Reset for potential reconnection
self.logger.info("Disconnected from BrainAccess device.")
except Exception as e:
self.logger.error(f"Error disconnecting from the headset: {str(e)}")
def start_recording(self, filepath: str) -> bool:
"""
Start recording EEG data.
Args:
filepath (str): Path where data will be saved.
Returns:
bool: True if recording started successfully, False otherwise.
"""
if not self._is_connected:
if not self.connect():
self.logger.error("Cannot start recording: Failed to connect to the headset.")
return False
if self._is_recording:
self.logger.warning("Called start_recording when already recording. Forcing stop of previous one.")
self.stop_recording()
try:
self.logger.info("Starting EEG data acquisition...")
self._eeg_acquisition.start_acquisition()
self._is_recording = True
self._session_name = os.path.basename(filepath)
self._filepath = filepath
self._recording_start_time = time.time()
self._annotate_internal("Recording started")
self.logger.info(f"Recording started: {filepath}")
return True
except Exception as e:
self.logger.error(f"Error starting recording: {str(e)}")
return False
def stop_recording(self) -> bool:
"""
Stop recording and save the data.
Returns:
bool: True if data was saved successfully, False otherwise.
"""
if not self._is_recording:
self.logger.info("No active recording to stop.")
return False
try:
self._annotate_internal("Recording ended")
self.logger.info("Processing recorded data...")
raw_data = self._eeg_acquisition.get_mne()
if raw_data is not None:
self.logger.info(f"Saving EEG data to {self._filepath}")
Path(self._filepath).parent.mkdir(parents=True, exist_ok=True)
raw_data.save(self._filepath)
# Also stop the acquisition
self._eeg_acquisition.stop_acquisition()
self._eeg_manager.clear_annotations()
self.logger.info("Recording stopped and data saved successfully.")
else:
self.logger.warning("No data to save - get_mne() returned None")
# Still stop the acquisition even if no data
try:
self._eeg_acquisition.stop_acquisition()
except:
pass
return False
return True
except Exception as e:
self.logger.error(f"Error stopping recording: {e}", exc_info=True)
# Try to stop acquisition even if saving failed
try:
self._eeg_acquisition.stop_acquisition()
except:
pass
return False
finally:
# Always reset the recording state to prevent the experiment from getting stuck
self._is_recording = False
def annotate(self, annotation: str) -> None:
"""
Add an annotation to the EEG data.
Args:
annotation (str): Annotation text to add.
"""
self._annotate_internal(annotation)
def _annotate_internal(self, annotation: str) -> None:
"""
Internal method to add an annotation to the EEG data.
Args:
annotation (str): Annotation text to add.
"""
if not self._is_connected:
self.logger.warning(f"Cannot annotate '{annotation}': Not connected to the headset.")
return
try:
timestamp = time.time() - self._recording_start_time if self._is_recording else 0
self._eeg_acquisition.annotate(annotation)
self._annotations.append({"timestamp": timestamp, "annotation": annotation})
self.logger.info(f"Annotation added: '{annotation}' at {timestamp:.2f}s")
except Exception as e:
self.logger.error(f"Error adding annotation: {str(e)}")
def is_recording(self) -> bool:
"""Check if the headset is recording data"""
return self._is_recording
def is_acquiring(self) -> bool:
"""
Check if the headset is acquiring data.
For this class, recording and acquiring are the same state.
"""
return self.is_recording()
def _create_dir_if_not_exist(self, path: str) -> None:
"""
Create a directory if it does not exist.
Args:
path (str): Directory path to create.
"""
if not os.path.exists(path):
os.makedirs(path)
self.logger.info(f"Created directory: {path}")