示例#1
0
def initialize_board(name='SYNTHETIC',port = None):
    if name == 'SYNTHETIC':
        BoardShim.enable_dev_board_logger()

        # use synthetic board for demo
        params = BrainFlowInputParams()
        board_id = BoardIds.SYNTHETIC_BOARD.value
        board = BoardShim(board_id, params)
        board.rate = BoardShim.get_sampling_rate(board_id)
        board.channels = BoardShim.get_eeg_channels(board_id)
        board.time_channel = BoardShim.get_timestamp_channel(board_id)
        board.eeg_channels = BoardShim.get_eeg_channels(board_id)
        board.accel_channels = BoardShim.get_accel_channels(board_id)

    elif name == 'OPENBCI':

        board_id = BoardIds.CYTON_DAISY_BOARD.value
        params = BrainFlowInputParams()
        params.serial_port = port
        board_id = BoardIds.CYTON_DAISY_BOARD.value
        board = BoardShim(board_id, params)
        board.rate = BoardShim.get_sampling_rate(board_id)
        board.channels = BoardShim.get_eeg_channels(board_id)
        board.time_channel = BoardShim.get_timestamp_channel(board_id)
        board.eeg_channels = BoardShim.get_eeg_channels(board_id)
        board.accel_channels = BoardShim.get_accel_channels(board_id)

    print('Must have OpenBCI GUI open to work... (as port is not opened by Brainflow)')
    board.prepare_session()
    return board
def convert (old_file, new_file):
    with open (old_file) as f:
        old_lines = f.readlines ()

    x_accel = '0.0'
    y_accel = '0.0'
    z_accel = '0.0'

    with open (new_file, 'w') as f:

        for i, line in enumerate (old_lines):
            if i == 0:
                f.write (line)
            elif i == 1:
                num_channels = find_int_in_string (line)
                f.write (line)
            elif i == 2:
                # sampling rate from double to int
                patched_string = line.replace ('.0 Hz', ' Hz')
                sampling_rate = find_int_in_string (patched_string)
                f.write (patched_string)
                board_class, board_id = get_board_class (num_channels, sampling_rate)
                board_line = '%%Board = OpenBCI_GUI$%s\n' % board_class
                f.write (board_line)
                # need to determine number of rows in new file
                num_rows = BoardShim.get_num_rows (board_id.value)
                accel_channels = BoardShim.get_accel_channels (board_id.value)
                stub_string = ['0.0' for i in range (num_rows + 1)]
                write_array (f, stub_string)
            # skip other lines in old header
            elif line.startswith ('%'):
                continue
            # start parsing data
            else:
                line = line.strip ('\n')
                data_points = line.split (',')
                new_data_points = list ()
                # first package and eeg are the same place always
                for i in range (1 + num_channels):
                    new_data_points.append (data_points[i])
                i = 1 + num_channels
                while i != accel_channels[0]:
                    i = i + 1
                    new_data_points.append ('0.0')
                # always 3 accel channels
                if not compare_floats (float(data_points[i]), 0.0):
                    x_accel = data_points[i]
                    y_accel = data_points[i + 1]
                    z_accel = data_points[i + 2]
                new_data_points.append (x_accel)
                new_data_points.append (y_accel)
                new_data_points.append (z_accel)
                i = i + 3
                while i < num_rows - 1:
                    i = i + 1
                    new_data_points.append ('0.0')
                # last two columns timestamps but reversed
                new_data_points.append (data_points[-1])
                new_data_points.append (data_points[-2])
                write_array (f, new_data_points)
