"""Connect to a BrainAccess headset, configure it and stream EEG data.
The module provides :class:`EEGManager`, the low-level interface to one headset.
"""
import ctypes
import threading
import numpy as np
import copy
from functools import wraps
from typing import Callable, Union, Optional
from brainaccess.utils.exceptions import (
_callback,
_handle_error,
_Error,
BrainAccessException,
)
from brainaccess.core import _dll
import brainaccess.core as _core
from brainaccess.core.battery_info import BatteryInfo
from brainaccess.core.full_battery_info import FullBatteryInfo
from brainaccess.core.device_info import DeviceInfo
from brainaccess.core.gain_mode import GainMode
from brainaccess.core.stream_rate import StreamRate
from brainaccess.core.annotation import Annotation
from brainaccess.core.impedance_measurement_mode import ImpedanceMeasurementMode # noqa
from brainaccess.core import eeg_channel
from brainaccess.core.device_features import DeviceFeatures
from brainaccess.core.charging_settings import ChargingSettings
from brainaccess.core.time_sync_info import TimeSyncInfo
from brainaccess.core.output_mode import OutputMode
# ctypes
# new_eeg_manager
_dll.ba_eeg_manager_new.argtypes = []
_dll.ba_eeg_manager_new.restype = ctypes.c_void_p
# destructor
_dll.ba_eeg_manager_free.argtypes = [ctypes.c_void_p]
_dll.ba_eeg_manager_free.restype = None
# connect(device_name)
_dll.ba_eeg_manager_connect.argtypes = [
ctypes.c_void_p,
ctypes.c_char_p,
ctypes.CFUNCTYPE(None, ctypes.c_bool, ctypes.c_void_p),
ctypes.c_void_p,
]
_dll.ba_eeg_manager_connect.restype = ctypes.c_uint8
# is_connected()
_dll.ba_eeg_manager_is_connected.argtypes = [ctypes.c_void_p]
_dll.ba_eeg_manager_is_connected.restype = ctypes.c_bool
# disconnect()
_dll.ba_eeg_manager_disconnect.argtypes = [ctypes.c_void_p]
_dll.ba_eeg_manager_disconnect.restype = None
# start_stream()
_dll.ba_eeg_manager_start_stream.argtypes = [
ctypes.c_void_p,
ctypes.CFUNCTYPE(None, ctypes.c_void_p),
ctypes.c_void_p,
]
_dll.ba_eeg_manager_start_stream.restype = ctypes.c_uint8
# stop_stream()
_dll.ba_eeg_manager_stop_stream.argtypes = [
ctypes.c_void_p,
ctypes.CFUNCTYPE(None, ctypes.c_void_p),
ctypes.c_void_p,
]
_dll.ba_eeg_manager_stop_stream.restype = ctypes.c_uint8
# is_streaming()
_dll.ba_eeg_manager_is_streaming.argtypes = [ctypes.c_void_p]
_dll.ba_eeg_manager_is_streaming.restype = ctypes.c_bool
# load_config()
_dll.ba_eeg_manager_load_config.argtypes = [
ctypes.c_void_p,
ctypes.CFUNCTYPE(None, ctypes.c_void_p),
ctypes.c_void_p,
]
_dll.ba_eeg_manager_load_config.restype = ctypes.c_uint8
# read_charging_settings()
_dll.ba_eeg_manager_read_charging_settings.argtypes = [
ctypes.c_void_p, ctypes.POINTER(ChargingSettings)
]
_dll.ba_eeg_manager_read_charging_settings.restype = ctypes.c_uint8
# set_charging_settings()
_dll.ba_eeg_manager_set_charging_settings.argtypes = [ctypes.c_void_p, ChargingSettings]
_dll.ba_eeg_manager_set_charging_settings.restype = ctypes.c_bool
# set_output_mode()
_dll.ba_eeg_manager_set_output_mode.argtypes = [ctypes.c_void_p, ctypes.c_uint8]
_dll.ba_eeg_manager_set_output_mode.restype = ctypes.c_uint8
# read_output_mode()
_dll.ba_eeg_manager_read_output_mode.argtypes = [
ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint8)
]
_dll.ba_eeg_manager_read_output_mode.restype = ctypes.c_uint8
# read_battery_info()
_dll.ba_eeg_manager_read_battery_info.argtypes = [
ctypes.c_void_p, ctypes.POINTER(BatteryInfo)
]
_dll.ba_eeg_manager_read_battery_info.restype = ctypes.c_uint8
# read_full_battery_info()
_dll.ba_eeg_manager_read_full_battery_info.argtypes = [
ctypes.c_void_p, ctypes.POINTER(FullBatteryInfo)
]
_dll.ba_eeg_manager_read_full_battery_info.restype = ctypes.c_uint8
# set_channel_enabled()
_dll.ba_eeg_manager_set_channel_enabled.argtypes = [
ctypes.c_void_p,
ctypes.c_uint16,
ctypes.c_bool,
]
_dll.ba_eeg_manager_set_channel_enabled.restype = None
# set_channel_gain()
_dll.ba_eeg_manager_set_channel_gain.argtypes = [
ctypes.c_void_p,
ctypes.c_uint16,
ctypes.c_uint8,
]
_dll.ba_eeg_manager_set_channel_gain.restype = None
# set_channel_bias_feedback()
_dll.ba_eeg_manager_set_channel_bias_feedback.argtypes = [
ctypes.c_void_p,
ctypes.c_uint16,
]
_dll.ba_eeg_manager_set_channel_bias_feedback.restype = None
# set_impedance_mode()
_dll.ba_eeg_manager_set_impedance_mode.argtypes = [
ctypes.c_void_p,
ctypes.c_uint8,
]
_dll.ba_eeg_manager_set_impedance_mode.restype = None
# get_device_info()
_dll.ba_eeg_manager_get_device_info.argtypes = [ctypes.c_void_p]
_dll.ba_eeg_manager_get_device_info.restype = ctypes.POINTER(DeviceInfo)
# get_channel_index()
_dll.ba_eeg_manager_get_channel_index.argtypes = [ctypes.c_void_p, ctypes.c_uint16]
_dll.ba_eeg_manager_get_channel_index.restype = ctypes.c_size_t
# read_sample_frequency()
_dll.ba_eeg_manager_read_sample_frequency.argtypes = [
ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint8)
]
_dll.ba_eeg_manager_read_sample_frequency.restype = ctypes.c_uint8
# set_callback_chunk()
_dll.ba_eeg_manager_set_callback_chunk.argtypes = [
ctypes.c_void_p,
ctypes.CFUNCTYPE(
None,
ctypes.POINTER(ctypes.c_void_p),
ctypes.c_size_t,
ctypes.c_void_p,
),
ctypes.c_void_p,
]
_dll.ba_eeg_manager_set_callback_chunk.restype = None
# set_callback_battery()
_dll.ba_eeg_manager_set_callback_battery.argtypes = [
ctypes.c_void_p,
ctypes.CFUNCTYPE(None, ctypes.POINTER(BatteryInfo), ctypes.c_void_p),
ctypes.c_void_p,
]
_dll.ba_eeg_manager_set_callback_battery.restype = None
# set_callback_disconnect()
_dll.ba_eeg_manager_set_callback_disconnect.argtypes = [
ctypes.c_void_p,
ctypes.CFUNCTYPE(None, ctypes.c_void_p),
ctypes.c_void_p,
]
_dll.ba_eeg_manager_set_callback_disconnect.restype = None
# update firmware
_dll.ba_eeg_manager_start_update.argtypes = [
ctypes.c_void_p,
ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t),
ctypes.c_void_p,
]
_dll.ba_eeg_manager_start_update.restype = ctypes.c_uint8
# annotate()
_dll.ba_eeg_manager_annotate.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
_dll.ba_eeg_manager_annotate.restype = ctypes.c_uint8
# get_time_sync_info()
_dll.ba_eeg_manager_get_time_sync_info.argtypes = [
ctypes.c_void_p, ctypes.POINTER(TimeSyncInfo)
]
_dll.ba_eeg_manager_get_time_sync_info.restype = ctypes.c_uint8
# get_annotations()
_dll.ba_eeg_manager_get_annotations.argtypes = [
ctypes.c_void_p,
ctypes.POINTER(ctypes.POINTER(Annotation)),
ctypes.POINTER(ctypes.c_size_t),
]
_dll.ba_eeg_manager_get_annotations.restype = None
# clear_annotations()
_dll.ba_eeg_manager_clear_annotations.argtypes = [ctypes.c_void_p]
_dll.ba_eeg_manager_clear_annotations.restype = None
# Stream channel metadata, also used when copying native chunks.
_dll.ba_eeg_manager_get_stream_channel_data_types.argtypes = [
ctypes.c_void_p,
ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8)),
ctypes.POINTER(ctypes.c_size_t),
]
_dll.ba_eeg_manager_get_stream_channel_data_types.restype = None
# Set sample rate
_dll.ba_eeg_manager_set_data_stream_rate.argtypes = [
ctypes.c_void_p,
ctypes.c_uint8,
]
_dll.ba_eeg_manager_set_data_stream_rate.restype = ctypes.c_uint8
_managers_mtx = threading.Lock()
_managers: dict = dict()
_callback_state = threading.local()
# The core's WRONG_VALUE from load_config/start_stream, once a running stream is ruled out: the
# device rejected the settings (or the core refused ones it would reject); nothing changed there.
_CONFIG_REJECTED = (
"Device rejected the configuration; it keeps its previous one and did not apply these settings"
)
def _manager_call(method):
"""Keep the native handle alive without holding a lock across native calls."""
device_io = method.__name__ in {
"get_battery_info", "get_full_battery_info",
"get_charging_settings", "set_charging_settings",
}
@wraps(method)
def guarded(self, *args, **kwargs):
if device_io:
_reject_callback_operation()
with self._lifecycle:
if self._closing or self._manager is None:
raise BrainAccessException("EEG manager is closed")
self._active_calls += 1
try:
return method(self, *args, **kwargs)
finally:
with self._lifecycle:
self._active_calls -= 1
self._lifecycle.notify_all()
return guarded
def _reject_callback_operation() -> None:
if getattr(_callback_state, "depth", 0):
raise BrainAccessException(
"Schedule connection, streaming and teardown operations outside callbacks"
)
def _dispatch_callback(data, name, args=(), prepare=None) -> None:
with _managers_mtx:
mgr = _managers.get(data)
if mgr is None:
return
with mgr._lifecycle:
if mgr._closing or mgr._manager is None:
return
mgr._active_calls += 1
depth = getattr(_callback_state, "depth", 0)
_callback_state.depth = depth + 1
try:
with getattr(mgr, name + "_mtx"):
callback = getattr(mgr, name, None)
if callback is not None:
if prepare is not None:
args = prepare(mgr, *args)
callback(*args)
finally:
_callback_state.depth = depth
with mgr._lifecycle:
mgr._active_calls -= 1
mgr._lifecycle.notify_all()
_types_map = [
ctypes.c_float, # 0
ctypes.c_uint8, # 1
ctypes.c_size_t, # 2
ctypes.c_double, # 3
]
@ctypes.CFUNCTYPE(None, ctypes.c_void_p)
def _callback_stop_stream(data: ctypes.c_void_p) -> None:
_dispatch_callback(data, "_callback_stop_stream")
@ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t)
def _callback_ota_update(data: ctypes.c_void_p, progress: int, total: int) -> None:
_dispatch_callback(data, "_callback_ota_update", (progress, total))
@ctypes.CFUNCTYPE(None, ctypes.c_void_p)
def _callback_start_stream(data: ctypes.c_void_p) -> None:
_dispatch_callback(data, "_callback_start_stream")
def _copy_chunk(mgr, chunk_data, chunk_size):
# Native channel layout is fixed for each stream.
types = mgr._stream_channel_types
if types is None:
types_ptr = ctypes.POINTER(ctypes.c_uint8)()
types_size = ctypes.c_size_t()
_dll.ba_eeg_manager_get_stream_channel_data_types(
mgr._manager, ctypes.byref(types_ptr), ctypes.byref(types_size)
)
types = [_types_map[types_ptr[i]] for i in range(types_size.value)]
mgr._stream_channel_types = types
arrays = []
for i, ctype in enumerate(types):
pointer = ctypes.cast(chunk_data[i], ctypes.POINTER(ctype * chunk_size))
# Native buffers are freed when this callback returns.
arrays.append(np.ctypeslib.as_array(pointer.contents).copy())
return arrays, chunk_size
@ctypes.CFUNCTYPE(
None, ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t, ctypes.c_void_p
)
def _callback_chunk(chunk_data, chunk_size: int, data: Optional[int]) -> None:
_dispatch_callback(data, "_callback_chunk", (chunk_data, chunk_size), _copy_chunk)
@ctypes.CFUNCTYPE(None, ctypes.POINTER(BatteryInfo), ctypes.c_void_p)
def _callback_battery(b_info, data) -> None:
_dispatch_callback(data, "_callback_battery", (copy.copy(b_info[0]),))
@ctypes.CFUNCTYPE(None, ctypes.c_void_p)
def _callback_load_config(data) -> None:
_dispatch_callback(data, "_callback_load_config")
@ctypes.CFUNCTYPE(None, ctypes.c_void_p)
def _callback_disconnect(data) -> None:
_dispatch_callback(data, "_callback_disconnect")
# ctypes rejects Python None for a CFUNCTYPE-typed argument; a typed NULL
# function pointer unregisters the native callback.
_NULL_CHUNK_CALLBACK = type(_callback_chunk)(0)
_NULL_BATTERY_CALLBACK = type(_callback_battery)(0)
[docs]
class EEGManager:
"""Connects to a BrainAccess headset, configures it and streams data from it.
Typical use:
1. Initialize the library with :func:`brainaccess.core.init`.
2. Create an :class:`EEGManager` and call :meth:`connect` with the headset name
(see :func:`brainaccess.core.scan`).
3. Configure the stream (:meth:`set_channel_enabled`, :meth:`set_channel_gain`,
:meth:`set_channel_bias_feedback`, :meth:`set_sample_rate`,
:meth:`set_impedance_mode`, :meth:`set_output_mode`).
4. Register :meth:`set_callback_chunk` and call :meth:`start_stream`.
5. Call :meth:`stop_stream`, :meth:`disconnect` and :meth:`destroy`.
The manager can be used as a context manager, which calls :meth:`destroy` on
exit::
with EEGManager() as mgr:
mgr.connect("BA HALO 001")
...
Destroy every manager before calling :func:`brainaccess.core.close`. After
:meth:`destroy`, every method raises ``BrainAccessException``.
Raises
------
BrainAccessException
If the library has not been initialized with
:func:`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 (:meth:`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 (:meth:`connect`, :meth:`disconnect`, :meth:`start_stream`,
:meth:`stop_stream`, :meth:`load_config`, :meth:`start_update`,
:meth:`get_battery_info`, :meth:`get_full_battery_info`,
:meth:`get_charging_settings`, :meth:`set_charging_settings`) and
:meth:`destroy` raise ``BrainAccessException``. 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
:meth:`set_callback_chunk`, :meth:`set_callback_battery` and
:meth:`set_callback_disconnect` may be called from any thread. In particular,
do not call :meth:`annotate`, :meth:`get_annotations` and
:meth:`clear_annotations` at the same time from different threads.
"""
def __init__(self) -> None:
"""Creates a new EEG manager; see the class description."""
self._lifecycle = threading.Condition()
self._active_calls = 0
self._closing = False
self._stream_channel_types: Optional[list] = None
self._callback_chunk_mtx = threading.Lock()
self._callback_battery_mtx = threading.Lock()
self._callback_disconnect_mtx = threading.Lock()
self._callback_start_stream_mtx = threading.Lock()
self._callback_stop_stream_mtx = threading.Lock()
self._callback_load_config_mtx = threading.Lock()
self._callback_ota_update_mtx = threading.Lock()
with _core._lifecycle_lock:
_core._get_config() # Reject construction before core initialization.
self._manager = _dll.ba_eeg_manager_new()
if self._manager is None:
raise BrainAccessException("Could not allocate EEG manager")
_core._live_managers.add(self._manager)
with _managers_mtx:
_managers[self._manager] = self
self._callback_disconnect = lambda: None
_dll.ba_eeg_manager_set_callback_disconnect(
self._manager, _callback_disconnect, self._manager
)
@_manager_call
def __enter__(self) -> "EEGManager":
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
self.destroy()
[docs]
def destroy(self) -> None:
"""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
:meth:`stop_stream` first. Afterwards every other method raises
``BrainAccessException``. Destroy all managers before calling
:func:`brainaccess.core.close`.
Raises
------
BrainAccessException
If called from inside a callback.
"""
_reject_callback_operation()
with self._lifecycle:
while self._closing:
self._lifecycle.wait()
if self._manager is None:
return
self._closing = True
handle = self._manager
with _managers_mtx:
_managers.pop(handle, None)
with self._lifecycle:
while self._active_calls:
self._lifecycle.wait()
try:
# No Python mutex is held while native teardown quiesces callbacks.
_dll.ba_eeg_manager_free(handle)
finally:
with _core._lifecycle_lock:
_core._live_managers.discard(handle)
with self._lifecycle:
self._manager = None
self._closing = False
self._lifecycle.notify_all()
@_manager_call
[docs]
def disconnect(self) -> None:
"""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
:meth:`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.
"""
_reject_callback_operation()
_dll.ba_eeg_manager_disconnect(self._manager)
@_manager_call
[docs]
def connect(self, bt_device_name: str) -> int:
"""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 by
:func:`brainaccess.core.scan`.
Returns
-------
int
Always 0; failures raise.
Raises
------
BrainAccessException
If the manager is already connected (call :meth:`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.
"""
_reject_callback_operation()
if self.is_connected():
raise BrainAccessException("Already connected; disconnect first")
cbk, _ = _callback()
code = _dll.ba_eeg_manager_connect(
self._manager, ctypes.c_char_p(bt_device_name.encode("utf-8")), cbk, None
)
_handle_error(code)
return code
@_manager_call
[docs]
def is_connected(self) -> bool:
"""Checks whether a headset is connected.
Returns
-------
bool
``True`` if connected, ``False`` otherwise.
Raises
------
BrainAccessException
If the manager has been destroyed.
"""
return _dll.ba_eeg_manager_is_connected(self._manager)
@_manager_call
[docs]
def start_stream(self, callback: Union[Callable, None] = None) -> bool:
"""Starts streaming with the current configuration.
Settings changed since the last :meth:`load_config` are sent to the
headset first. Blocks until the stream has started. Register the chunk
callback with :meth:`set_callback_chunk` before starting.
Parameters
----------
callback : callable, optional
Called without arguments once the stream has started.
Returns
-------
bool
Always ``True``; failures raise.
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.
"""
_reject_callback_operation()
if self.is_streaming():
raise BrainAccessException("Stream already running")
# New stream: channel types are re-fetched on the first chunk.
self._stream_channel_types = None
if callback is not None:
with self._callback_start_stream_mtx:
self._callback_start_stream = callback
else:
with self._callback_start_stream_mtx:
self._callback_start_stream = lambda: None
code = _dll.ba_eeg_manager_start_stream(
self._manager, _callback_start_stream, self._manager
)
if code == _Error.WRONG_VALUE.value:
raise BrainAccessException(_CONFIG_REJECTED)
return _handle_error(code)
@_manager_call
[docs]
def stop_stream(self, callback: Union[Callable, None] = None) -> bool:
"""Stops the stream.
If the headset is not connected or no stream is running, nothing happens
and ``False`` is returned. Otherwise the samples received since the last
full chunk reach the chunk callback in one last, shorter call before this
returns, with :meth:`is_streaming` already ``False`` (see
:meth:`set_callback_chunk`).
Parameters
----------
callback : callable, optional
Called without arguments once the stream has stopped.
Returns
-------
bool
``True`` if the stream was stopped, ``False`` if there was nothing to
stop.
Raises
------
BrainAccessException
If the stream could not be stopped, the manager has been destroyed or
this is called from inside a callback.
"""
_reject_callback_operation()
if not self.is_connected() or not self.is_streaming():
return False
if callback is not None:
with self._callback_stop_stream_mtx:
self._callback_stop_stream = callback
else:
with self._callback_stop_stream_mtx:
self._callback_stop_stream = lambda: None
return _handle_error(
_dll.ba_eeg_manager_stop_stream(self._manager, _callback_stop_stream, self._manager)
)
@_manager_call
[docs]
def is_streaming(self) -> bool:
"""Checks whether the headset is streaming.
Returns
-------
bool
``True`` if a stream is running, ``False`` otherwise.
Raises
------
BrainAccessException
If the manager has been destroyed.
"""
return _dll.ba_eeg_manager_is_streaming(self._manager)
@_manager_call
[docs]
def load_config(self, callback: Union[Callable, None] = None) -> None:
"""Sends the current stream settings to the headset.
Calling this is optional: :meth:`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.
"""
_reject_callback_operation()
if callback is not None:
with self._callback_load_config_mtx:
self._callback_load_config = callback
else:
with self._callback_load_config_mtx:
self._callback_load_config = lambda: None
code = _dll.ba_eeg_manager_load_config(
self._manager, _callback_load_config, self._manager
)
if code == _Error.WRONG_VALUE.value:
raise BrainAccessException(_CONFIG_REJECTED)
_handle_error(code)
@_manager_call
[docs]
def get_battery_info(self) -> BatteryInfo:
"""Returns the most recent battery status reported by the headset.
The headset reports changes by itself; use :meth:`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
-------
:class:`~brainaccess.core.battery_info.BatteryInfo`
Battery level (percent) and charging status.
Raises
------
BrainAccessException
If the headset is not connected, the manager has been destroyed or
this is called from inside a callback.
"""
info = BatteryInfo()
_handle_error(_dll.ba_eeg_manager_read_battery_info(self._manager, ctypes.byref(info)))
return info
@_manager_call
[docs]
def get_full_battery_info(self) -> FullBatteryInfo:
"""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
-------
:class:`~brainaccess.core.full_battery_info.FullBatteryInfo`
The diagnostics; see that class for the fields and units.
Raises
------
BrainAccessException
If the headset is not connected, the manager has been destroyed or
this is called from inside a callback.
"""
info = FullBatteryInfo()
_handle_error(_dll.ba_eeg_manager_read_full_battery_info(self._manager, ctypes.byref(info)))
return info
@_manager_call
[docs]
def set_channel_enabled(self, channel: int, state: bool) -> None:
"""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_CONTACT`` channel 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 its ``ELECTRODE_MEASUREMENT`` and
``ELECTRODE_CONTACT`` channels.
Parameters
----------
channel : int
Channel ID, one of the constants in :mod:`brainaccess.core.eeg_channel`
(for example ``ELECTRODE_MEASUREMENT + 2``).
state : bool
``True`` to enable the channel, ``False`` to disable it.
Raises
------
BrainAccessException
If a stream is running or the manager has been destroyed.
"""
if self.is_streaming():
raise BrainAccessException("Cannot change channel state while streaming")
_dll.ba_eeg_manager_set_channel_enabled(
self._manager, ctypes.c_uint16(channel), ctypes.c_bool(state)
)
def _validate_electrode_channel(self, channel: int) -> None:
"""Raises unless `channel` is an electrode channel of the connected device."""
if not self.is_connected():
raise BrainAccessException("Not connected")
count = DeviceFeatures(self.get_device_info()).electrode_count()
if not (
eeg_channel.ELECTRODE_MEASUREMENT
<= channel
< eeg_channel.ELECTRODE_MEASUREMENT + count
):
raise BrainAccessException(
f"Invalid electrode channel {channel}; device has {count} electrodes"
)
@_manager_call
[docs]
def set_channel_gain(self, channel: int, gain: GainMode) -> None:
"""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
:attr:`~brainaccess.core.gain_mode.GainMode.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_MEASUREMENT`` plus the
0-based electrode index (see :mod:`brainaccess.core.eeg_channel`).
gain : :class:`~brainaccess.core.gain_mode.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.
"""
if self.is_streaming():
raise BrainAccessException("Cannot change channel gain while streaming")
self._validate_electrode_channel(channel)
_dll.ba_eeg_manager_set_channel_gain(
self._manager, ctypes.c_uint16(channel), ctypes.c_uint8(gain.value)
)
@_manager_call
[docs]
def set_channel_bias_feedback(self, channel: int) -> None:
"""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 :meth:`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_MEASUREMENT`` plus the
0-based electrode index (see :mod:`brainaccess.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.
"""
if self.is_streaming():
raise BrainAccessException("Cannot change channel bias while streaming")
self._validate_electrode_channel(channel)
_dll.ba_eeg_manager_set_channel_bias_feedback(self._manager, ctypes.c_uint16(channel))
@_manager_call
[docs]
def set_impedance_mode(self, mode: ImpedanceMeasurementMode) -> None:
"""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
:meth:`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_8`` always streams at 250 Hz, ``HZ_31_2`` streams at 250 Hz if
the sample rate is above 1000 Hz, and ``DR_DIV4`` streams at the sample
rate. The sample rate you set is kept: switching the mode back to ``OFF``
before the stream starts restores it. :meth:`get_sample_frequency`
reports the rate that will be streamed.
Takes effect at the next stream start and is reset to ``OFF`` when the
stream stops or the headset disconnects.
Parameters
----------
mode : :class:`~brainaccess.core.impedance_measurement_mode.ImpedanceMeasurementMode`
The impedance measurement mode.
Raises
------
BrainAccessException
If a stream is running or the manager has been destroyed.
"""
if self.is_streaming():
raise BrainAccessException("Cannot change impedance mode while streaming")
_dll.ba_eeg_manager_set_impedance_mode(
self._manager, ctypes.c_uint8(mode.value)
)
@_manager_call
[docs]
def get_device_info(self) -> DeviceInfo:
"""Returns static information about the connected headset.
The headset must be connected.
Returns
-------
:class:`~brainaccess.core.device_info.DeviceInfo`
Device model, hardware and firmware versions and other static
information. It stays valid after the headset disconnects.
Raises
------
BrainAccessException
If the headset is not connected, the information is unavailable or the
manager has been destroyed.
"""
if not self.is_connected():
raise BrainAccessException("Not connected")
pointer = _dll.ba_eeg_manager_get_device_info(self._manager)
if not pointer:
raise BrainAccessException("Device information is unavailable")
return copy.copy(pointer.contents)
@_manager_call
[docs]
def get_channel_index(self, channel: int) -> int:
"""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 :mod:`brainaccess.core.eeg_channel`).
Returns
-------
int
The index of the channel in the chunk callback's list.
Raises
------
BrainAccessException
If the channel does not exist, is not enabled, or the manager has been
destroyed.
"""
val = _dll.ba_eeg_manager_get_channel_index(
self._manager, ctypes.c_uint16(channel)
)
if val == ctypes.c_size_t(-1).value:
raise BrainAccessException(
"Channel does not exist or is not currently streaming"
)
return val
@_manager_call
[docs]
def get_sample_frequency(self) -> int:
"""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 :meth:`set_sample_rate`, or 250 Hz if the impedance mode cannot be
measured at that rate (see :meth:`set_impedance_mode`). During a stream,
it is the rate of the running stream.
Returns
-------
int
The sample rate in Hz.
Raises
------
BrainAccessException
If the rate cannot be read or the manager has been destroyed.
"""
rate = ctypes.c_uint8()
_handle_error(_dll.ba_eeg_manager_read_sample_frequency(self._manager, ctypes.byref(rate)))
return StreamRate(rate.value).to_hz
@_manager_call
[docs]
def get_stream_channel_data_types(self) -> tuple:
"""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 :meth:`get_channel_index` to find a channel in it. A stream must be
running.
Returns
-------
tuple of numpy.dtype
One data type per streamed channel.
Raises
------
BrainAccessException
If no stream is running or the manager has been destroyed.
"""
if not self.is_streaming():
raise BrainAccessException("No stream is running")
types = ctypes.POINTER(ctypes.c_uint8)()
count = ctypes.c_size_t()
_dll.ba_eeg_manager_get_stream_channel_data_types(
self._manager, ctypes.byref(types), ctypes.byref(count)
)
return tuple(np.dtype(_types_map[types[i]]) for i in range(count.value))
@_manager_call
[docs]
def set_callback_chunk(self, callback: Optional[Callable] = None) -> None:
"""Sets the function that receives the streamed data chunks.
The callback is called as ``callback(data, chunk_size)``:
- ``data`` is a list of NumPy arrays with ``chunk_size`` values each, one
per streamed channel. Find a channel with :meth:`get_channel_index` and
its dtype with :meth:`get_stream_channel_data_types`. The arrays are
copies that you may keep. EEG values are in µV (kOhm in an impedance
mode).
- ``chunk_size`` is the configured chunk size (25 by default, see
:func:`brainaccess.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
:meth:`stop_stream` or :meth:`disconnect` (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 ``None`` to remove the
callback. Stop the stream before :meth:`destroy`, which discards
samples not yet passed to the callback.
Raises
------
BrainAccessException
If the manager has been destroyed.
"""
with self._callback_chunk_mtx:
self._callback_chunk = callback
# Outside the lock: the library waits for a chunk call under way on
# another thread, and that call takes the lock to read the callback.
_dll.ba_eeg_manager_set_callback_chunk(
self._manager,
_callback_chunk if callback is not None else _NULL_CHUNK_CALLBACK,
self._manager,
)
@_manager_call
[docs]
def set_callback_battery(self, callback: Union[Callable, None] = None) -> None:
"""Sets the function called when the battery status changes.
The callback is called as ``callback(battery_info)`` with a
:class:`~brainaccess.core.battery_info.BatteryInfo`. 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 ``None`` to remove the callback.
Raises
------
BrainAccessException
If the manager has been destroyed.
"""
with self._callback_battery_mtx:
self._callback_battery = callback
# Outside the lock, as in set_callback_chunk.
_dll.ba_eeg_manager_set_callback_battery(
self._manager,
_callback_battery if callback is not None else _NULL_BATTERY_CALLBACK,
self._manager,
)
@_manager_call
[docs]
def set_callback_disconnect(self, callback: Optional[Callable] = None) -> None:
"""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: :meth:`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 ``None`` to remove the callback.
Raises
------
BrainAccessException
If the manager has been destroyed.
"""
if callback is None:
with self._callback_disconnect_mtx:
self._callback_disconnect = lambda: None
else:
with self._callback_disconnect_mtx:
self._callback_disconnect = callback
_dll.ba_eeg_manager_set_callback_disconnect(
self._manager, _callback_disconnect, self._manager
)
@_manager_call
[docs]
def annotate(self, annotation: str) -> None:
"""Adds an annotation to the running stream.
The annotation's timestamp is a sample number (the value of the
``SAMPLE_NUMBER`` channel, 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. :meth:`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.
"""
if not annotation:
raise BrainAccessException("Annotation cannot be empty")
if not self.is_streaming():
raise BrainAccessException("Annotations require a running stream")
_handle_error(
_dll.ba_eeg_manager_annotate(
self._manager, ctypes.c_char_p(annotation.encode("utf-8"))
)
)
@_manager_call
[docs]
def get_time_sync_info(self) -> TimeSyncInfo:
"""Reads the state of the clock synchronization used to place annotations.
A diagnostic; it is not needed to use :meth:`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 or ``False`` before the first stream.
Returns
-------
:class:`~brainaccess.core.time_sync_info.TimeSyncInfo`
The synchronization state.
Raises
------
BrainAccessException
If the state cannot be read or the manager has been destroyed.
"""
info = TimeSyncInfo()
_handle_error(
_dll.ba_eeg_manager_get_time_sync_info(self._manager, ctypes.byref(info))
)
return info
@_manager_call
[docs]
def get_device_features(self) -> DeviceFeatures:
"""Returns the features of the connected headset.
Returns
-------
:class:`~brainaccess.core.device_features.DeviceFeatures`
Query object for the accelerometer, gyroscope, bipolar electrodes and
electrode count.
Raises
------
BrainAccessException
If the headset is not connected, the information is unavailable or the
manager has been destroyed.
"""
info = self.get_device_info()
return DeviceFeatures(info)
@_manager_call
[docs]
def get_annotations(self) -> dict:
"""Returns all annotations collected so far.
Annotations are cleared when the headset disconnects.
Returns
-------
dict
A dictionary with two keys:
- ``"annotations"``: list of annotation strings.
- ``"timestamps"``: list of the matching timestamps, as sample numbers
(not seconds); see :meth:`annotate`.
Raises
------
BrainAccessException
If the manager has been destroyed.
"""
ae = ctypes.POINTER(Annotation)()
size = ctypes.c_size_t()
_dll.ba_eeg_manager_get_annotations(
self._manager, ctypes.pointer(ae), ctypes.pointer(size)
)
annotations = [ae[i] for i in range(size.value)]
timestamps = [x.timestamp for x in annotations]
annotations = [x.annotation for x in annotations]
return {"annotations": annotations, "timestamps": timestamps}
@_manager_call
[docs]
def clear_annotations(self) -> None:
"""Removes all annotations.
Raises
------
BrainAccessException
If the manager has been destroyed.
"""
_dll.ba_eeg_manager_clear_annotations(self._manager)
@_manager_call
[docs]
def start_update(self, callback: Union[Callable, None] = None) -> None:
"""Sends a firmware image to the headset.
The image file is set with :func:`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. ``callback`` is not called in these
cases.
"""
_reject_callback_operation()
done = callback if callback is not None else (lambda: None)
with self._callback_ota_update_mtx:
self._callback_ota_update = lambda _sent, _total: done()
_handle_error(
_dll.ba_eeg_manager_start_update(
self._manager, _callback_ota_update, self._manager
)
)
@_manager_call
[docs]
def set_sample_rate(self, sample_rate: int) -> bool:
"""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 :class:`~brainaccess.core.stream_rate.StreamRate` for 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
:meth:`set_impedance_mode`).
Parameters
----------
sample_rate : int
The sample rate in Hz.
Returns
-------
bool
Always ``True``; failures raise.
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.
"""
if self.is_streaming():
raise BrainAccessException("Cannot change sample rate while streaming")
_sample_rate = StreamRate.from_hz(sample_rate)
if _sample_rate == StreamRate.UNKNOWN:
raise BrainAccessException("Wrong sample rate")
code = _dll.ba_eeg_manager_set_data_stream_rate(
self._manager, ctypes.c_uint8(_sample_rate.value)
)
if code == _Error.UNSUPPORTED_DEVICE.value:
device_model = self.get_device_info().device_model
raise BrainAccessException(
f"{device_model.name} does not support {sample_rate} Hz sample rate"
)
return _handle_error(code)
@_manager_call
[docs]
def get_charging_settings(self) -> ChargingSettings:
"""Reads the charging settings from the headset.
Returns
-------
:class:`~brainaccess.core.charging_settings.ChargingSettings`
Whether the headset stays on while charging, and the sleep timeout in
minutes.
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.
"""
settings = ChargingSettings()
_handle_error(_dll.ba_eeg_manager_read_charging_settings(self._manager, ctypes.byref(settings)))
return settings
@_manager_call
[docs]
def set_charging_settings(self, settings: ChargingSettings) -> bool:
"""Writes the charging settings to the headset.
The settings revert to their defaults when the headset powers off. A
``sleep_timeout`` of 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 with :meth:`get_charging_settings`.
Parameters
----------
settings : :class:`~brainaccess.core.charging_settings.ChargingSettings`
The settings to apply, for example ``ChargingSettings(False, 15)``.
Returns
-------
bool
``True`` if the settings were written to the headset.
Raises
------
BrainAccessException
If the headset is not connected, the manager has been destroyed or
this is called from inside a callback.
"""
if not self.is_connected():
raise BrainAccessException("Not connected")
return _dll.ba_eeg_manager_set_charging_settings(self._manager, settings)
@_manager_call
[docs]
def set_output_mode(self, mode: OutputMode) -> bool:
"""Selects the output mode of the next stream.
:attr:`~brainaccess.core.output_mode.OutputMode.SQUARE_WAVE` replaces the
electrode data with a test signal generated by the headset, for checking
the signal chain.
:attr:`~brainaccess.core.output_mode.OutputMode.NORMAL` streams 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 : :class:`~brainaccess.core.output_mode.OutputMode`
The output mode.
Returns
-------
bool
``True`` if the mode was accepted.
Raises
------
BrainAccessException
If the mode is rejected or the manager has been destroyed.
"""
return _handle_error(
_dll.ba_eeg_manager_set_output_mode(
self._manager, ctypes.c_uint8(mode.value)
)
)
@_manager_call
[docs]
def get_output_mode(self) -> OutputMode:
"""Returns the output mode of the next stream.
Returns
-------
:class:`~brainaccess.core.output_mode.OutputMode`
The configured output mode.
Raises
------
BrainAccessException
If the mode cannot be read or the manager has been destroyed.
"""
mode = ctypes.c_uint8()
_handle_error(_dll.ba_eeg_manager_read_output_mode(self._manager, ctypes.byref(mode)))
return OutputMode(mode.value)