Skip to content
60 changes: 54 additions & 6 deletions octave/examples/recordAndMarker.m
Original file line number Diff line number Diff line change
Expand Up @@ -13,42 +13,63 @@ function recordAndMarker()
% Connect: establish authorization, connect the selected headset, and create its active session.
cortex = cortexConnect();
fig = [];
helpText = [];
statusText = [];
connectionCleanup = onCleanup(@cleanupConnection);
try
if ~cortex.isConnected
error('recordAndMarker:connect', 'Cortex connection or authorization failed.');
end
cortex = cortexSession(cortex, headsetId);
activeSessionId = cortex.manager.getContext().sessionId;
exitRequested = false;
fprintf('[recordAndMarker] Connected to %s. Key help:\n', headsetId);
fprintf(' S: start a record.\n');
fprintf(' A-Z except S: inject an instance marker; press that key again to end its interval.\n');
fprintf(' Esc: stop the record and exit.\n');

markerIds = struct();
fig = figure('Name', 'Cortex Record and Marker Example', 'NumberTitle', 'off', ...
'KeyPressFcn', @onKeyPress, 'Interruptible', 'off', 'BusyAction', 'queue');
'MenuBar', 'none', 'ToolBar', 'none', ...
'KeyPressFcn', @onKeyPress, 'WindowButtonDownFcn', @focusKeyboardTarget, ...
'Interruptible', 'off', 'BusyAction', 'queue');
helpLines = {'Keyboard controls', '', ...
'S: start a new record', ...
'A-Z (except S): add an instance marker while recording', ...
'Press the same letter again: end its marker interval', ...
'Esc: stop the record and exit', '', ...
'Click in this window before typing a shortcut.', '', ...
'Marker ID, type, start time, and end time are printed', ...
'in the Command Window after each marker action.'};
helpText = uicontrol(fig, 'Style', 'text', 'Units', 'normalized', ...
'Position', [0.08 0.12 0.84 0.78], ...
'String', helpLines, ...
'HorizontalAlignment', 'left', 'FontSize', 12, ...
'BackgroundColor', get(fig, 'Color'), 'Enable', 'on', ...
'KeyPressFcn', @onKeyPress, 'Interruptible', 'off', 'BusyAction', 'queue');
'KeyPressFcn', @onKeyPress, 'ButtonDownFcn', @focusKeyboardTarget, ...
'Interruptible', 'off', 'BusyAction', 'queue');
statusText = uicontrol(fig, 'Style', 'text', 'Units', 'normalized', ...
'Position', [0.08 0.02 0.84 0.08], ...
'String', 'Ready: press S to start a record.', ...
'HorizontalAlignment', 'left', 'FontSize', 10, ...
'BackgroundColor', get(fig, 'Color'), 'Enable', 'on', ...
'KeyPressFcn', @onKeyPress, 'Interruptible', 'off', 'BusyAction', 'queue');
'KeyPressFcn', @onKeyPress, 'ButtonDownFcn', @focusKeyboardTarget, ...
'Interruptible', 'off', 'BusyAction', 'queue');
focusKeyboardTarget([], []);

% Acquire: wait for keyboard events while Cortex keeps the active session open.
uiwait(fig);
% Poll periodically while waiting so session-close warnings are handled even when idle.
while ishandle(fig) && ~exitRequested
uiwait(fig, 1);
if ishandle(fig)
try
headset = cortex.manager.getHeadset();
headset.update();
syncSessionState();
catch pollFailure
fprintf('[recordAndMarker] Cortex poll failed: %s\n', pollFailure.message);
end
end
end
catch failure
fprintf('[recordAndMarker] ERROR %s: %s\n', failure.identifier, failure.message);
end
Expand All @@ -71,6 +92,7 @@ function onKeyPress(source, event)
showStatus(['Could not stop record: ' stopFailure.message]);
end
end
exitRequested = true;
if ishandle(fig), uiresume(fig); end
return;
end
Expand Down Expand Up @@ -147,8 +169,34 @@ function showStatus(message)
end
end

function focusKeyboardTarget(~, ~)
if ~isempty(fig) && ishandle(fig) && ~isempty(helpText) && ishandle(helpText)
figure(fig);
uicontrol(helpText);
end
end

function syncSessionState()
context = cortex.manager.getContext();
if strcmp(context.sessionId, activeSessionId), return; end

