From 30fd0cfe39b569edcf76fa54bb8ceb37d0c606ae Mon Sep 17 00:00:00 2001 From: KhanhLe Date: Wed, 18 Nov 2026 08:40:07 +0700 Subject: [PATCH 01/10] COR-6620: Handle case headset disconnected for Octave example --- octave/examples/recordAndMarker.m | 39 +++++++++++++++-- octave/internal/CortexHeadset.m | 71 +++++++++++++++++++++++++++++-- 2 files changed, 104 insertions(+), 6 deletions(-) diff --git a/octave/examples/recordAndMarker.m b/octave/examples/recordAndMarker.m index 40d1a8a..954e692 100644 --- a/octave/examples/recordAndMarker.m +++ b/octave/examples/recordAndMarker.m @@ -19,6 +19,8 @@ function recordAndMarker() 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'); @@ -47,8 +49,19 @@ function recordAndMarker() 'BackgroundColor', get(fig, 'Color'), 'Enable', 'on', ... 'KeyPressFcn', @onKeyPress, 'Interruptible', 'off', 'BusyAction', 'queue'); - % 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 @@ -71,6 +84,7 @@ function onKeyPress(source, event) showStatus(['Could not stop record: ' stopFailure.message]); end end + exitRequested = true; if ishandle(fig), uiresume(fig); end return; end @@ -147,8 +161,27 @@ function showStatus(message) 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'); + showStatus('Session closed. Scanning for headset...'); + else + set(fig, 'Visible', 'on'); + figure(fig); + 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 diff --git a/octave/internal/CortexHeadset.m b/octave/internal/CortexHeadset.m index 5bf39f4..6fa038c 100644 --- a/octave/internal/CortexHeadset.m +++ b/octave/internal/CortexHeadset.m @@ -20,6 +20,12 @@ scanFinished = false lastQueryAt = [] parser + reconnectHeadsetId = '' + reconnectStreams = {} + reconnectProfileName = '' + reconnectProfileWasLoaded = false + reconnectPending = false + reconnectSessionReady = false end methods @@ -30,6 +36,7 @@ if isempty(context.buffer) context.buffer = CortexDataBuffer(10000); end + obj.client.onWarning(0, @(warning) obj.onSessionClosed(warning)); obj.client.onWarning(1, @(warning) obj.onSessionClosed(warning)); obj.client.onWarning(142, @(warning) obj.onScanFinished(warning)); end @@ -114,8 +121,12 @@ function stopScan(obj) if ~strcmp(headset.status, 'connected') if ~strcmp(headset.status, 'connecting') fprintf('[CortexHeadset] Connecting to %s...\n', headsetId); - obj.client.sendRequest('controlDevice', ... - struct('command', 'connect', 'headset', headsetId)); + params = struct('command', 'connect', 'headset', headsetId); + if ~isempty(strfind(upper(headsetId), 'FLEX')) + params.mappings = struct('CMS', 'TP8', 'DRL', 'P6', ... + 'RM', 'TP10', 'RN', 'P4', 'RO', 'P8'); + end + obj.client.sendRequest('controlDevice', params); end if isempty(obj.client.waitForWarning(104, obj.connectTimeout)) message = sprintf(['Connection to %s was not successful: warning 104 ' ... @@ -143,6 +154,7 @@ function stopScan(obj) sessionId = response.result.id; obj.context.sessionId = sessionId; obj.context.headsetId = headsetId; + obj.reconnectHeadsetId = headsetId; end function subscribe(obj, streams) @@ -177,6 +189,7 @@ function subscribe(obj, streams) if ~obj.isSubscribed error('CortexHeadset:subscribe', 'Cortex did not accept any data stream.'); end + obj.reconnectStreams = obj.context.subscribedStreams; end function unsubscribe(obj) @@ -226,17 +239,32 @@ function onSessionClosed(obj, warning) return; end - obj.isScanning = false; + obj.reconnectHeadsetId = obj.context.headsetId; + obj.reconnectStreams = obj.context.subscribedStreams; + obj.reconnectProfileName = obj.context.profileName; + obj.reconnectProfileWasLoaded = obj.context.isProfileLoaded; + obj.reconnectPending = ~isempty(obj.reconnectHeadsetId); + obj.reconnectSessionReady = false; + obj.isScanning = obj.reconnectPending; + obj.autoRescan = true; + obj.scanFinished = obj.reconnectPending; + obj.lastQueryAt = []; obj.isSubscribed = false; obj.context.sessionId = ''; obj.context.headsetId = ''; obj.context.subscribedStreams = {}; + obj.context.streamLabels = struct(); obj.context.isRecording = false; obj.context.recordId = ''; obj.context.profileName = ''; obj.context.isProfileLoaded = false; + obj.context.detectionInfo = struct(); + obj.context.trainingEvents = {}; obj.parser.reset(); fprintf('[CortexHeadset] Session %s was closed by Cortex.\n', warning.message.sessionId); + if obj.reconnectPending + fprintf('[CortexHeadset] Scanning to reconnect %s...\n', obj.reconnectHeadsetId); + end end function runScanTimer(obj) @@ -246,6 +274,43 @@ function runScanTimer(obj) end if isempty(obj.lastQueryAt) || toc(obj.lastQueryAt) >= obj.queryInterval obj.queryHeadsets(); + if obj.reconnectPending + obj.reconnectIfAvailable(); + end + end + end + + function reconnectIfAvailable(obj) + headset = obj.findHeadset(obj.reconnectHeadsetId); + if isempty(headset), return; end + + if ~obj.reconnectSessionReady + [ok, message] = obj.connectToHeadset(obj.reconnectHeadsetId, {}); + if ~ok + fprintf('[CortexHeadset] Reconnect attempt failed: %s\n', message); + obj.isScanning = true; + obj.lastQueryAt = tic(); + return; + end + obj.reconnectSessionReady = true; + end + + try + if obj.reconnectProfileWasLoaded + profile = CortexProfile(obj.client, obj.context); + profile.loadOrCreate(obj.reconnectProfileName); + end + if ~isempty(obj.reconnectStreams) + obj.subscribe(obj.reconnectStreams); + end + obj.reconnectPending = false; + obj.reconnectSessionReady = false; + obj.isScanning = false; + fprintf('[CortexHeadset] Reconnected to %s.\n', obj.reconnectHeadsetId); + catch failure + fprintf('[CortexHeadset] Could not restore the session: %s\n', failure.message); + obj.isScanning = true; + obj.lastQueryAt = tic(); end end From 49eb2b6f065bed034ebd0d637c89ad2904770762 Mon Sep 17 00:00:00 2001 From: KhanhLe Date: Wed, 18 Nov 2026 08:51:53 +0700 Subject: [PATCH 02/10] Update logic --- octave/internal/CortexHeadset.m | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/octave/internal/CortexHeadset.m b/octave/internal/CortexHeadset.m index 6fa038c..a1d80f7 100644 --- a/octave/internal/CortexHeadset.m +++ b/octave/internal/CortexHeadset.m @@ -14,6 +14,11 @@ queryInterval = 3 end + properties (Constant, Access = private) + flexMapping = struct('CMS', 'TP8', 'DRL', 'P6', ... + 'RM', 'TP10', 'RN', 'P4', 'RO', 'P8') + end + properties (Access = private) client context @@ -123,8 +128,7 @@ function stopScan(obj) fprintf('[CortexHeadset] Connecting to %s...\n', headsetId); params = struct('command', 'connect', 'headset', headsetId); if ~isempty(strfind(upper(headsetId), 'FLEX')) - params.mappings = struct('CMS', 'TP8', 'DRL', 'P6', ... - 'RM', 'TP10', 'RN', 'P4', 'RO', 'P8'); + params.mappings = CortexHeadset.flexMapping; end obj.client.sendRequest('controlDevice', params); end From 80a82ba5b9aec3af5066a3875af6eeff52d9d285 Mon Sep 17 00:00:00 2001 From: KhanhLe Date: Wed, 18 Nov 2026 09:52:58 +0700 Subject: [PATCH 03/10] Update logic --- octave/examples/recordAndMarker.m | 23 ++++++++-- octave/examples/subscribeAndPlot.m | 69 ++++-------------------------- octave/functions/cortexSession.m | 14 ++++-- octave/internal/CortexHeadset.m | 19 ++++++-- 4 files changed, 53 insertions(+), 72 deletions(-) diff --git a/octave/examples/recordAndMarker.m b/octave/examples/recordAndMarker.m index 954e692..e619c43 100644 --- a/octave/examples/recordAndMarker.m +++ b/octave/examples/recordAndMarker.m @@ -13,6 +13,8 @@ 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 @@ -28,12 +30,15 @@ function recordAndMarker() 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', ... @@ -41,13 +46,16 @@ function recordAndMarker() '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([], []); % Poll periodically while waiting so session-close warnings are handled even when idle. while ishandle(fig) && ~exitRequested @@ -161,6 +169,13 @@ 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 @@ -174,7 +189,7 @@ function syncSessionState() showStatus('Session closed. Scanning for headset...'); else set(fig, 'Visible', 'on'); - figure(fig); + focusKeyboardTarget([], []); showStatus('Session restored. Ready to start a new record.'); end end diff --git a/octave/examples/subscribeAndPlot.m b/octave/examples/subscribeAndPlot.m index 5f18856..bcc01ce 100644 --- a/octave/examples/subscribeAndPlot.m +++ b/octave/examples/subscribeAndPlot.m @@ -1,12 +1,14 @@ function subscribeAndPlot() -% subscribeAndPlot Subscribe to EEG, motion (mot), and performance metrics (met) streams and plot live. +% subscribeAndPlot Subscribe to the EEG stream and plot it live. % 1. Initialization & Configuration: make the SDK functions visible. currentDir = fileparts(mfilename('fullpath')); addpath(fullfile(currentDir, '../functions')); -% Set your headset id (shown in EMOTIV Launcher, for example 'INSIGHT-A1B2C3D4'). +% Set the EPOC Flex headset id and electrode map. headsetId = ''; +mappings = struct('CMS', 'TP8', 'DRL', 'P6', ... + 'RM', 'TP10', 'RN', 'P4', 'RO', 'P8'); streams = {'eeg'}; durationSeconds = 90; @@ -15,7 +17,7 @@ function subscribeAndPlot() cortex = cortexConnect(); connectionCleanup = onCleanup(@() cortexDisconnect(cortex)); if cortex.isConnected - cortex = cortexSession(cortex, headsetId); + cortex = cortexSession(cortex, headsetId, 'mappings', mappings); cortex = cortexSubscribe(cortex, streams); end @@ -26,9 +28,6 @@ function subscribeAndPlot() if ismember('eeg', cortex.streams) figs.eeg = figure('Name', 'Live EEG', 'NumberTitle', 'off'); end - if ismember('mot', cortex.streams) - figs.mot = figure('Name', 'Live Motion (IMU)', 'NumberTitle', 'off'); - end if ismember('met', cortex.streams) figs.met = figure('Name', 'Live Performance Metrics', 'NumberTitle', 'off'); end @@ -42,13 +41,6 @@ function subscribeAndPlot() end end - if isfield(figs, 'mot') && ishandle(figs.mot) - [labels, data, time] = cortexGetData(cortex, 'mot', 160); - if ~isempty(data) - plotMotion(figs.mot, labels, data, time); - end - end - if isfield(figs, 'met') && ishandle(figs.met) [labels, data, time] = cortexGetData(cortex, 'met', 60); if ~isempty(data) @@ -89,6 +81,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); @@ -107,54 +102,6 @@ function plotEeg(fig, labels, data, time) ylabel('Channel'); end -function plotMotion(fig, labels, data, time) -% plotMotion Plot 9-axis IMU motion stream: -% - Quaternions (Q0..Q3): [-1, 1] (or Gyroscope GYROX..GYROZ: [-100, 100] dps) -% - Accelerometer (ACCX..ACCZ): [-4, 4] g -% - Magnetometer (MAGX..MAGZ): [-4900, 4900] uT -figure(fig); -t = time - time(end); - -quatCols = find(ismember(labels, {'Q0', 'Q1', 'Q2', 'Q3'})); -gyroCols = find(ismember(labels, {'GYROX', 'GYROY', 'GYROZ'})); -accCols = find(ismember(labels, {'ACCX', 'ACCY', 'ACCZ'})); -magCols = find(ismember(labels, {'MAGX', 'MAGY', 'MAGZ'})); - -subplot(3, 1, 1); -if ~isempty(quatCols) - plot(t, data(:, quatCols)); - ylim([-1, 1]); - legend(labels(quatCols), 'Location', 'eastoutside'); - title('Quaternions ([-1, 1])'); - ylabel('Quaternion'); -elseif ~isempty(gyroCols) - plot(t, data(:, gyroCols)); - ylim([-100, 100]); - legend(labels(gyroCols), 'Location', 'eastoutside'); - title('Gyroscope ([-100, 100] dps)'); - ylabel('dps'); -end - -subplot(3, 1, 2); -if ~isempty(accCols) - plot(t, data(:, accCols)); - ylim([-4, 4]); - legend(labels(accCols), 'Location', 'eastoutside'); - title('Accelerometer ([-4, 4] g)'); - ylabel('g'); -end - -subplot(3, 1, 3); -if ~isempty(magCols) - plot(t, data(:, magCols)); - ylim([-4900, 4900]); - legend(labels(magCols), 'Location', 'eastoutside'); - title('Magnetometer ([-4900, 4900] uT)'); - ylabel('uT'); - xlabel('Seconds'); -end -end - function plotPm(fig, labels, data, time) % plotPm Plot normalized Performance Metrics (met) in the [0, 1] range. figure(fig); diff --git a/octave/functions/cortexSession.m b/octave/functions/cortexSession.m index 3fb52f6..6cd6dc8 100644 --- a/octave/functions/cortexSession.m +++ b/octave/functions/cortexSession.m @@ -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 @@ -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(); @@ -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 diff --git a/octave/internal/CortexHeadset.m b/octave/internal/CortexHeadset.m index a1d80f7..b504ac9 100644 --- a/octave/internal/CortexHeadset.m +++ b/octave/internal/CortexHeadset.m @@ -27,6 +27,7 @@ parser reconnectHeadsetId = '' reconnectStreams = {} + reconnectMappings = [] reconnectProfileName = '' reconnectProfileWasLoaded = false reconnectPending = false @@ -110,9 +111,10 @@ function stopScan(obj) end end - function [ok, message] = connectToHeadset(obj, headsetId, streams) + function [ok, message] = connectToHeadset(obj, headsetId, streams, mappings) % Connects the headset if needed, creates an active session, and subscribes when streams are provided. if nargin < 3, streams = {}; end + if nargin < 4, mappings = []; end ok = false; message = ''; @@ -123,12 +125,20 @@ function stopScan(obj) return; end + isFlex = ~isempty(strfind(upper(headsetId), 'FLEX')); + if isFlex && isempty(mappings) + mappings = CortexHeadset.flexMapping; + elseif ~isFlex && ~isempty(mappings) + error('CortexHeadset:mappings', 'mappings can only be supplied for an EPOC Flex headset.'); + end + obj.reconnectMappings = mappings; + if ~strcmp(headset.status, 'connected') if ~strcmp(headset.status, 'connecting') fprintf('[CortexHeadset] Connecting to %s...\n', headsetId); params = struct('command', 'connect', 'headset', headsetId); - if ~isempty(strfind(upper(headsetId), 'FLEX')) - params.mappings = CortexHeadset.flexMapping; + if isFlex + params.mappings = mappings; end obj.client.sendRequest('controlDevice', params); end @@ -289,7 +299,8 @@ function reconnectIfAvailable(obj) if isempty(headset), return; end if ~obj.reconnectSessionReady - [ok, message] = obj.connectToHeadset(obj.reconnectHeadsetId, {}); + [ok, message] = obj.connectToHeadset( ... + obj.reconnectHeadsetId, {}, obj.reconnectMappings); if ~ok fprintf('[CortexHeadset] Reconnect attempt failed: %s\n', message); obj.isScanning = true; From ddd3ff19adb92f0277fbc32d57c7b52957bb109c Mon Sep 17 00:00:00 2001 From: KhanhLe Date: Wed, 18 Nov 2026 09:58:42 +0700 Subject: [PATCH 04/10] Update logic --- octave/examples/subscribeAndPlot.m | 62 +++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/octave/examples/subscribeAndPlot.m b/octave/examples/subscribeAndPlot.m index bcc01ce..d9d5e0c 100644 --- a/octave/examples/subscribeAndPlot.m +++ b/octave/examples/subscribeAndPlot.m @@ -1,5 +1,5 @@ function subscribeAndPlot() -% subscribeAndPlot Subscribe to the EEG stream and plot it live. +% subscribeAndPlot Subscribe to EEG, motion (mot), and performance metrics (met) streams and plot live. % 1. Initialization & Configuration: make the SDK functions visible. currentDir = fileparts(mfilename('fullpath')); @@ -9,7 +9,7 @@ function subscribeAndPlot() headsetId = ''; mappings = struct('CMS', 'TP8', 'DRL', 'P6', ... 'RM', 'TP10', 'RN', 'P4', 'RO', 'P8'); -streams = {'eeg'}; +streams = {'eeg', 'mot'}; durationSeconds = 90; % 2. Connection / Authentication, then create a headset session and subscribe to streams. @@ -28,6 +28,9 @@ function subscribeAndPlot() if ismember('eeg', cortex.streams) figs.eeg = figure('Name', 'Live EEG', 'NumberTitle', 'off'); end + if ismember('mot', cortex.streams) + figs.mot = figure('Name', 'Live Motion (IMU)', 'NumberTitle', 'off'); + end if ismember('met', cortex.streams) figs.met = figure('Name', 'Live Performance Metrics', 'NumberTitle', 'off'); end @@ -41,6 +44,13 @@ function subscribeAndPlot() end end + if isfield(figs, 'mot') && ishandle(figs.mot) + [labels, data, time] = cortexGetData(cortex, 'mot', 160); + if ~isempty(data) + plotMotion(figs.mot, labels, data, time); + end + end + if isfield(figs, 'met') && ishandle(figs.met) [labels, data, time] = cortexGetData(cortex, 'met', 60); if ~isempty(data) @@ -102,6 +112,54 @@ function plotEeg(fig, labels, data, time) ylabel('Channel'); end +function plotMotion(fig, labels, data, time) +% plotMotion Plot 9-axis IMU motion stream: +% - Quaternions (Q0..Q3): [-1, 1] (or Gyroscope GYROX..GYROZ: [-100, 100] dps) +% - Accelerometer (ACCX..ACCZ): [-4, 4] g +% - Magnetometer (MAGX..MAGZ): [-4900, 4900] uT +figure(fig); +t = time - time(end); + +quatCols = find(ismember(labels, {'Q0', 'Q1', 'Q2', 'Q3'})); +gyroCols = find(ismember(labels, {'GYROX', 'GYROY', 'GYROZ'})); +accCols = find(ismember(labels, {'ACCX', 'ACCY', 'ACCZ'})); +magCols = find(ismember(labels, {'MAGX', 'MAGY', 'MAGZ'})); + +subplot(3, 1, 1); +if ~isempty(quatCols) + plot(t, data(:, quatCols)); + ylim([-1, 1]); + legend(labels(quatCols), 'Location', 'eastoutside'); + title('Quaternions ([-1, 1])'); + ylabel('Quaternion'); +elseif ~isempty(gyroCols) + plot(t, data(:, gyroCols)); + ylim([-100, 100]); + legend(labels(gyroCols), 'Location', 'eastoutside'); + title('Gyroscope ([-100, 100] dps)'); + ylabel('dps'); +end + +subplot(3, 1, 2); +if ~isempty(accCols) + plot(t, data(:, accCols)); + ylim([-4, 4]); + legend(labels(accCols), 'Location', 'eastoutside'); + title('Accelerometer ([-4, 4] g)'); + ylabel('g'); +end + +subplot(3, 1, 3); +if ~isempty(magCols) + plot(t, data(:, magCols)); + ylim([-4900, 4900]); + legend(labels(magCols), 'Location', 'eastoutside'); + title('Magnetometer ([-4900, 4900] uT)'); + ylabel('uT'); + xlabel('Seconds'); +end +end + function plotPm(fig, labels, data, time) % plotPm Plot normalized Performance Metrics (met) in the [0, 1] range. figure(fig); From cce9dc91aa6cd26d0428917f1685d8822a2b7289 Mon Sep 17 00:00:00 2001 From: KhanhLe Date: Wed, 18 Nov 2026 10:02:34 +0700 Subject: [PATCH 05/10] Update logic --- octave/examples/subscribeAndPlot.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/octave/examples/subscribeAndPlot.m b/octave/examples/subscribeAndPlot.m index d9d5e0c..6321c45 100644 --- a/octave/examples/subscribeAndPlot.m +++ b/octave/examples/subscribeAndPlot.m @@ -9,7 +9,7 @@ function subscribeAndPlot() headsetId = ''; mappings = struct('CMS', 'TP8', 'DRL', 'P6', ... 'RM', 'TP10', 'RN', 'P4', 'RO', 'P8'); -streams = {'eeg', 'mot'}; +streams = {'eeg'}; durationSeconds = 90; % 2. Connection / Authentication, then create a headset session and subscribe to streams. From 86ecabc595860f575f22b5a28e28e9f8cf8a2ad0 Mon Sep 17 00:00:00 2001 From: khanhle1993 Date: Wed, 18 Nov 2026 10:21:03 +0700 Subject: [PATCH 06/10] Update cortexSession logic based on headsetId Refactor cortexSession call to handle headsetId conditions. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- octave/examples/subscribeAndPlot.m | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/octave/examples/subscribeAndPlot.m b/octave/examples/subscribeAndPlot.m index 6321c45..2169f1d 100644 --- a/octave/examples/subscribeAndPlot.m +++ b/octave/examples/subscribeAndPlot.m @@ -17,7 +17,11 @@ function subscribeAndPlot() cortex = cortexConnect(); connectionCleanup = onCleanup(@() cortexDisconnect(cortex)); if cortex.isConnected - cortex = cortexSession(cortex, headsetId, 'mappings', mappings); + if isempty(strfind(upper(headsetId), 'FLEX')) + cortex = cortexSession(cortex, headsetId); + else + cortex = cortexSession(cortex, headsetId, 'mappings', mappings); + end cortex = cortexSubscribe(cortex, streams); end From b7f0a25ad0aa3052586029710b42e46f4a938966 Mon Sep 17 00:00:00 2001 From: khanhle1993 Date: Wed, 18 Nov 2026 10:21:59 +0700 Subject: [PATCH 07/10] Conditionally assign reconnect properties Wrap reconnect properties assignment in a conditional check for reconnectPending. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- octave/internal/CortexHeadset.m | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/octave/internal/CortexHeadset.m b/octave/internal/CortexHeadset.m index b504ac9..aa58632 100644 --- a/octave/internal/CortexHeadset.m +++ b/octave/internal/CortexHeadset.m @@ -253,10 +253,12 @@ function onSessionClosed(obj, warning) return; end - obj.reconnectHeadsetId = obj.context.headsetId; - obj.reconnectStreams = obj.context.subscribedStreams; - obj.reconnectProfileName = obj.context.profileName; - obj.reconnectProfileWasLoaded = obj.context.isProfileLoaded; + if ~obj.reconnectPending + obj.reconnectHeadsetId = obj.context.headsetId; + obj.reconnectStreams = obj.context.subscribedStreams; + obj.reconnectProfileName = obj.context.profileName; + obj.reconnectProfileWasLoaded = obj.context.isProfileLoaded; + end obj.reconnectPending = ~isempty(obj.reconnectHeadsetId); obj.reconnectSessionReady = false; obj.isScanning = obj.reconnectPending; From 9ff61803592df2edbc17ac083e1a9e9701022354 Mon Sep 17 00:00:00 2001 From: khanhle1993 Date: Wed, 18 Nov 2026 10:34:43 +0700 Subject: [PATCH 08/10] Add missing streams handling for reconnection Implement logic to handle missing streams during reconnection. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- octave/internal/CortexHeadset.m | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/octave/internal/CortexHeadset.m b/octave/internal/CortexHeadset.m index aa58632..08a093e 100644 --- a/octave/internal/CortexHeadset.m +++ b/octave/internal/CortexHeadset.m @@ -317,8 +317,21 @@ function reconnectIfAvailable(obj) profile = CortexProfile(obj.client, obj.context); profile.loadOrCreate(obj.reconnectProfileName); end - if ~isempty(obj.reconnectStreams) - obj.subscribe(obj.reconnectStreams); + targetStreams = obj.reconnectStreams; + missingStreams = targetStreams(~ismember(targetStreams, obj.context.subscribedStreams)); + if ~isempty(missingStreams) + try + obj.subscribe(missingStreams); + catch subscribeFailure + obj.reconnectStreams = targetStreams; + obj.isSubscribed = ~isempty(obj.context.subscribedStreams); + rethrow(subscribeFailure); + end + obj.reconnectStreams = targetStreams; + end + obj.isSubscribed = ~isempty(obj.context.subscribedStreams); + if ~all(ismember(targetStreams, obj.context.subscribedStreams)) + error('CortexHeadset:subscribe', 'Not all data streams have been restored.'); end obj.reconnectPending = false; obj.reconnectSessionReady = false; From 17223f78226541cbaf26d113489aadd7541224d2 Mon Sep 17 00:00:00 2001 From: KhanhLe Date: Wed, 18 Nov 2026 11:15:10 +0700 Subject: [PATCH 09/10] Fix copilot issue --- octave/internal/CortexHeadset.m | 51 ++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/octave/internal/CortexHeadset.m b/octave/internal/CortexHeadset.m index 08a093e..f9388bd 100644 --- a/octave/internal/CortexHeadset.m +++ b/octave/internal/CortexHeadset.m @@ -111,10 +111,11 @@ function stopScan(obj) end end - function [ok, message] = connectToHeadset(obj, headsetId, streams, mappings) + function [ok, message] = connectToHeadset(obj, headsetId, streams, mappings, isRecovery) % Connects the headset if needed, creates an active session, and subscribes when streams are provided. if nargin < 3, streams = {}; end if nargin < 4, mappings = []; end + if nargin < 5, isRecovery = false; end ok = false; message = ''; @@ -152,6 +153,9 @@ function stopScan(obj) obj.isScanning = false; obj.createSession(headsetId); + if ~isRecovery + obj.clearRecoveryState(); + end if ~isempty(streams) obj.subscribe(streams); end @@ -171,11 +175,20 @@ function stopScan(obj) obj.reconnectHeadsetId = headsetId; end - function subscribe(obj, streams) + function subscribe(obj, streams, preserveTarget) + if nargin < 3, preserveTarget = false; end if isempty(obj.context.sessionId) error('CortexHeadset:noSession', 'Create a session before subscribing.'); end + if ~preserveTarget + for index = 1:numel(streams) + if ~any(strcmp(obj.reconnectStreams, streams{index})) + obj.reconnectStreams{end + 1} = streams{index}; + end + end + end + params = struct('cortexToken', obj.context.token, 'session', obj.context.sessionId, ... 'streams', {streams}); response = obj.client.sendRequest('subscribe', params); @@ -199,11 +212,10 @@ function subscribe(obj, streams) obj.context.buffer.configure(name, labels); fprintf('[CortexHeadset] Subscribed to %s (%d columns).\n', name, numel(labels)); end - obj.isSubscribed = ~isempty(successes); + obj.isSubscribed = ~isempty(obj.context.subscribedStreams); if ~obj.isSubscribed error('CortexHeadset:subscribe', 'Cortex did not accept any data stream.'); end - obj.reconnectStreams = obj.context.subscribedStreams; end function unsubscribe(obj) @@ -213,6 +225,7 @@ function unsubscribe(obj) obj.isSubscribed = false; obj.parser.reset(); obj.context.subscribedStreams = {}; + obj.reconnectStreams = {}; obj.client.sendRequest('unsubscribe', params); end @@ -302,7 +315,7 @@ function reconnectIfAvailable(obj) if ~obj.reconnectSessionReady [ok, message] = obj.connectToHeadset( ... - obj.reconnectHeadsetId, {}, obj.reconnectMappings); + obj.reconnectHeadsetId, {}, obj.reconnectMappings, true); if ~ok fprintf('[CortexHeadset] Reconnect attempt failed: %s\n', message); obj.isScanning = true; @@ -320,18 +333,18 @@ function reconnectIfAvailable(obj) targetStreams = obj.reconnectStreams; missingStreams = targetStreams(~ismember(targetStreams, obj.context.subscribedStreams)); if ~isempty(missingStreams) - try - obj.subscribe(missingStreams); - catch subscribeFailure - obj.reconnectStreams = targetStreams; - obj.isSubscribed = ~isempty(obj.context.subscribedStreams); - rethrow(subscribeFailure); - end + obj.subscribe(missingStreams, true); + missingStreams = targetStreams(~ismember(targetStreams, obj.context.subscribedStreams)); obj.reconnectStreams = targetStreams; end obj.isSubscribed = ~isempty(obj.context.subscribedStreams); - if ~all(ismember(targetStreams, obj.context.subscribedStreams)) - error('CortexHeadset:subscribe', 'Not all data streams have been restored.'); + if ~isempty(missingStreams) + obj.reconnectStreams = targetStreams; + fprintf('[CortexHeadset] Waiting to restore streams: %s.\n', ... + strjoin(missingStreams, ', ')); + obj.isScanning = true; + obj.lastQueryAt = tic(); + return; end obj.reconnectPending = false; obj.reconnectSessionReady = false; @@ -354,6 +367,16 @@ function storeSample(obj, msg) obj.context.buffer.append(stream, row, time, bciAction); end + function clearRecoveryState(obj) + obj.reconnectStreams = {}; + obj.reconnectProfileName = ''; + obj.reconnectProfileWasLoaded = false; + obj.reconnectPending = false; + obj.reconnectSessionReady = false; + obj.scanFinished = false; + obj.lastQueryAt = []; + end + function storeSystemEvent(obj, values, time) % A sys sample is {detection, event}, for example {'mentalCommand', 'MC_Started'}. names = CortexStreamParser.stringsOf(values); From b72c72646ecdf7108511e16ff615fb3581b78925 Mon Sep 17 00:00:00 2001 From: KhanhLe Date: Wed, 18 Nov 2026 14:21:13 +0700 Subject: [PATCH 10/10] Fix comment issue --- octave/examples/subscribeAndPlot.m | 10 +++++++--- octave/internal/CortexHeadset.m | 7 +++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/octave/examples/subscribeAndPlot.m b/octave/examples/subscribeAndPlot.m index 2169f1d..2f9e2d4 100644 --- a/octave/examples/subscribeAndPlot.m +++ b/octave/examples/subscribeAndPlot.m @@ -5,10 +5,14 @@ function subscribeAndPlot() currentDir = fileparts(mfilename('fullpath')); addpath(fullfile(currentDir, '../functions')); -% Set the EPOC Flex headset id and electrode map. +% Set your headset ID. headsetId = ''; -mappings = struct('CMS', 'TP8', 'DRL', 'P6', ... - 'RM', 'TP10', 'RN', 'P4', 'RO', 'P8'); +% 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; diff --git a/octave/internal/CortexHeadset.m b/octave/internal/CortexHeadset.m index f9388bd..9701ab2 100644 --- a/octave/internal/CortexHeadset.m +++ b/octave/internal/CortexHeadset.m @@ -15,8 +15,11 @@ end properties (Constant, Access = private) - flexMapping = struct('CMS', 'TP8', 'DRL', 'P6', ... - 'RM', 'TP10', 'RN', 'P4', 'RO', 'P8') + flexMapping = 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') end properties (Access = private)