brainaccess.core.eeg_manager#
Connect to a BrainAccess headset, configure it and stream EEG data.
The module provides EEGManager, the low-level interface to one headset.
Classes#
Connects to a BrainAccess headset, configures it and streams data from it. |
Module Contents#
- class brainaccess.core.eeg_manager.EEGManager[source]#
Connects to a BrainAccess headset, configures it and streams data from it.
Typical use:
Initialize the library with
brainaccess.core.init().Create an
EEGManagerand callconnect()with the headset name (seebrainaccess.core.scan()).Configure the stream (
set_channel_enabled(),set_channel_gain(),set_channel_bias_feedback(),set_sample_rate(),set_impedance_mode(),set_output_mode()).Register
set_callback_chunk()and callstart_stream().Call
stop_stream(),disconnect()anddestroy().
The manager can be used as a context manager, which calls
destroy()on exit:with EEGManager() as mgr: mgr.connect("BA HALO 001") ...
Destroy every manager before calling
brainaccess.core.close(). Afterdestroy(), every method raisesBrainAccessException.- Raises:
BrainAccessException – If the library has not been initialized with
brainaccess.core.init(), or the manager could not be created.
Notes
The stream settings (enabled channels, gains, bias feedback, impedance mode and sample rate) take effect at the next stream start and are reset when the stream stops or the headset disconnects, so set them before every stream. The output mode (
set_output_mode()) is the exception: it is not reset.Callbacks run on a library thread. Inside a callback, the methods that talk to the headset (
connect(),disconnect(),start_stream(),stop_stream(),load_config(),start_update(),get_battery_info(),get_full_battery_info(),get_charging_settings(),set_charging_settings()) anddestroy()raiseBrainAccessException. Signal an application thread instead (for example with an event or a queue) and call them from there.A manager is not thread-safe: use it from one thread at a time. Only
set_callback_chunk(),set_callback_battery()andset_callback_disconnect()may be called from any thread. In particular, do not callannotate(),get_annotations()andclear_annotations()at the same time from different threads.- annotate(annotation)[source]#
Adds an annotation to the running stream.
The annotation’s timestamp is a sample number (the value of the
SAMPLE_NUMBERchannel, not seconds) of the sample being recorded at the moment of the call. With headset firmware 3.8.0 and newer it is placed using the headset’s clock. Otherwise (older firmware, impedance mode, or the first half second of a stream) it is estimated from the arrival of the latest data packet and can be slightly early.get_time_sync_info()shows which case applies.Annotations are cleared when the headset disconnects.
- Parameters:
annotation (str) – The annotation text. Must not be empty.
- Raises:
BrainAccessException – If the text is empty, no stream is running, the annotation could not be stored, or the manager has been destroyed.
- Return type:
None
- clear_annotations()[source]#
Removes all annotations.
- Raises:
BrainAccessException – If the manager has been destroyed.
- Return type:
None
- connect(bt_device_name)[source]#
Connects to a BrainAccess headset.
Blocks until the connection is established and the headset is ready.
- Parameters:
bt_device_name (str) – The full advertised name of the headset, for example
"BA HALO 001". It must match exactly, as listed bybrainaccess.core.scan().- Returns:
Always 0; failures raise.
- Return type:
- Raises:
BrainAccessException – If the manager is already connected (call
disconnect()first), no headset with that name is found, the headset is not a supported model, the connection fails, Bluetooth is disabled or unavailable, the manager has been destroyed, or this is called from inside a callback.
- destroy()[source]#
Releases the manager. Safe to call more than once.
Any connection is closed. If a stream is still running, the samples received since the last full chunk are discarded, so call
stop_stream()first. Afterwards every other method raisesBrainAccessException. Destroy all managers before callingbrainaccess.core.close().- Raises:
BrainAccessException – If called from inside a callback.
- Return type:
None
- disconnect()[source]#
Disconnects from the headset, if connected.
A running stream ends first: the samples received since the last full chunk reach the chunk callback before this returns (see
set_callback_chunk()). The disconnect callback is also called for this disconnect, annotations are cleared and the stream settings are reset.- Raises:
BrainAccessException – If the manager has been destroyed or this is called from inside a callback.
- Return type:
None
- get_annotations()[source]#
Returns all annotations collected so far.
Annotations are cleared when the headset disconnects.
- Returns:
A dictionary with two keys:
"annotations": list of annotation strings."timestamps": list of the matching timestamps, as sample numbers (not seconds); seeannotate().
- Return type:
- Raises:
BrainAccessException – If the manager has been destroyed.
- get_battery_info()[source]#
Returns the most recent battery status reported by the headset.
The headset reports changes by itself; use
set_callback_battery()to be notified. If no report has arrived yet, the values can be zero (0 %, no charger), which cannot be told apart from a real reading.- Returns:
Battery level (percent) and charging status.
- Return type:
- Raises:
BrainAccessException – If the headset is not connected, the manager has been destroyed or this is called from inside a callback.
- get_channel_index(channel)[source]#
Returns the position of a channel in the chunk callback’s list.
The chunk callback receives one array per streamed channel; this gives the position of a given channel in that list. Before a stream starts, it reflects the channels that are enabled now (the layout the next stream will use). During a stream, it reflects the running stream.
- Parameters:
channel (int) – Channel ID (see
brainaccess.core.eeg_channel).- Returns:
The index of the channel in the chunk callback’s list.
- Return type:
- Raises:
BrainAccessException – If the channel does not exist, is not enabled, or the manager has been destroyed.
- get_charging_settings()[source]#
Reads the charging settings from the headset.
- Returns:
Whether the headset stays on while charging, and the sleep timeout in minutes.
- Return type:
- Raises:
BrainAccessException – If the headset is not connected, a setting could not be read, the manager has been destroyed or this is called from inside a callback.
- get_device_features()[source]#
Returns the features of the connected headset.
- Returns:
Query object for the accelerometer, gyroscope, bipolar electrodes and electrode count.
- Return type:
- Raises:
BrainAccessException – If the headset is not connected, the information is unavailable or the manager has been destroyed.
- get_device_info()[source]#
Returns static information about the connected headset.
The headset must be connected.
- Returns:
Device model, hardware and firmware versions and other static information. It stays valid after the headset disconnects.
- Return type:
- Raises:
BrainAccessException – If the headset is not connected, the information is unavailable or the manager has been destroyed.
- get_full_battery_info()[source]#
Reads detailed battery diagnostics from the headset.
Intended for debugging; use sparingly, as it performs several Bluetooth reads. A successful return does not guarantee that every field was read: fields that could not be read stay zero.
- Returns:
The diagnostics; see that class for the fields and units.
- Return type:
- Raises:
BrainAccessException – If the headset is not connected, the manager has been destroyed or this is called from inside a callback.
- get_output_mode()[source]#
Returns the output mode of the next stream.
- Returns:
The configured output mode.
- Return type:
- Raises:
BrainAccessException – If the mode cannot be read or the manager has been destroyed.
- get_sample_frequency()[source]#
Returns the sample rate of the stream in Hz.
Before a stream, this is the rate the next stream will use: the rate set with
set_sample_rate(), or 250 Hz if the impedance mode cannot be measured at that rate (seeset_impedance_mode()). During a stream, it is the rate of the running stream.- Returns:
The sample rate in Hz.
- Return type:
- Raises:
BrainAccessException – If the rate cannot be read or the manager has been destroyed.
- get_stream_channel_data_types()[source]#
Returns the NumPy data types of the streamed channels.
The tuple is in the same order as the arrays passed to the chunk callback; use
get_channel_index()to find a channel in it. A stream must be running.- Returns:
One data type per streamed channel.
- Return type:
tuple of numpy.dtype
- Raises:
BrainAccessException – If no stream is running or the manager has been destroyed.
- get_time_sync_info()[source]#
Reads the state of the clock synchronization used to place annotations.
A diagnostic; it is not needed to use
annotate(). It shows whether annotations are placed using the headset’s clock (valid) or estimated from packet arrival. It works whether connected or not; all values are zero orFalsebefore the first stream.- Returns:
The synchronization state.
- Return type:
- Raises:
BrainAccessException – If the state cannot be read or the manager has been destroyed.
- is_connected()[source]#
Checks whether a headset is connected.
- Returns:
Trueif connected,Falseotherwise.- Return type:
- Raises:
BrainAccessException – If the manager has been destroyed.
- is_streaming()[source]#
Checks whether the headset is streaming.
- Returns:
Trueif a stream is running,Falseotherwise.- Return type:
- Raises:
BrainAccessException – If the manager has been destroyed.
- load_config(callback=None)[source]#
Sends the current stream settings to the headset.
Calling this is optional:
start_stream()sends any changed settings itself. Call it only while no stream is running. A configuration the headset rejects is not applied; the headset keeps the one it had.- Parameters:
callback (callable, optional) – Called without arguments once the headset has accepted the configuration, before this method returns. Not called if it is rejected.
- Raises:
BrainAccessException – If the headset is not connected, the write fails or the headset rejects the configuration (firmware 3.7.0 and newer report a rejection; older firmware is assumed to accept). Also raised if the manager has been destroyed or this is called from inside a callback.
- Return type:
None
- set_callback_battery(callback=None)[source]#
Sets the function called when the battery status changes.
The callback is called as
callback(battery_info)with aBatteryInfo. It runs on a library thread, so synchronize access to shared data and return quickly. It can be set before connecting.May be called from any thread. Once it returns, the replaced callback is no longer running and will not be called again (unless this is called from inside that callback). Do not call it while holding a lock the callback takes.
- Parameters:
callback (callable, optional) – The function to call, or
Noneto remove the callback.- Raises:
BrainAccessException – If the manager has been destroyed.
- Return type:
None
- set_callback_chunk(callback=None)[source]#
Sets the function that receives the streamed data chunks.
The callback is called as
callback(data, chunk_size):datais a list of NumPy arrays withchunk_sizevalues each, one per streamed channel. Find a channel withget_channel_index()and its dtype withget_stream_channel_data_types(). The arrays are copies that you may keep. EEG values are in µV (kOhm in an impedance mode).chunk_sizeis the configured chunk size (25 by default, seebrainaccess.core.config_set_chunk_size()), except for the last call of a stream, which carries the remaining shorter chunk, and in an impedance mode, where each packet is passed on as it arrives.
The callback runs on a library thread, so synchronize access to shared data and return quickly. The last call of a stream runs inside
stop_stream()ordisconnect()(or on the library thread after an unexpected disconnect). Do not call those while holding a lock the callback takes.May be called from any thread, also during a stream. Once it returns, the replaced callback is no longer running and will not be called again (unless this is called from inside that callback, which then runs to its end). Do not call it while holding a lock the callback takes.
- Parameters:
callback (callable, optional) – The function to call for each chunk, or
Noneto remove the callback. Stop the stream beforedestroy(), which discards samples not yet passed to the callback.- Raises:
BrainAccessException – If the manager has been destroyed.
- Return type:
None
- set_callback_disconnect(callback=None)[source]#
Sets the function called when the headset disconnects.
The callback is called without arguments, on a library thread, when the connection ends for any reason:
disconnect(), or the headset going out of range or switching off. Return quickly. It can be set before connecting.May be called from any thread. Once it returns, the replaced callback is no longer running and will not be called again (unless this is called from inside that callback). Do not call it while holding a lock the callback takes.
- Parameters:
callback (callable, optional) – The function to call, or
Noneto remove the callback.- Raises:
BrainAccessException – If the manager has been destroyed.
- Return type:
None
- set_channel_bias_feedback(channel)[source]#
Uses an electrode as a bias feedback electrode.
The signals of the selected electrodes are inverted and fed back to the body to reduce common-mode noise, such as power-line interference. Select electrodes with good skin contact. A bias electrode is also recommended for impedance measurements (see
set_impedance_mode()).Takes effect at the next stream start. The selection is cleared when the stream stops or the headset disconnects, so select the electrodes before every stream. An electrode cannot be deselected individually.
- Parameters:
channel (int) – Channel ID of the electrode:
ELECTRODE_MEASUREMENTplus the 0-based electrode index (seebrainaccess.core.eeg_channel).- Raises:
BrainAccessException – If a stream is running, the headset is not connected, the channel is not an electrode channel of the connected headset, or the manager has been destroyed.
- Return type:
None
- set_channel_enabled(channel, state)[source]#
Enables or disables a data channel of the stream.
Takes effect at the next stream start and is reset when the stream stops or the headset disconnects: electrode measurement channels are enabled again and all other channels disabled. Set the channels before every stream.
A stream with every electrode disabled is valid. It still carries the motion sensor data of headsets that have one, the sample number and, if enabled, the digital input.
Enabling only an electrode’s
ELECTRODE_CONTACTchannel also makes the headset measure that electrode, because contact can only be detected on a measured electrode. This uses as much bandwidth as a measured electrode, and in an impedance mode the electrode is part of every measurement sweep, but its readings are not included in the chunks. To leave an electrode out, disable both itsELECTRODE_MEASUREMENTandELECTRODE_CONTACTchannels.- Parameters:
channel (int) – Channel ID, one of the constants in
brainaccess.core.eeg_channel(for exampleELECTRODE_MEASUREMENT + 2).state (bool) –
Trueto enable the channel,Falseto disable it.
- Raises:
BrainAccessException – If a stream is running or the manager has been destroyed.
- Return type:
None
- set_channel_gain(channel, gain)[source]#
Sets the gain of an electrode channel.
A higher gain gives finer resolution over a smaller input range; a lower gain measures a larger range at coarser resolution. The default is
X8. The returned data is already scaled for the gain.Takes effect at the next stream start and is reset to the default when the stream stops or the headset disconnects, so set the gains before every stream.
- Parameters:
channel (int) – Channel ID of the electrode:
ELECTRODE_MEASUREMENTplus the 0-based electrode index (seebrainaccess.core.eeg_channel).gain (
GainMode) – The gain to use.
- Raises:
BrainAccessException – If a stream is running, the headset is not connected, the channel is not an electrode channel of the connected headset, or the manager has been destroyed.
- Return type:
None
- set_charging_settings(settings)[source]#
Writes the charging settings to the headset.
The settings revert to their defaults when the headset powers off. A
sleep_timeoutof 0 is treated as 1 minute.Warning
Staying on while charging is for development only, not for normal use. Never record from a person while the headset is connected to a charger. The setting must be enabled before the charger is plugged in; otherwise the headset disconnects when charging starts. It is off by default.
Notes
The timeout and the stay-on flag are written separately, timeout first. If this returns
False, it is not known which of them were applied; read them back withget_charging_settings().- Parameters:
settings (
ChargingSettings) – The settings to apply, for exampleChargingSettings(False, 15).- Returns:
Trueif the settings were written to the headset.- Return type:
- Raises:
BrainAccessException – If the headset is not connected, the manager has been destroyed or this is called from inside a callback.
- set_impedance_mode(mode)[source]#
Sets the impedance measurement mode of the next stream.
In an impedance mode the electrode channels carry electrode impedance in kOhm, computed on the headset, instead of voltage in µV. Bias feedback selection is not affected; select a bias electrode (see
set_channel_bias_feedback()) for a reliable measurement.The stream carries one sample per estimate: the headset measures the active electrodes one at a time, 25 ADC samples each, and the sample number counts those ADC samples, so it advances by a whole sweep between samples. The chunk callback is called for every packet, with at most the configured chunk size of samples, and once more with the rest when the stream ends.
The headset cannot measure a fixed-frequency mode at a high sample rate, so
HZ_7_8always streams at 250 Hz,HZ_31_2streams at 250 Hz if the sample rate is above 1000 Hz, andDR_DIV4streams at the sample rate. The sample rate you set is kept: switching the mode back toOFFbefore the stream starts restores it.get_sample_frequency()reports the rate that will be streamed.Takes effect at the next stream start and is reset to
OFFwhen the stream stops or the headset disconnects.- Parameters:
mode (
ImpedanceMeasurementMode) – The impedance measurement mode.- Raises:
BrainAccessException – If a stream is running or the manager has been destroyed.
- Return type:
None
- set_output_mode(mode)[source]#
Selects the output mode of the next stream.
SQUARE_WAVEreplaces the electrode data with a test signal generated by the headset, for checking the signal chain.NORMALstreams real measurements.Takes effect at the next stream start. Unlike every other stream setting, the output mode is not reset when the stream stops or the headset disconnects; it stays until you change it.
- Parameters:
mode (
OutputMode) – The output mode.- Returns:
Trueif the mode was accepted.- Return type:
- Raises:
BrainAccessException – If the mode is rejected or the manager has been destroyed.
- set_sample_rate(sample_rate)[source]#
Sets the sample rate of the next stream.
Supported rates depend on the headset model. All models support 250 and 500 Hz; HALO V3 also supports 1000 Hz; EXG8 also supports 1000 and 2000 Hz. See
StreamRatefor the known rates.Takes effect at the next stream start and is reset to 250 Hz when the stream stops or the headset disconnects, so set it before every stream. An impedance mode can stream at 250 Hz instead (see
set_impedance_mode()).- Parameters:
sample_rate (int) – The sample rate in Hz.
- Returns:
Always
True; failures raise.- Return type:
- Raises:
BrainAccessException – If a stream is running, the rate is not a known rate, the connected headset does not support it, the headset is not connected, or the manager has been destroyed.
- start_stream(callback=None)[source]#
Starts streaming with the current configuration.
Settings changed since the last
load_config()are sent to the headset first. Blocks until the stream has started. Register the chunk callback withset_callback_chunk()before starting.- Parameters:
callback (callable, optional) – Called without arguments once the stream has started.
- Returns:
Always
True; failures raise.- Return type:
- Raises:
BrainAccessException – If the headset is not connected, a stream is already running, the headset rejects the configuration (it keeps its previous one and does not stream), or it cannot start the stream (reported by firmware 3.7.0 and newer). After a failure the headset stays connected and not streaming, so the start can be retried. Also raised if the manager has been destroyed or this is called from inside a callback.
- start_update(callback=None)[source]#
Sends a firmware image to the headset.
The image file is set with
brainaccess.core.set_config_update_path(). Blocks until the headset has received the whole image and reported whether it accepts it (at most 10 seconds after the last packet). On success the headset installs the image, restarts and disconnects, so connect again afterwards. Firmware that predates result reporting only confirms the transfer, which is taken as acceptance.- Parameters:
callback (callable, optional) – Called without arguments, before this method returns, only if the headset accepted the image.
- Raises:
BrainAccessException – If the headset is not connected, the image file is missing, the transfer fails, the headset disconnects or reports no result within 10 seconds, or it rejects the image (it then keeps its current firmware). Also raised if the manager has been destroyed or this is called from inside a callback.
callbackis not called in these cases.- Return type:
None
- stop_stream(callback=None)[source]#
Stops the stream.
If the headset is not connected or no stream is running, nothing happens and
Falseis returned. Otherwise the samples received since the last full chunk reach the chunk callback in one last, shorter call before this returns, withis_streaming()alreadyFalse(seeset_callback_chunk()).- Parameters:
callback (callable, optional) – Called without arguments once the stream has stopped.
- Returns:
Trueif the stream was stopped,Falseif there was nothing to stop.- Return type:
- Raises:
BrainAccessException – If the stream could not be stopped, the manager has been destroyed or this is called from inside a callback.