Skip to content

Commit 45be0e3

Browse files
committed
Final Changes
1 parent 46a7d47 commit 45be0e3

File tree

1 file changed

+44
-25
lines changed

1 file changed

+44
-25
lines changed

bioamptool.py

Lines changed: 44 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,14 @@
2626
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2727
# SOFTWARE.
2828

29-
from pylsl import StreamInfo, StreamOutlet
30-
import argparse
31-
import serial
32-
import time
33-
import csv
34-
from datetime import datetime
35-
import serial.tools.list_ports
29+
30+
from pylsl import StreamInfo, StreamOutlet # Import LSL stream classes for data streaming
31+
import argparse # Import argparse for command-line argument parsing
32+
import serial # Import serial for serial communication with Arduino
33+
import time # Import time for handling time-related functions
34+
import csv # Import csv for handling CSV file operations
35+
from datetime import datetime # Import datetime for date and time operations
36+
import serial.tools.list_ports # Import tools for listing available serial ports
3637

3738
# Initialize global variables
3839
total_packet_count = 0 # Total number of packets received
@@ -46,11 +47,16 @@
4647
SYNC_BYTE1 = 0xA5 # First sync byte value
4748
SYNC_BYTE2 = 0x5A # Second sync byte value
4849
END_BYTE = 0x01 # End byte value for the packet
50+
verbose_mode = False # Flag for verbose output
4951

5052
# LSL Stream Setup
5153
lsl_outlet = None # LSL outlet for streaming data
5254

53-
def auto_detect_arduino(baudrate, timeout=1): # Auto-detect Arduino by checking all available serial ports.
55+
# Initialize global variables for 10-second data counting
56+
data_count_10_sec = 0 # Count of data points in the last 10 seconds
57+
last_10_sec_time = None # Last time when the 10-second count was logged
58+
59+
def auto_detect_arduino(baudrate, timeout=1): # Auto-detect Arduino by checking all available serial ports.
5460
ports = serial.tools.list_ports.comports() # List all available serial ports
5561
for port in ports:
5662
try:
@@ -67,8 +73,8 @@ def auto_detect_arduino(baudrate, timeout=1): # Auto-detect Arduino by che
6773
print("Arduino not detected") # Print message if no Arduino is found
6874
return None # Return None if no Arduino is detected
6975

70-
def read_arduino_data(ser, csv_writer=None): #Read data from Arduino, process it, and optionally write to CSV and LSL stream.
71-
global total_packet_count, previous_sample_number, missing_samples, buffer
76+
def read_arduino_data(ser, csv_writer=None): # Read data from Arduino, process it, and optionally write to CSV and LSL stream.
77+
global total_packet_count, previous_sample_number, missing_samples, buffer, data_count_10_sec
7278
raw_data = ser.read(ser.in_waiting or 1) # Read data from the serial port
7379
buffer.extend(raw_data) # Append the read data to the buffer
7480

@@ -91,6 +97,7 @@ def read_arduino_data(ser, csv_writer=None): #Read data from Arduino, process
9197

9298
previous_sample_number = counter # Update the previous sample number
9399
total_packet_count += 1 # Increment the total packet count
100+
data_count_10_sec += 1 # Increment 10-second data count
94101

95102
channel_data = [] # List to store channel data
96103
for i in range(4, 16, 2): # Extract channel data from the packet
@@ -108,22 +115,24 @@ def read_arduino_data(ser, csv_writer=None): #Read data from Arduino, process
108115
else:
109116
del buffer[:sync_index + 1] # Remove invalid data from the buffer
110117

111-
def start_timer(): # Initialize timers for minute and ten-minute intervals and reset packet count.
112-
global start_time, last_ten_minute_time, total_packet_count
118+
def start_timer(): # Initialize timers for minute and ten-minute intervals and reset packet count.
119+
global start_time, last_ten_minute_time, total_packet_count, last_10_sec_time, data_count_10_sec
113120
time.sleep(0.5) # Ensure LSL stream setup is complete
114121
current_time = time.time() # Get the current time
115122
start_time = current_time # Set the start time
116123
last_ten_minute_time = current_time # Set the time for the last ten-minute interval
124+
last_10_sec_time = current_time # Set the start time for the 10-second interval
117125
total_packet_count = 0 # Reset total packet count
126+
data_count_10_sec = 0 # Reset 10-second data count
118127

119-
def log_minute_data(): #Logs and resets data count per minute
128+
def log_minute_data(): # Logs and resets data count per minute
120129
global total_packet_count
121130
count_for_minute = total_packet_count # Get the data count for the current minute
122131
print(f"Data count for this minute: {count_for_minute} samples") # Print the data count
123132
total_packet_count = 0 # Reset total packet count for the next minute
124133
return count_for_minute # Return the count for further use
125134

126-
def log_ten_minute_data(): #Logs data count for every 10 minutes and computes sampling rate and drift.
135+
def log_ten_minute_data(): # Logs data count for every 10 minutes and computes sampling rate and drift.
127136
global total_data_received, last_ten_minute_time
128137

