10
10
from datetime import datetime
11
11
12
12
class Connection :
13
- def __init__ (self , csv_logging = False ):
13
+ def __init__ (self ):
14
14
self .ble_connection = None
15
15
self .wifi_connection = None
16
16
self .lsl_connection = None
@@ -21,12 +21,12 @@ def __init__(self, csv_logging=False):
21
21
self .last_sample = None
22
22
self .ble_samples_received = 0
23
23
self .ble_start_time = time .time ()
24
- self .csv_logging = csv_logging
25
24
self .csv_file = None
26
25
self .csv_writer = None
27
26
self .sample_counter = 0
28
27
self .num_channels = 0
29
28
self .stream_active = False
29
+ self .recording_active = False
30
30
31
31
async def get_ble_device (self ):
32
32
devices = await Chords_BLE .scan_devices ()
@@ -53,27 +53,45 @@ def setup_lsl(self, num_channels, sampling_rate):
53
53
self .lsl_connection = StreamOutlet (info )
54
54
print (f"LSL stream started: { num_channels } channels at { sampling_rate } Hz" )
55
55
self .stream_active = True
56
- print ("Flag is set to True" )
57
56
self .num_channels = num_channels
58
57
59
- def setup_csv (self ):
60
- if not self .csv_logging or self . csv_file :
61
- return # Already set up or logging disabled
62
-
58
+ def start_csv_recording (self ):
59
+ if self .recording_active :
60
+ return False
61
+
63
62
try :
64
63
timestamp = datetime .now ().strftime ("%Y%m%d_%H%M%S" )
65
64
filename = f"ChordsPy_{ timestamp } .csv"
66
65
self .csv_file = open (filename , 'w' , newline = '' )
67
66
headers = ['Counter' ] + [f'Channel{ i + 1 } ' for i in range (self .num_channels )]
68
67
self .csv_writer = csv .writer (self .csv_file )
69
68
self .csv_writer .writerow (headers )
70
- print (f"CSV logging started: { filename } " )
69
+ self .recording_active = True
70
+ self .sample_counter = 0
71
+ print (f"CSV recording started: { filename } " )
72
+ return True
71
73
except Exception as e :
72
- print (f"Error setting up CSV logging: { str (e )} " )
73
- self .csv_logging = False
74
+ print (f"Error starting CSV recording: { str (e )} " )
75
+ return False
76
+
77
+ def stop_csv_recording (self ):
78
+ if not self .recording_active :
79
+ return False
80
+
81
+ try :
82
+ if self .csv_file :
83
+ self .csv_file .close ()
84
+ self .csv_file = None
85
+ self .csv_writer = None
86
+ self .recording_active = False
87
+ print ("CSV recording stopped" )
88
+ return True
89
+ except Exception as e :
90
+ print (f"Error stopping CSV recording: { str (e )} " )
91
+ return False
74
92
75
93
def log_to_csv (self , sample_data ):
76
- if not self .csv_logging or not self .csv_writer :
94
+ if not self .recording_active or not self .csv_writer :
77
95
return
78
96
79
97
try :
@@ -82,7 +100,7 @@ def log_to_csv(self, sample_data):
82
100
self .csv_writer .writerow (row )
83
101
except Exception as e :
84
102
print (f"Error writing to CSV: { str (e )} " )
85
- self .csv_logging = False
103
+ self .stop_csv_recording ()
86
104
87
105
def connect_ble (self , device_address = None ):
88
106
self .ble_connection = Chords_BLE ()
@@ -92,7 +110,6 @@ def notification_handler(sender, data):
92
110
if len (data ) == self .ble_connection .NEW_PACKET_LEN :
93
111
if not self .lsl_connection :
94
112
self .setup_lsl (num_channels = 3 , sampling_rate = 500 )
95
- self .setup_csv ()
96
113
97
114
original_notification_handler (sender , data )
98
115
@@ -109,7 +126,8 @@ def notification_handler(sender, data):
109
126
110
127
if self .lsl_connection : # Push to LSL
111
128
self .lsl_connection .push_sample (channels )
112
- self .log_to_csv (channels ) # Log to CSV
129
+ if self .recording_active :
130
+ self .log_to_csv (channels )
113
131
114
132
self .ble_connection .notification_handler = notification_handler
115
133
@@ -125,8 +143,10 @@ def notification_handler(sender, data):
125
143
self .ble_connection .connect (selected_device .address )
126
144
127
145
print ("BLE connection established. Waiting for data..." )
146
+ return True
128
147
except Exception as e :
129
148
print (f"BLE connection failed: { str (e )} " )
149
+ return False
130
150
131
151
def connect_usb (self ):
132
152
serial_connection = Chords_USB ()
@@ -135,18 +155,20 @@ def connect_usb(self):
135
155
sampling_rate = serial_connection .supported_boards [serial_connection .board ]["sampling_rate" ]
136
156
137
157
self .setup_lsl (self .num_channels , sampling_rate )
138
- self .setup_csv ()
139
158
140
159
original_read_data = serial_connection .read_data
141
160
def wrapped_read_data ():
142
161
original_read_data ()
143
162
if hasattr (serial_connection , 'data' ) and self .lsl_connection :
144
163
sample = serial_connection .data [:, - 1 ]
145
164
self .lsl_connection .push_sample (sample )
146
- self .log_to_csv (sample .tolist ())
165
+ if self .recording_active :
166
+ self .log_to_csv (sample .tolist ())
147
167
148
168
serial_connection .read_data = wrapped_read_data
149
169
serial_connection .start_streaming ()
170
+ return True
171
+ return False
150
172
151
173
def connect_wifi (self ):
152
174
self .wifi_connection = Chords_WIFI ()
@@ -157,8 +179,6 @@ def connect_wifi(self):
157
179
158
180
if not self .lsl_connection :
159
181
self .setup_lsl (self .num_channels , sampling_rate )
160
- if self .csv_logging :
161
- self .setup_csv ()
162
182
163
183
try :
164
184
print ("\n Connected! (Press Ctrl+C to stop)" )
@@ -179,28 +199,35 @@ def connect_wifi(self):
179
199
180
200
if self .lsl_connection : # Push to LSL
181
201
self .lsl_connection .push_sample (channel_data )
182
- if self .csv_logging and self . csv_writer : # Only log if CSV is set up
202
+ if self .recording_active :
183
203
self .log_to_csv (channel_data )
184
204
185
205
except KeyboardInterrupt :
186
206
self .wifi_connection .disconnect ()
187
207
print ("\n Disconnected" )
188
208
finally :
189
- if self .csv_file :
190
- self .csv_file .close ()
209
+ self .stop_csv_recording ()
210
+
211
+ def cleanup (self ):
212
+ self .stop_csv_recording ()
213
+ self .stream_active = False
214
+ if self .ble_connection :
215
+ self .ble_connection .disconnect ()
216
+ if self .wifi_connection :
217
+ self .wifi_connection .disconnect ()
218
+ if self .lsl_connection :
219
+ self .lsl_connection = None
191
220
192
221
def __del__ (self ):
193
- if self .csv_file :
194
- self .csv_file .close ()
222
+ self .cleanup ()
195
223
196
224
def main ():
197
225
parser = argparse .ArgumentParser (description = 'Connect to device' )
198
226
parser .add_argument ('--protocol' , choices = ['usb' , 'wifi' , 'ble' ], required = True , help = 'Connection protocol' )
199
227
parser .add_argument ('--ble-address' , help = 'Direct BLE device address' )
200
- parser .add_argument ('--csv' , action = 'store_true' , help = 'Enable CSV logging' )
201
228
args = parser .parse_args ()
202
229
203
- manager = Connection (csv_logging = args . csv )
230
+ manager = Connection ()
204
231
205
232
try :
206
233
if args .protocol == 'usb' :
0 commit comments