% muse_test 1.0 by Olav Krigolson, July 11 2016

%%% SOME INITIALIZATION STUFF
clear all;
close all;
clc;
num_samples = 500; % we want 1000 ms of data, or 500 samples as we are at 500 Hz sampling rate with the AD preset
length_of_erp = 1; % we want 1 second of data
osc_wait_factor = 1.5; % This factor determines how long we'll wait for data, e.g. if we're trying to get 1000 ms of data then we are willing to wait up to 1500 ms
osc_timeout = 0.1; % Timeout for receiving OSC messages

%%% OPEN THE CONNECTION
osc_stream = osc_new_server(5555); % creates a new OSC server on Port 5555
u = udp('127.0.0.1',5556); % specify the UDP address MUSE data will come in on (essentially adds Port 5556)
fopen(u); % open the connection with MUSE

%%% GET ONE SECOND OF DATA
eeg = nan(4,num_samples); % make a variable to hold the eeg data in
counter = 1; % define a sample counter
tic; % start a clock
while counter <= num_samples && toc <= osc_wait_factor*length_of_erp % nake sure we have the amount of data we want and we have waited long enough for it
    muse_data = osc_recv(osc_stream,0.1); % read in some MUSE data
    if ~isempty(muse_data)
        for p = 1:length(muse_data)
            this_path = muse_data{p}.path; % find the bit we want
            if strcmp(this_path,'/muse/eeg') % specifically find the eeg data
                eeg(:,counter) = double(cell2mat(muse_data{p}.data))'; %convert the data into a numeric format
                counter = counter + 1;
                if counter >= num_samples % exit out of this once we have 500 samples of data
                    break;
                end
            end
        end
    end
end

%%% CLOSE THE CONNECTION
osc_free_server(osc_stream); % releases the connection with MUSE
fclose(u); % closes the port MUSE was using