cortex.isRecording = false;
cortex.recordId = '';
markerIds = struct();
activeSessionId = context.sessionId;
if isempty(activeSessionId)
set(fig, 'Visible', 'off');
Comment thread
khanhle1993 marked this conversation as resolved.
Resolved
showStatus('Session closed. Scanning for headset...');
else
set(fig, 'Visible', 'on');
focusKeyboardTarget([], []);
showStatus('Session restored. Ready to start a new record.');
end
end

function cleanupConnection()
if cortex.isRecording
context = cortex.manager.getContext();
if cortex.isRecording && context.isRecording
try
[cortex, ~] = cortexRecord(cortex, 'stop');
catch stopFailure
Expand Down
17 changes: 15 additions & 2 deletions octave/examples/subscribeAndPlot.m
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@ function subscribeAndPlot()
currentDir = fileparts(mfilename('fullpath'));
addpath(fullfile(currentDir, '../functions'));

% Set your headset id (shown in EMOTIV Launcher, for example 'INSIGHT-A1B2C3D4').
% Set your headset ID.
headsetId = '<YOUR_HEADSET_ID>';
% For EPOC Flex, also set the electrode map.
mappings = struct('CMS', 'TP9', 'DRL', 'TP10', ...
'LA', 'FC5', 'LB', 'O1', 'LC', 'P7', 'LD', 'T7', ...
'LE', 'F3', 'LF', 'F7', 'LG', 'AF3', ...
'RA', 'FC6', 'RB', 'O2', 'RC', 'P8', 'RD', 'T8', ...
'RE', 'F4', 'RF', 'F8', 'RG', 'AF4');
streams = {'eeg'};
durationSeconds = 90;

Expand All @@ -15,7 +21,11 @@ function subscribeAndPlot()
cortex = cortexConnect();
connectionCleanup = onCleanup(@() cortexDisconnect(cortex));
if cortex.isConnected
cortex = cortexSession(cortex, headsetId);
if isempty(strfind(upper(headsetId), 'FLEX'))
cortex = cortexSession(cortex, headsetId);
else
cortex = cortexSession(cortex, headsetId, 'mappings', mappings);
end
cortex = cortexSubscribe(cortex, streams);
end

Expand Down Expand Up @@ -89,6 +99,9 @@ function plotEeg(fig, labels, data, time)
% plotEeg Plot multi-channel EEG with +/-100 uV per trace and 200 uV channel spacing.
figure(fig);
channels = find(strcmp(labels, 'INTERPOLATED')) + 1:find(strcmp(labels, 'RAW_CQ')) - 1;
if isempty(channels)
channels = find(~ismember(labels, {'COUNTER', 'INTERPOLATED', 'RAW_CQ', 'MARKER', 'TIMESTAMP'}));
end
if isempty(channels), return; end

eeg = data(:, channels);
Expand Down
14 changes: 11 additions & 3 deletions octave/functions/cortexSession.m
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
% Calling it again for the same active headset reuses that session; another headset
% cannot be connected until the current Cortex connection is closed.
% Optional name/value pairs: autoRescan (true), queryInterval (3 seconds),
% and scanTimeout (30 seconds).
% scanTimeout (30 seconds), and mappings (a scalar struct for EPOC Flex).

options = struct('autoRescan', true, 'queryInterval', 3, 'scanTimeout', 30);
options = struct('autoRescan', true, 'queryInterval', 3, 'scanTimeout', 30, 'mappings', []);
if mod(numel(varargin), 2) ~= 0
error('cortex:sessionFailed', 'Options must be supplied as name/value pairs.');
end
Expand All @@ -25,6 +25,14 @@
if ~ischar(headsetId) || isempty(headsetId)
error('cortex:sessionFailed', 'headsetId must be a non-empty character vector.');
end
if ~isempty(options.mappings)
if ~isstruct(options.mappings) || ~isscalar(options.mappings) || isempty(fieldnames(options.mappings))
error('cortex:sessionFailed', 'mappings must be a non-empty scalar struct.');
end
if isempty(strfind(upper(headsetId), 'FLEX'))
error('cortex:sessionFailed', 'mappings can only be supplied for an EPOC Flex headset.');
end
end

manager = cortex.manager;
context = manager.getContext();
Expand All @@ -48,7 +56,7 @@
headsetId, options.scanTimeout);
end

[ok, message] = headset.connectToHeadset(headsetId, {});
[ok, message] = headset.connectToHeadset(headsetId, {}, options.mappings);
if ~ok
error('CortexHeadset:connect', '%s', message);
end
Expand Down
Loading
Loading