Skip to content

Commit 6b3d3e1

Browse files
committed
Class name changed
1 parent 6811ba5 commit 6b3d3e1

File tree

2 files changed

+68
-51
lines changed

2 files changed

+68
-51
lines changed

chords_wifi.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import socket
55
from scipy.signal import butter, filtfilt
66

7-
class NPG_Wifi:
7+
class Chords_WIFI:
88
def __init__(self, stream_name='NPG', channels=3, sampling_rate=250, block_size=13, timeout_sec=1):
99
self.stream_name = stream_name
1010
self.channels = channels
@@ -129,7 +129,7 @@ def __del__(self):
129129
if __name__ == "__main__":
130130
client = None
131131
try:
132-
client = NPG_Wifi()
132+
client = Chords_WIFI()
133133
client.connect()
134134
client.process_data()
135135
except Exception as e:

connection.py

Lines changed: 66 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from chords_serial import Serial_USB
2-
from chords_wifi import NPG_Wifi
3-
from chords_ble import NPG_Ble
1+
from chords_serial import Chords_USB
2+
from chords_wifi import Chords_WIFI
3+
from chords_ble import Chords_BLE
44
from pylsl import StreamInfo, StreamOutlet
55
import argparse
66
import time
@@ -13,7 +13,7 @@ class Connection:
1313
def __init__(self, csv_logging=False):
1414
self.ble_connection = None
1515
self.wifi_connection = None
16-
self.lsl_outlet = None
16+
self.lsl_connection = None
1717
self.stream_name = "BioAmpDataStream"
1818
self.stream_type = "EXG"
1919
self.stream_format = "float32"
@@ -28,7 +28,7 @@ def __init__(self, csv_logging=False):
2828
self.num_channels = 0
2929

3030
async def get_ble_device(self):
31-
devices = await NPG_Ble.scan_devices()
31+
devices = await Chords_BLE.scan_devices()
3232
if not devices:
3333
print("No NPG devices found!")
3434
return None
@@ -49,40 +49,47 @@ async def get_ble_device(self):
4949

5050
def setup_lsl(self, num_channels, sampling_rate):
5151
info = StreamInfo(self.stream_name, self.stream_type, num_channels, sampling_rate, self.stream_format, self.stream_id)
52-
self.lsl_outlet = StreamOutlet(info)
52+
self.lsl_connection = StreamOutlet(info)
5353
print(f"LSL stream started: {num_channels} channels at {sampling_rate}Hz")
5454
self.num_channels = num_channels
5555

5656
def setup_csv(self):
57-
if not self.csv_logging:
58-
return
57+
if not self.csv_logging or self.csv_file:
58+
return # Already set up or logging disabled
5959

60-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
61-
filename = f"ChordsPy{timestamp}.csv"
62-
self.csv_file = open(filename, 'w', newline='')
63-
headers = ['Counter'] + [f'Channel{i+1}' for i in range(self.num_channels)]
64-
self.csv_writer = csv.writer(self.csv_file)
65-
self.csv_writer.writerow(headers)
66-
print(f"CSV logging started: {filename}")
60+
try:
61+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
62+
filename = f"ChordsPy_{timestamp}.csv"
63+
self.csv_file = open(filename, 'w', newline='')
64+
headers = ['Counter'] + [f'Channel{i+1}' for i in range(self.num_channels)]
65+
self.csv_writer = csv.writer(self.csv_file)
66+
self.csv_writer.writerow(headers)
67+
print(f"CSV logging started: {filename}")
68+
except Exception as e:
69+
print(f"Error setting up CSV logging: {str(e)}")
70+
self.csv_logging = False
6771

6872
def log_to_csv(self, sample_data):
6973
if not self.csv_logging or not self.csv_writer:
7074
return
7175

72-
self.sample_counter += 1
73-
row = [self.sample_counter] + sample_data
74-
self.csv_writer.writerow(row)
76+
try:
77+
self.sample_counter += 1
78+
row = [self.sample_counter] + sample_data
79+
self.csv_writer.writerow(row)
80+
except Exception as e:
81+
print(f"Error writing to CSV: {str(e)}")
82+
self.csv_logging = False
7583

7684
def connect_ble(self, device_address=None):
77-
self.ble_connection = NPG_Ble()
85+
self.ble_connection = Chords_BLE()
7886
original_notification_handler = self.ble_connection.notification_handler
79-
80-
def wrapped_notification_handler(sender, data):
87+
88+
def notification_handler(sender, data):
8189
if len(data) == self.ble_connection.NEW_PACKET_LEN:
82-
if not self.lsl_outlet:
90+
if not self.lsl_connection:
8391
self.setup_lsl(num_channels=3, sampling_rate=500)
8492
self.setup_csv()
85-
print("BLE LSL stream started")
8693

