File size: 11,843 Bytes
5e284bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import argparse
import sys
import os
import serial
import time
import paramiko
import io
from pathlib import Path
from datetime import datetime

def create_ssh_connection():
    """Create SSH connection to remote server"""
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect('topos.exypno.tech', port=420, username='albert')
        return ssh
    except Exception as e:
        print(f"Failed to connect to remote server: {e}")
        return None

def set_gain(ser, gain=8):
    """Set 2x gain on all channels (1-16) for Cyton+Daisy"""
    print(f"Setting {gain}x gain on all channels...")

    # Stop any streaming first
    ser.write(b's')
    time.sleep(0.5)

    gain_mapping = [1, 2, 4, 6, 8, 12, 24]
    gain_val = gain_mapping.index(gain)

    # Main board channels (1-8)
    main_channels = ['1', '2', '3', '4', '5', '6', '7', '8']
    # Daisy board channels (9-16 represented as Q-I)
    daisy_channels = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I']

    # Combine all channel commands into one string
    commands = ''
    for ch in main_channels + daisy_channels:
        commands += f'x{ch}0{gain_val}0000X'

    # Send all commands at once
    ser.write(commands.encode())
    time.sleep(0.5)

    # Clear any response from the serial buffer
    ser.reset_input_buffer()

    print("Gain settings updated")

def set_sample_rate(ser, freq):
    """Set sample rate using the '~' command"""
    # Sample rate mapping according to documentation
    freq_mapping = {
        16000: '0',
        8000: '1',
        4000: '2',
        2000: '3',
        1000: '4',
        500: '5',
        250: '6'
    }

    if freq not in freq_mapping:
        raise ValueError(f"Unsupported frequency {freq}Hz. Supported rates: {list(freq_mapping.keys())}")

    # Stop any streaming first
    ser.write(b's')
    time.sleep(0.5)

    # Set sample rate
    command = f"~{freq_mapping[freq]}"
    ser.write(command.encode())
    time.sleep(0.5)

    # Clear response from buffer
    ser.reset_input_buffer()
    print(f"Sample rate set to {freq}Hz")

def init_board(ser):
    """Initialize the OpenBCI board for 16 channels"""
    print("Initializing board...")
    
    # Stop any previous streaming
    ser.write(b's')
    time.sleep(1)
    
    # Soft reset
    ser.write(b'v')
    time.sleep(2)
    
    # Clear buffers
    ser.reset_input_buffer()
    ser.reset_output_buffer()
    
    # Enable 16 channel mode
    ser.write(b'C')
    time.sleep(1)
    
    # Enable all channels (1-16)
    # First 8 channels
    commands = [b'!', b'@', b'#', b'$', b'%', b'^', b'&', b'*']
    # Next 8 channels (Daisy module)
    commands.extend([b'Q', b'W', b'E', b'R', b'T', b'Y', b'U', b'I'])
    
    for cmd in commands:
        ser.write(cmd)
        time.sleep(0.1)

    # Set high-speed mode
    ser.write(b'\xF0\x06')  # Set baud rate to 230400
    time.sleep(1)
    ser.baudrate = 230400

    set_gain(ser, gain=2)
    
    print("Board initialized")

def find_packet_start(ser):
    """Find the start of a packet by looking for 0xA0 header"""
    while True:
        byte = ser.read()
        if byte[0] == 0xA0:  # Header byte
            return byte
    return None

def read_complete_packet(ser):
    """Read a complete packet ensuring proper alignment"""
    # Find the start of packet
    start_byte = find_packet_start(ser)
    if not start_byte:
        return None
        
    # Read remaining 32 bytes
    remaining_bytes = ser.read(32)
    if len(remaining_bytes) != 32:
        return None
        
    # Verify footer byte (0xCx)
    if (remaining_bytes[31] & 0xF0) != 0xC0:
        return None
        
    return start_byte + remaining_bytes

def process_packet(packet):
    """Process a 33-byte packet and extract channel data according to documentation"""
    if len(packet) != 33:
        return None
    
    channels = []
    for i in range(8):
        start_idx = 2 + (i * 3)  # Start at byte 2 (after header and sample number)
        channel_data = packet[start_idx:start_idx + 3]
        
        # Convert 24-bit to 32-bit signed int according to documentation
        if (channel_data[0] & 0x80):  # If negative number
            value = -1 * ((((~channel_data[0] & 0xFF) << 16) | 
                          ((~channel_data[1] & 0xFF) << 8) | 
                          (~channel_data[2] & 0xFF)) + 1)
        else:  # If positive number
            value = (channel_data[0] << 16) | (channel_data[1] << 8) | channel_data[2]
            
        # Convert to microvolts: 4.5V / gain / (2^23 - 1)
        scale_factor = 4.5 / (24.0 * 8388607.0) * 1000000  # Using gain of 24
        channels.append(value * scale_factor)
        
    return channels

def start_sd_recording(ser, duration='G'):
    """Start recording to SD card with specified duration
    Duration codes:
    A = 5MIN
    S = 15MIN
    F = 30MIN
    G = 1HR (default)
    H = 2HR
    J = 4HR
    K = 12HR
    L = 24HR
    a = ~14sec (test)
    """
    valid_durations = {'A', 'S', 'F', 'G', 'H', 'J', 'K', 'L', 'a'}
    if duration not in valid_durations:
        raise ValueError(f"Invalid duration code. Valid codes: {valid_durations}")
    
    print(f"Starting SD card recording with duration code {duration}")
    ser.write(duration.encode())
    time.sleep(0.5)
    ser.write(b'b')
    time.sleep(0.5)
    