示例#3
0
class OpenBCIInterface:
    def __init__(self,
                 serial_port='COM5',
                 board_id=0,
                 log='store_true',
                 streamer_params='',
                 ring_buffer_size=45000):  # default board_id 2 for Cyton
        params = BrainFlowInputParams()
        params.serial_port = serial_port
        params.ip_port = 0
        params.mac_address = ''
        params.other_info = ''
        params.serial_number = ''
        params.ip_address = ''
        params.ip_protocol = 0
        params.timeout = 0
        params.file = ''
        self.streamer_params = streamer_params
        self.ring_buffer_size = ring_buffer_size
        self.board_id = board_id
        self.info_eeg = None
        self.info_aux = None
        self.outlet_eeg = None
        self.outlet_aux = None

        if (log):
            BoardShim.enable_dev_board_logger()
        else:
            BoardShim.disable_board_logger()

        self.board = BoardShim(board_id, params)

    def start_sensor(self):
        # tell the sensor to start sending frames
        self.board.prepare_session()
        print('OpenBCIInterface: connected to sensor')
        print(self.board.get_board_id())

        try:
            self.board.start_stream(self.ring_buffer_size,
                                    self.streamer_params)
            self.infor_test()
        except brainflow.board_shim.BrainFlowError:
            print('OpenBCIInterface: Board is not ready.')

    def process_frames(self):
        # return one or more frames of the sensor
        frames = self.board.get_board_data()
        return frames

    def stop_sensor(self):
        try:
            self.board.stop_stream()
            print('OpenBCIInterface: stopped streaming.')
            self.board.release_session()
            print('OpenBCIInterface: released session.')
        except brainflow.board_shim.BrainFlowError as e:
            print(e)

    def create_lsl(self,
                   name='OpenBCI_Cyton_8',
                   type='EEG',
                   channel_count=8,
                   nominal_srate=250.0,
                   channel_format='float32',
                   source_id='Cyton_0'):

        self.info_eeg = StreamInfo(name=name,
                                   type=type,
                                   channel_count=channel_count,
                                   nominal_srate=nominal_srate,
                                   channel_format=channel_format,
                                   source_id='')

        chns = self.info_eeg.desc().append_child('channels')

        self.labels = ['Fp1', 'Fp2', 'C3', 'C4', 'T5', 'T6', 'O1', 'O2']

        for label in self.labels:
            ch = chns.append_child("channel")
            ch.append_child_value('label', label)
            ch.append_child_value('unit', 'microvolts')
            ch.append_child_value('type', 'EEG')

        self.info_eeg.desc().append_child_value('manufacturer', 'OpenBCI Inc.')
        self.outlet_eeg = StreamOutlet(self.info_eeg)

        print("--------------------------------------\n" + \
              "LSL Configuration: \n" + \
              "  Stream 1: \n" + \
              "      Name: " + name + " \n" + \
              "      Type: " + type + " \n" + \
              "      Channel Count: " + str(channel_count) + "\n" + \
              "      Sampling Rate: " + str(nominal_srate) + "\n" + \
              "      Channel Format: " + channel_format + " \n" + \
              "      Source Id: " + source_id + " \n")

    def push_sample(self, samples):
        self.outlet_eeg.push_sample(samples)

    def infor_test(self):
        print(self.board.get_eeg_names(self.board_id))
        print(self.board.get_sampling_rate(self.board_id))
        print(self.board.get_board_id())
        print(self.board.get_package_num_channel(self.board_id))
        print(self.board.get_timestamp_channel(self.board_id))
        print(self.board.get_eeg_channels(self.board_id))
        print(self.board.get_accel_channels(self.board_id))
        print(self.board.get_marker_channel(self.board_id))
        print(self.board.get_other_channels(self.board_id))
        print(self.board.get_analog_channels(self.board_id))
        print(self.board.get_other_channels(self.board_id))