129138
print(f"Total data count after 10 minutes: {total_data_received} samples") # Print total data count
@@ -137,23 +146,24 @@ def log_ten_minute_data(): #Logs data count for every 10 minutes and computes
137146
total_data_received = 0 # Reset total data received for the next 10-minute interval
138147
last_ten_minute_time = time.time() # Update the last ten-minute interval start
139148

140-
def parse_data(port, baudrate, lsl_flag=False, csv_flag=False): # Main function to process data from the Arduino.
149+
def parse_data(port, baudrate, lsl_flag=False, csv_flag=False, verbose_flag=False): # Main function to process data from the Arduino.
141150
global total_packet_count, start_time, total_data_received, lsl_outlet, last_ten_minute_time
151+
global data_count_10_sec, last_10_sec_time, verbose_mode
152+
153+
verbose_mode = verbose_flag # Set the verbose mode flag
142154

143155
csv_writer = None # CSV writer is initially None
144-
csv_filename = None
156+
csv_filename = None # CSV filename is initially None
145157

146158
# Check if LSL stream is enabled
147159
if lsl_flag:
148160
lsl_stream_info = StreamInfo('BioAmpDataStream', 'EXG', 6, 250, 'float32', 'UpsideDownLabs') # Define LSL stream info
149161
lsl_outlet = StreamOutlet(lsl_stream_info) # Create LSL outlet
150162
print("LSL stream started") # Print message indicating LSL stream has started
151-
time.sleep(0.5) # Delay to ensure that LSL stream setup is complete
152163

153164
# If CSV logging is requested
154165
if csv_flag:
155-
# Generate the filename dynamically based on current date and time
156-
csv_filename = f"data_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.csv"
166+
csv_filename = f"data_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.csv" # Generate the filename dynamically based on current date and time
157167
print(f"CSV recording started. Data will be saved to {csv_filename}") # Print CSV recording message
158168

159169
# Open the serial port and CSV file
@@ -165,18 +175,26 @@ def parse_data(port, baudrate, lsl_flag=False, csv_flag=False): # Main functio
165175
csv_writer.writerow(['Counter', 'Channel1', 'Channel2', 'Channel3', 'Channel4', 'Channel5', 'Channel6']) # Write CSV header
166176

167177
# Delay to account for initial data and ensure accurate timing
168-
start_timer()
178+
start_timer() # Initialize timers and reset counters
169179

170180
try:
171181
while True:
172-
read_arduino_data(ser, csv_writer) # Read and process data from Arduino
173-
174182
current_time = time.time() # Get the current time
175183

184+
# Read and process data from Arduino
185+
read_arduino_data(ser, csv_writer)
186+
187+
# Check if 10 seconds have passed and log data count
188+
if current_time - last_10_sec_time >= 10:
189+
if verbose_mode:
190+
print(f"Verbose: Data count in the last 10 seconds: {data_count_10_sec}") # Print verbose data count
191+
data_count_10_sec = 0 # Reset 10-second data count
192+
last_10_sec_time = current_time # Update 10-second interval start
193+
176194
# Check if a minute has passed and log minute data
177195
if current_time - start_time >= 60:
178196
total_data_received += log_minute_data() # Update total data received
179-
start_time += 60 # Adjust the start time to handle next interval accurately
197+
start_time += 60 # Adjust the start time to handle the next interval accurately
180198

181199
# Check if 10 minutes have passed and log ten-minute data
182200
if current_time - last_ten_minute_time >= 600:
@@ -197,8 +215,9 @@ def parse_data(port, baudrate, lsl_flag=False, csv_flag=False): # Main functio
197215
parser.add_argument('-b', '--baudrate', type=int, default=57600, help="Set baud rate for the serial communication")
198216
parser.add_argument('--csv', action='store_true', help="Create and write to a CSV file")
199217
parser.add_argument('--lsl', action='store_true', help="Start LSL stream")
218+
parser.add_argument('-v', '--verbose', action='store_true', help="Verbose mode for data count every 10 seconds")
200219

201-
args = parser.parse_args()
220+
args = parser.parse_args() # Parse command-line arguments
202221

203222
# Determine port and start data parsing based on arguments
204223
if args.lsl:
@@ -210,6 +229,6 @@ def parse_data(port, baudrate, lsl_flag=False, csv_flag=False): # Main functio
210229
if port is None:
211230
print("Arduino port not specified or detected. Exiting.") # Print message if no port detected
212231
else:
213-
parse_data(port, args.baudrate, lsl_flag=args.lsl, csv_flag=args.csv) # Start data parsing
232+
parse_data(port, args.baudrate, lsl_flag=args.lsl, csv_flag=args.csv, verbose_flag=args.verbose) # Start data parsing
214233
else:
215234
parser.print_help() # Print help message if no valid arguments are provided

0 commit comments

Comments
 (0)