Skip to content

Commit da062fc

Browse files
committed
app.py and connection.py are updated to save the data as CSV as well,if asked
1 parent 737c878 commit da062fc

File tree

2 files changed

+75
-27
lines changed

2 files changed

+75
-27
lines changed

app.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@ def connect_device():
8282
data = request.get_json()
8383
protocol = data.get('protocol')
8484
device_address = data.get('device_address')
85-
csv_logging = data.get('csv_logging', False)
8685

8786
# Reset stream status
8887
stream_active = False
@@ -94,7 +93,7 @@ def connect_device():
9493
connection_thread.join()
9594

9695
# Create new connection
97-
connection_manager = Connection(csv_logging=csv_logging)
96+
connection_manager = Connection()
9897

9998
def run_connection():
10099
try:
@@ -136,5 +135,27 @@ def disconnect_device():
136135
return jsonify({'status': 'disconnected'})
137136
return jsonify({'status': 'no active connection'})
138137

138+
@app.route('/start_recording', methods=['POST'])
139+
def start_recording():
140+
global connection_manager
141+
if connection_manager and connection_manager.stream_active:
142+
try:
143+
connection_manager.start_csv_recording()
144+
return jsonify({'status': 'recording_started'})
145+
except Exception as e:
146+
return jsonify({'status': 'error', 'message': str(e)}), 500
147+
return jsonify({'status': 'error', 'message': 'No active stream'}), 400
148+
149+
@app.route('/stop_recording', methods=['POST'])
150+
def stop_recording():
151+
global connection_manager
152+
if connection_manager:
153+
try:
154+
connection_manager.stop_csv_recording()
155+
return jsonify({'status': 'recording_stopped'})
156+
except Exception as e:
157+
return jsonify({'status': 'error', 'message': str(e)}), 500
158+
return jsonify({'status': 'error', 'message': 'No active connection'}), 400
159+
139160
if __name__ == "__main__":
140161
app.run(debug=True)

connection.py

Lines changed: 52 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from datetime import datetime
1111

1212
class Connection:
13-
def __init__(self, csv_logging=False):
13+
def __init__(self):
1414
self.ble_connection = None
1515
self.wifi_connection = None
1616
self.lsl_connection = None
@@ -21,12 +21,12 @@ def __init__(self, csv_logging=False):
2121
self.last_sample = None
2222
self.ble_samples_received = 0
2323
self.ble_start_time = time.time()
24-
self.csv_logging = csv_logging
2524
self.csv_file = None
2625
self.csv_writer = None
2726
self.sample_counter = 0
2827
self.num_channels = 0
2928
self.stream_active = False
29+
self.recording_active = False
3030

3131
async def get_ble_device(self):
3232
devices = await Chords_BLE.scan_devices()
@@ -53,27 +53,45 @@ def setup_lsl(self, num_channels, sampling_rate):
5353
self.lsl_connection = StreamOutlet(info)
5454
print(f"LSL stream started: {num_channels} channels at {sampling_rate}Hz")
5555
self.stream_active = True
56-
print("Flag is set to True")
5756
self.num_channels = num_channels
5857

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+
6362
try:
6463
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
6564
filename = f"ChordsPy_{timestamp}.csv"
6665
self.csv_file = open(filename, 'w', newline='')
6766
headers = ['Counter'] + [f'Channel{i+1}' for i in range(self.num_channels)]
6867
self.csv_writer = csv.writer(self.csv_file)
6968
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
7173
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
7492

7593
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:
7795
return
7896

7997
try:
@@ -82,7 +100,7 @@ def log_to_csv(self, sample_data):
82100
self.csv_writer.writerow(row)
83101
except Exception as e:
84102
print(f"Error writing to CSV: {str(e)}")
85-
self.csv_logging = False
103+
self.stop_csv_recording()
86104

87105
def connect_ble(self, device_address=None):
88106
self.ble_connection = Chords_BLE()
@@ -92,7 +110,6 @@ def notification_handler(sender, data):
92110
if len(data) == self.ble_connection.NEW_PACKET_LEN:
93111
if not self.lsl_connection:
94112
self.setup_lsl(num_channels=3, sampling_rate=500)
95-
self.setup_csv()
96113

97114
original_notification_handler(sender, data)
98115

@@ -109,7 +126,8 @@ def notification_handler(sender, data):
109126

110127
if self.lsl_connection: # Push to LSL
111128
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)
113131

114132
self.ble_connection.notification_handler = notification_handler
115133

@@ -125,8 +143,10 @@ def notification_handler(sender, data):
125143
self.ble_connection.connect(selected_device.address)
126144

127145
print("BLE connection established. Waiting for data...")
146+
return True
128147
except Exception as e:
129148
print(f"BLE connection failed: {str(e)}")
149+
return False
130150

131151
def connect_usb(self):
132152
serial_connection = Chords_USB()
@@ -135,18 +155,20 @@ def connect_usb(self):
135155
sampling_rate = serial_connection.supported_boards[serial_connection.board]["sampling_rate"]
136156

137157
self.setup_lsl(self.num_channels, sampling_rate)
138-
self.setup_csv()
139158

140159
original_read_data = serial_connection.read_data
141160
def wrapped_read_data():
142161
original_read_data()
143162
if hasattr(serial_connection, 'data') and self.lsl_connection:
144163
sample = serial_connection.data[:, -1]
145164
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())
147167

148168
serial_connection.read_data = wrapped_read_data
149169
serial_connection.start_streaming()
170+
return True
171+
return False
150172

151173
def connect_wifi(self):
152174
self.wifi_connection = Chords_WIFI()
@@ -157,8 +179,6 @@ def connect_wifi(self):
157179

158180
if not self.lsl_connection:
159181
self.setup_lsl(self.num_channels, sampling_rate)
160-
if self.csv_logging:
161-
self.setup_csv()
162182

163183
try:
164184
print("\nConnected! (Press Ctrl+C to stop)")
@@ -179,28 +199,35 @@ def connect_wifi(self):
179199

180200
if self.lsl_connection: # Push to LSL
181201
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:
183203
self.log_to_csv(channel_data)
184204

185205
except KeyboardInterrupt:
186206
self.wifi_connection.disconnect()
187207
print("\nDisconnected")
188208
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
191220

192221
def __del__(self):
193-
if self.csv_file:
194-
self.csv_file.close()
222+
self.cleanup()
195223

196224
def main():
197225
parser = argparse.ArgumentParser(description='Connect to device')
198226
parser.add_argument('--protocol', choices=['usb', 'wifi', 'ble'], required=True, help='Connection protocol')
199227
parser.add_argument('--ble-address', help='Direct BLE device address')
200-
parser.add_argument('--csv', action='store_true', help='Enable CSV logging')
201228
args = parser.parse_args()
202229

203-
manager = Connection(csv_logging=args.csv)
230+
manager = Connection()
204231

205232
try:
206233
if args.protocol == 'usb':

0 commit comments

Comments
 (0)