示例#4
0
class OpenBCILSLInterface:

    def __init__(self, stream_name='OpenBCI_Cyton_8', stream_type='EEG', serial_port='COM5', board_id="0",
                 log='store_true', streamer_params='',
                 ring_buffer_size=45000):  # default board_id 2 for Cyton
        self.params = BrainFlowInputParams()
        self.params.serial_port = serial_port
        self.params.ip_port = 0
        self.params.mac_address = ''
        self.params.other_info = ''
        self.params.serial_number = ''
        self.params.ip_address = ''
        self.params.ip_protocol = 0
        self.params.timeout = 0
        self.params.file = ''

        self.stream_name = stream_name
        self.stream_type = stream_type
        self.board_id = int(board_id)
        self.streamer_params = streamer_params
        self.ring_buffer_size = ring_buffer_size

        if (log):
            BoardShim.enable_dev_board_logger()
        else:
            BoardShim.disable_board_logger()

        try:
            self.board = BoardShim(self.board_id, self.params)
            self.info_print()

        except brainflow.board_shim.BrainFlowError:
            print('Cannot connect to board')

    def start_sensor(self):
        # tell the sensor to start sending frames
        try:
            self.board.prepare_session()
        except brainflow.board_shim.BrainFlowError:
            raise AssertionError('Unable to connect to device: please check the sensor connection or the COM port number in device preset.')
        print('OpenBCIInterface: connected to sensor')

        try:
            self.board.start_stream(self.ring_buffer_size, self.streamer_params)
        except brainflow.board_shim.BrainFlowError:
            raise AssertionError('Unable to connect to device: please check the sensor connection or the COM port number in device preset.')
        print('OpenBCIInterface: connected to sensor')

        self.create_lsl(name=self.stream_name,
                        type=self.stream_type,
                        nominal_srate=self.board.get_sampling_rate(self.board_id),
                        channel_format='float32',
                        source_id='Cyton_' + str(self.board_id))

    def process_frames(self):
        # return one or more frames of the sensor
        frames = self.board.get_board_data()

        for frame in frames.T:
            self.push_frame(frame)
        # TODO: fine push chunk error
        # frames = np.transpose(frames)
        # tesst = [[rand() for chan_ix in range(24)]
        #            for samp_ix in range(6)]
        # # frames = frames.astype('float32')
        # if frames.shape[0] > 0:
        #     self.push_frame(samples=frames)

        return frames

    def stop_sensor(self):
        try:
            self.board.stop_stream()
            print('OpenBCIInterface: stopped streaming.')
            self.board.release_session()
            print('OpenBCIInterface: released session.')
        except brainflow.board_shim.BrainFlowError as e:
            print(e)

    def create_lsl(self, name='OpenBCI_Cyton_8', type='EEG',
                   nominal_srate=250.0, channel_format='float32',
                   source_id='Cyton_0'):

        channel_count = self.board.get_num_rows(self.board_id)
        self.info_eeg = StreamInfo(name=name, type=type, channel_count=channel_count,
                                   nominal_srate=nominal_srate, channel_format=channel_format,
                                   source_id=source_id)

        # chns = self.info_eeg.desc().append_child('channels')
        #
        # self.labels = ['Fp1', 'Fp2', 'C3', 'C4', 'T5', 'T6', 'O1', 'O2']
        #
        # for label in self.labels:
        #     ch = chns.append_child("channel")
        #     ch.append_child_value('label', label)
        #     ch.append_child_value('unit', 'microvolts')
        #     ch.append_child_value('type', 'EEG')
        #
        # self.info_eeg.desc().append_child_value('manufacturer', 'OpenBCI Inc.')
        self.outlet_eeg = StreamOutlet(self.info_eeg)

        print("--------------------------------------\n" + \
              "LSL Configuration: \n" + \
              "  Stream 1: \n" + \
              "      Name: " + name + " \n" + \
              "      Type: " + type + " \n" + \
              "      Channel Count: " + str(channel_count) + "\n" + \
              "      Sampling Rate: " + str(nominal_srate) + "\n" + \
              "      Channel Format: " + channel_format + " \n" + \
              "      Source Id: " + source_id + " \n")

    def push_frame(self, samples):
        self.outlet_eeg.push_sample(samples)

    def info_print(self):
        print("Board Information:")
        print("Sampling Rate:", self.board.get_sampling_rate(self.board_id))
        print("Board Id:", self.board.get_board_id())
        print("EEG names:", self.board.get_eeg_names(self.board_id))
        print("Package Num Channel: ", self.board.get_package_num_channel(self.board_id))
        print("EEG Channels:", self.board.get_eeg_channels(self.board_id))
        print("Accel Channels: ", self.board.get_accel_channels(self.board_id))
        print("Other Channels:", self.board.get_other_channels(self.board_id))
        print("Analog Channels: ", self.board.get_analog_channels(self.board_id))
        print("TimeStamp: ", self.board.get_timestamp_channel(self.board_id))
        print("Marker Channel: ", self.board.get_marker_channel(self.board_id))