def stop_sd_recording(ser):
    """Stop SD card recording"""
    print("Stopping SD card recording")
    ser.write(b's')
    time.sleep(0.5)
    ser.write(b'j')
    time.sleep(0.5)

def sd_record(port, duration='G', sample_rate=1000):
    """Record data to SD card"""
    duration_map = {
        'A': 5*60,      # 5 minutes
        'S': 15*60,     # 15 minutes
        'F': 30*60,     # 30 minutes
        'G': 60*60,     # 1 hour
        'H': 2*60*60,   # 2 hours
        'J': 4*60*60,   # 4 hours
        'K': 12*60*60,  # 12 hours
        'L': 24*60*60,  # 24 hours
        'a': 14         # ~14 seconds (test)
    }

    # Open serial port
    ser = serial.Serial(port, 115200)
    time.sleep(2)
    
    try:
        # Initialize board
        init_board(ser)
        
        # Set sample rate
        set_sample_rate(ser, sample_rate)
        
        # Start recording
        start_sd_recording(ser, duration)
        
        # Calculate wait time
        wait_time = duration_map[duration]
        start_time = time.time()
        
        print(f"Recording to SD card for {wait_time} seconds...")
        
        try:
            while (time.time() - start_time) < wait_time:
                remaining = wait_time - (time.time() - start_time)
                print(f"\rRecording... {remaining:.1f} seconds remaining  ", end='')
                time.sleep(0.1)
                
        except KeyboardInterrupt:
            print("\nRecording interrupted by user")
        
        finally:
            # Always stop recording
            stop_sd_recording(ser)
            print("\nRecording complete")
            
    finally:
        ser.close()

def main():
    parser = argparse.ArgumentParser(description='OpenBCI EEG Recording Tool')
    parser.add_argument('--port', '-p', type=str, default='/dev/ttyUSB0',
                        help='Serial port to use (default: /dev/ttyUSB0)')
    parser.add_argument('--filename', '-o', type=str,
                        help='Output filename (default: openbci_<timestamp>.txt)')
    parser.add_argument('--sd', action='store_true',
                        help='Record to SD card instead of streaming to PC')
    parser.add_argument('--duration', type=str, default='G',
                        help='SD card recording duration code (default: G = 1 hour)')
    parser.add_argument('--sample-rate', type=int, default=1000,
                        help='Sample rate in Hz (default: 1000)')
    parser.add_argument('--remote', action='store_true',
                        help='Write to remote server instead of local file')
    args = parser.parse_args()

    if args.sd:
        sd_record(args.port, args.duration, args.sample_rate)
        return

    if args.filename is None:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        args.filename = f"openbci_{timestamp}.txt"

    # Open serial port
    ser = serial.Serial(args.port, 115200)
    time.sleep(2)
    init_board(ser)

    filename = args.filename

    if args.remote:
        ssh = create_ssh_connection()
        if not ssh:
            print("Failed to establish SSH connection. Exiting.")
            return

        sftp = ssh.open_sftp()
        remote_file = sftp.open(filename, 'w')

        # Write header
        header = "Timestamp,"
        header += ",".join([f"Channel{i+1}" for i in range(16)])
        header += "\n"
        remote_file.write(header)
    else:
        # Original local file writing
        with open(filename, 'w') as f:
            header = "Timestamp,"
            header += ",".join([f"Channel{i+1}" for i in range(16)])
            header += "\n"
            f.write(header)

    # Start streaming
    ser.write(b'b')
    time.sleep(0.5)
    ser.reset_input_buffer()

    print(f"Started recording to {filename}")

    packet_count = 0
    start_time = time.time()
    buffer = io.StringIO()
    last_write = time.time()

    try:
        while True:
            # Read two properly aligned packets
            packet1 = read_complete_packet(ser)
            if packet1:
                packet2 = read_complete_packet(ser)
                if packet2:
                    # Process both packets
                    data1 = process_packet(packet1)
                    data2 = process_packet(packet2)

                    if data1 and data2:
                        packet_count += 1
                        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
                        all_channels = data1 + data2  # Combine all 16 channels
                        data_str = [f"{x:.6f}" for x in all_channels]
                        line = timestamp + "," + ",".join(data_str) + "\n"

                        if args.remote:
                            buffer.write(line)

                            # Write buffer every 100ms
                            if time.time() - last_write >= 0.1:
                                remote_file.write(buffer.getvalue())
                                buffer = io.StringIO()
                                last_write = time.time()
                        else:
                            with open(filename, 'a') as f:
                                f.write(line)

                        # Print status every second
                        if packet_count % 125 == 0:
                            elapsed_time = time.time() - start_time
                            rate = packet_count / elapsed_time
                            print(f"\rRecording... {rate:.1f} Hz, {packet_count} packets", end='')

            # Check for buffer overflow
            if ser.in_waiting > 1000:
                print(f"\nWarning: Buffer building up ({ser.in_waiting} bytes)")
                ser.reset_input_buffer()

    except KeyboardInterrupt:
        # Stop streaming
        ser.write(b's')
        ser.close()

        if args.remote:
            # Write any remaining data in buffer
            if buffer.getvalue():
                remote_file.write(buffer.getvalue())
            remote_file.close()
            sftp.close()
            ssh.close()

        # Print final statistics
        elapsed_time = time.time() - start_time
        rate = packet_count / elapsed_time
        print(f"\n\nRecording stopped")
        print(f"Duration: {elapsed_time:.1f} seconds")
        print(f"Packets recorded: {packet_count}")
        print(f"Average sample rate: {rate:.1f} Hz")
        print(f"Data saved to: {filename}")

if __name__ == "__main__":
    main()