8794
original_notification_handler(sender, data)
8895

@@ -96,25 +103,30 @@ def wrapped_notification_handler(sender, data):
96103
]
97104
self.last_sample = channels
98105
self.ble_samples_received += 1
106+
107+
if self.lsl_connection: # Push to LSL
108+
self.lsl_connection.push_sample(channels)
109+
self.log_to_csv(channels) # Log to CSV
99110

100-
if self.lsl_outlet: # Push to LSL
101-
self.lsl_outlet.push_sample(channels)
102-
self.log_to_csv(channels) # Log to CSV
103-
104-
self.ble_connection.notification_handler = wrapped_notification_handler
105-
106-
if device_address:
107-
self.ble_connection.connect(device_address)
108-
else:
109-
selected_device = asyncio.run(self.get_ble_device())
110-
if not selected_device:
111-
return
112-
self.ble_connection.connect(selected_device.address)
113-
114-
print("BLE connection established. Waiting for data...")
111+
self.ble_connection.notification_handler = notification_handler
112+
113+
try:
114+
if device_address:
115+
print(f"Connecting to BLE device: {device_address}")
116+
self.ble_connection.connect(device_address)
117+
else:
118+
selected_device = asyncio.run(self.get_ble_device())
119+
if not selected_device:
120+
return
121+
print(f"Connecting to BLE device: {selected_device.name}")
122+
self.ble_connection.connect(selected_device.address)
123+
124+
print("BLE connection established. Waiting for data...")
125+
except Exception as e:
126+
print(f"BLE connection failed: {str(e)}")
115127

116128
def connect_usb(self):
117-
serial_connection = Serial_USB()
129+
serial_connection = Chords_USB()
118130
if serial_connection.detect_hardware():
119131
self.num_channels = serial_connection.num_channels
120132
sampling_rate = serial_connection.supported_boards[serial_connection.board]["sampling_rate"]
@@ -125,21 +137,25 @@ def connect_usb(self):
125137
original_read_data = serial_connection.read_data
126138
def wrapped_read_data():
127139
original_read_data()
128-
if hasattr(serial_connection, 'data') and self.lsl_outlet:
140+
if hasattr(serial_connection, 'data') and self.lsl_connection:
129141
sample = serial_connection.data[:, -1]
130-
self.lsl_outlet.push_sample(sample)
142+
self.lsl_connection.push_sample(sample)
131143
self.log_to_csv(sample.tolist())
132144

133145
serial_connection.read_data = wrapped_read_data
134146
serial_connection.start_streaming()
135147

136148
def connect_wifi(self):
137-
self.wifi_connection = NPG_Wifi()
149+
self.wifi_connection = Chords_WIFI()
138150
self.wifi_connection.connect()
139151

140152
self.num_channels = self.wifi_connection.channels
141-
self.setup_lsl(self.num_channels, self.wifi_connection.sampling_rate)
142-
self.setup_csv()
153+
sampling_rate = self.wifi_connection.sampling_rate
154+
155+
if not self.lsl_connection:
156+
self.setup_lsl(self.num_channels, sampling_rate)
157+
if self.csv_logging:
158+
self.setup_csv()
143159

144160
try:
145161
print("\nConnected! (Press Ctrl+C to stop)")
@@ -158,10 +174,11 @@ def connect_wifi(self):
158174
sample = int.from_bytes(block[offset:offset + 2], byteorder='big', signed=True)
159175
channel_data.append(sample)
160176

161-
if self.lsl_outlet: # Push to LSL
162-
self.lsl_outlet.push_sample(channel_data)
163-
self.log_to_csv(channel_data) # Log to CSV
164-
177+
if self.lsl_connection: # Push to LSL
178+
self.lsl_connection.push_sample(channel_data)
179+
if self.csv_logging and self.csv_writer: # Only log if CSV is set up
180+
self.log_to_csv(channel_data)
181+
165182
except KeyboardInterrupt:
166183
self.wifi_connection.disconnect()
167184
print("\nDisconnected")
@@ -190,7 +207,7 @@ def main():
190207
elif args.protocol == 'ble':
191208
manager.connect_ble(args.ble_address)
192209
except KeyboardInterrupt:
193-
print("\nDisconnecting...")
210+
print("\nCleanup Completed.")
194211
except Exception as e:
195212
print(f"Error: {str(e)}")
196213

0 commit comments

Comments
 (0)