示例#5
0
def main():
    parser = argparse.ArgumentParser()
    # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port
    parser.add_argument('--ip-port',
                        type=int,
                        help='ip port',
                        required=False,
                        default=0)
    parser.add_argument('--ip-protocol',
                        type=int,
                        help='ip protocol, check IpProtocolType enum',
                        required=False,
                        default=0)
    parser.add_argument('--ip-address',
                        type=str,
                        help='ip address',
                        required=False,
                        default='')
    parser.add_argument('--serial-port',
                        type=str,
                        help='serial port',
                        required=False,
                        default='')
    parser.add_argument('--mac-address',
                        type=str,
                        help='mac address',
                        required=False,
                        default='')
    parser.add_argument('--other-info',
                        type=str,
                        help='other info',
                        required=False,
                        default='')
    parser.add_argument(
        '--board-id',
        type=int,
        help='board id, check docs to get a list of supported boards',
        required=True)
    parser.add_argument('--log', action='store_true')
    args = parser.parse_args()

    # in fact it can be CytonDaisy or Wifi Shield based boards, limit it to only Cyton in demo
    if args.board_id != BoardIds.CYTON_BOARD.value:
        raise ValueError('wrong board id, should be Cyton')

    params = BrainFlowInputParams()
    params.ip_port = args.ip_port
    params.serial_port = args.serial_port
    params.mac_address = args.mac_address
    params.other_info = args.other_info
    params.ip_address = args.ip_address
    params.ip_protocol = args.ip_protocol

    if (args.log):
        BoardShim.enable_dev_board_logger()
    else:
        BoardShim.disable_board_logger()

    board = BoardShim(args.board_id, params)
    board.prepare_session()

    board.config_board('/2')  # enable analog mode only for Cyton Based Boards!

    board.start_stream()
    time.sleep(10)
    data = board.get_board_data()
    board.stop_stream()
    board.release_session()

    other_channels = BoardShim.get_other_channels(args.board_id)
    accel_channels = BoardShim.get_accel_channels(args.board_id)
    analog_channels = BoardShim.get_analog_channels(args.board_id)
    """
    data format for cyton with analog and accel data,
    data[get_other_channels(board_id)[0]] contains cyton end byte
    if end byte is 0xC0 there are accel data in data[get_accel_channels(board_id)[....]] else there are zeros
    if end byte is 0xC1 there are analog data in data[get_analog_channels(board_id)[....]] else there are zeros
    """
    if not other_channels:
        raise ValueError('no cyton end byte foud')

    print('end bytes for first 20 packages:')
    print(data[other_channels[0]][0:20])

    # we send /2 to enable analog mode so here we will see zeroes
    print('accel data for first 20 packages:')
    for count, channel in enumerate(accel_channels):
        print(data[channel][0:20])

    # analog data are in int32 format but we return single array fron low level api so it was casted to double wo any changes
    print('analog data for first 20 packages:')
    for count, channel in enumerate(analog_channels):
        print(data[channel][0:20])
示例#6
0
文件: bf.py 项目: bookRa/keisaku
todays_sessions = os.listdir(todays_sessions_path)
curr_sesh_name = f"Session_{len(todays_sessions)+1}"
if args.synth:
    curr_sesh_name += "_SYNTH"
current_session_dir = os.path.join(todays_sessions_path, curr_sesh_name)
os.mkdir(current_session_dir)
raw_data_path = os.path.join(current_session_dir, "raw_data.csv")

board_id = BoardIds.SYNTHETIC_BOARD.value if args.synth else BoardIds.CYTON_DAISY_BOARD.value

sampling_rate = BoardShim.get_sampling_rate(board_id)
eegs = BoardShim.get_eeg_channels(board_id)
battery = BoardShim.get_battery_channel(board_id)
resistance = BoardShim.get_resistance_channels(board_id)
timestamp = BoardShim.get_timestamp_channel(board_id)
others = BoardShim.get_accel_channels(
    board_id) if args.synth else BoardShim.get_other_channels(board_id)
columns = ['timestamp'] + [f'ch_{x+1}' for x in range(len(eegs))
                           ] + [f'aux_{x+1}' for x in range(len(others))]
with open(raw_data_path, 'w') as raw:
    raw.write(','.join(columns) + '\n')

if args.debug:
    BoardShim.enable_dev_board_logger()
    for c in ['eegs', 'battery', 'resistance', 'others', 'timestamp']:
        log_debug(f'Channel for {c} is {eval(c)} ')
    log_debug(f"sampling rate is {sampling_rate} with board ID {board_id}")

DataFilter.write_file
BUFFER_TIME = args.buffer
params = BrainFlowInputParams() if args.synth else fill_in_cyton_params()
board = BoardShim(board_id=board_id, input_params=params)
import numpy as np
import brainflow
from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds
from brainflow.data_filter import DataFilter, FilterTypes, AggOperations
from pylsl import StreamInfo, StreamOutlet

#from queue import Queue
BoardShim.enable_dev_board_logger()
params = BrainFlowInputParams()
params.serial_port = '/dev/cu.usbserial-DM00D7TW'
board = BoardShim(BoardIds.CYTON_BOARD.value, params) # added cyton board id here
srate = board.get_sampling_rate(BoardIds.CYTON_BOARD.value)
board.prepare_session()
board.start_stream()
eeg_chan = BoardShim.get_eeg_channels(BoardIds.CYTON_BOARD.value)
aux_chan = BoardShim.get_accel_channels(BoardIds.CYTON_BOARD.value)

print('EEG channels:')
print(eeg_chan)
print('Accelerometer channels')
print(aux_chan)

# define lsl streams

# Defining stream info:
name = 'OpenBCIEEG'
ID = 'OpenBCIEEG'
channels = 8
sample_rate = 250
datatype = 'float32'
streamType = 'EEG'