"""Low-level control of BrainAccess headsets.
Start with :func:`init`, find headsets with :func:`scan`, and talk to a headset
through :class:`~brainaccess.core.eeg_manager.EEGManager`. This module also holds
the library configuration (:func:`get_config`, :func:`set_config_fields` and the
helpers built on them) and the library version (:func:`get_version`). Call
:func:`close` when you are done.
For recording EEG without handling the connection yourself, use
:class:`brainaccess.utils.acquisition.EEG`.
"""
import ctypes
import os
import threading
from typing import Any, Dict, List
from pathlib import Path
from brainaccess.utils.exceptions import (
_handle_error,
_handle_error_bacore,
_ErrorBacore,
)
from brainaccess.utils.exceptions import BrainAccessException
from brainaccess.core.log_level import LogLevel
from brainaccess.libload import load_library
from brainaccess.core.ble_device import _BaBleDevice, ScannedDevice
from brainaccess.core.sBacore_config_t import BacoreConfig
_dll = load_library("bacore")
_lifecycle_lock = threading.RLock()
_live_managers = set()
from brainaccess.core.version import Version # noqa: E402
# init()
_dll.ba_core_init.argtypes = []
_dll.ba_core_init.restype = ctypes.c_uint8
# ba_core_get_config()
_dll.ba_core_get_config.argtypes = [ctypes.POINTER(BacoreConfig)]
_dll.ba_core_get_config.restype = ctypes.c_uint8
# ba_core_set_config()
_dll.ba_core_set_config.argtypes = [ctypes.POINTER(BacoreConfig)]
_dll.ba_core_set_config.restype = ctypes.c_uint8
# close()
_dll.ba_core_close.argtypes = []
_dll.ba_core_close.restype = ctypes.c_uint8
# get_version()
_dll.ba_core_get_version.argtypes = []
_dll.ba_core_get_version.restype = ctypes.POINTER(Version)
# scan()
_dll.ba_core_scan.argtypes = [
ctypes.POINTER(ctypes.POINTER(_BaBleDevice)),
ctypes.POINTER(ctypes.c_size_t),
]
_dll.ba_core_scan.restype = ctypes.c_uint8
[docs]
def init() -> bool:
"""Initialize BrainAccess Core.
Call it once before :func:`scan`, :func:`get_config`, :func:`set_config_fields`
or creating an :class:`~brainaccess.core.eeg_manager.EEGManager`. Calling it
again after a successful call does nothing and returns ``True``.
Initialization starts the library with its default configuration (see
:func:`get_config`). The log file ``bacore.log`` is created in the current
directory when the first line is logged.
Returns
-------
bool
``True`` on success.
Raises
------
BrainAccessException
If the library cannot allocate its resources. It then stays
uninitialized and the call can be repeated.
"""
with _lifecycle_lock:
code = _dll.ba_core_init()
if code == _ErrorBacore.INIT_ALREADY_INITIALIZED.value:
return True
return _handle_error_bacore(code)
[docs]
def close() -> None:
"""Shut BrainAccess Core down and discard its configuration.
Destroy every :class:`~brainaccess.core.eeg_manager.EEGManager` first (leave
its ``with`` block or call ``destroy()``). Calling :func:`close` when the
library is not initialized does nothing. The next :func:`init` starts from the
default configuration again.
Raises
------
BrainAccessException
If an :class:`~brainaccess.core.eeg_manager.EEGManager` still exists, or
the library fails to shut down.
"""
with _lifecycle_lock:
if _live_managers:
raise BrainAccessException("Destroy all EEG managers before closing BrainAccess Core")
code = _dll.ba_core_close()
if code == _ErrorBacore.INIT_NOT_ALL_MANAGERS_CLOSED.value:
raise BrainAccessException(
"Destroy all EEG managers before closing BrainAccess Core"
)
if code not in (
_ErrorBacore.OK.value, _ErrorBacore.INIT_NOT_INITIALIZED.value
):
raise BrainAccessException(f"BrainAccess Core could not be shut down (error code {code})")
[docs]
def get_version() -> Version:
"""Get the version of the BrainAccess Core library.
This is the version of the bundled native library, not the version of the
``brainaccess`` Python package. It works without :func:`init`.
Returns
-------
~brainaccess.core.version.Version
Major, minor and patch numbers of the library.
"""
return _dll.ba_core_get_version()[0]
[docs]
def scan() -> List[ScannedDevice]:
"""Scan for nearby BrainAccess headsets.
The call blocks for about 5 seconds. Call :func:`init` first.
Only devices advertising a BrainAccess name (``BA <MODEL> <number>``, for
example ``BA HALO 042`` or ``BA EXG8 003``) are returned; a renamed device is
not listed. A headset that is already connected, from this or another
computer, usually stops advertising and is then not found.
Returns
-------
list of ~brainaccess.core.ble_device.ScannedDevice
The headsets found, empty if there are none. ``mac_address`` is the MAC
address on Linux and Windows; macOS does not reveal MAC addresses, so it
is the 36-character CoreBluetooth UUID there.
Raises
------
BrainAccessException
If the library is not initialized, or Bluetooth cannot be used (no
adapter, the system Bluetooth service is not reachable, or the adapter
selected with ``adapter_index`` does not exist).
Notes
-----
On Linux the adapter ``hci<adapter_index>`` is used (see
:func:`set_config_fields`); Windows and macOS always use the system default
adapter.
"""
with _lifecycle_lock:
list_size = ctypes.c_size_t()
device_list_ptr = ctypes.POINTER(_BaBleDevice)()
_handle_error(
_dll.ba_core_scan(ctypes.pointer(device_list_ptr),
ctypes.pointer(list_size))
)
# Copy strings before another scan or shutdown can invalidate them.
return [
ScannedDevice(device.name, device.mac_address)
for device in device_list_ptr[: list_size.value]
]
_MAX_CSTR = 200 # includes terminating NUL in C
def _to_cstr_200(s: str) -> bytes:
b = os.fsencode(s)
if len(b) >= _MAX_CSTR: # must leave room for NUL
raise BrainAccessException(
f"String too long ({len(b)} bytes). Max is 199 UTF-8 bytes."
)
return b
def _as_int_log_level(value: Any) -> int:
# Accept IntEnum, int, etc.
if hasattr(value, "value"):
value = int(value.value)
if not isinstance(value, int):
raise BrainAccessException(
f"log_level must be int/IntEnum, got {type(value).__name__}"
)
# The core stores any byte without checking it (ba_core_set_config).
if value not in {level.value for level in LogLevel}:
raise BrainAccessException(
f"log_level must be a LogLevel value (0..4), got {value}"
)
return value
def _get_config() -> BacoreConfig:
with _lifecycle_lock:
cfg = BacoreConfig()
_handle_error(_dll.ba_core_get_config(ctypes.byref(cfg)))
return cfg
def _set_config(cfg: BacoreConfig) -> bool:
with _lifecycle_lock:
_handle_error(_dll.ba_core_set_config(ctypes.byref(cfg)))
return True
[docs]
def get_config() -> Dict[str, Any]:
"""Get the current library configuration.
Returns
-------
dict
The settings below, with the values they have after :func:`init`. Change
them with :func:`set_config_fields`.
- ``log_buffer_size`` (int): log buffer in bytes; default ``512``.
- ``log_path`` (str): log file; default ``"bacore.log"`` in the current
directory.
- ``log_level`` (int): a :class:`~brainaccess.core.log_level.LogLevel`
value; default ``2`` (``INFO``).
- ``append_logs`` (bool): append to an existing log file instead of
overwriting it; default ``False``.
- ``timestamps_enabled`` (bool): timestamp each log line; default ``True``.
- ``autoflush`` (bool): write each log line to disk at once; default
``False``.
- ``thread_ids_enabled`` (bool): add the thread ID to each log line;
default ``True``.
- ``chunk_size`` (int): samples per data chunk; default ``25``.
- ``enable_logs`` (bool): logging on or off; default ``True``.
- ``update_path`` (str): firmware file for
:meth:`~brainaccess.core.eeg_manager.EEGManager.start_update`; default
``"../updates/firmware_HALO.bin"``.
- ``adapter_index`` (int): Bluetooth adapter; default ``0``.
Raises
------
BrainAccessException
If the core is not initialized.
"""
cfg = _get_config()
fsdec = os.fsdecode
return {
"log_buffer_size": int(cfg.log_buffer_size),
"log_path": fsdec(bytes(cfg.log_path).split(b"\0", 1)[0]),
"log_level": int(cfg.log_level),
"append_logs": bool(cfg.append_logs),
"timestamps_enabled": bool(cfg.timestamps_enabled),
"autoflush": bool(cfg.autoflush),
"thread_ids_enabled": bool(cfg.thread_ids_enabled),
"chunk_size": int(cfg.chunk_size),
"enable_logs": bool(cfg.enable_logs),
"update_path": fsdec(bytes(cfg.update_path).split(b"\0", 1)[0]),
"adapter_index": int(cfg.adapter_index),
}
[docs]
def set_config_fields(**fields) -> bool:
"""Change one or more library settings.
Settings you do not pass keep their value. The names, types and defaults are
those listed in :func:`get_config`.
Parameters
----------
**fields
Any of the following keyword arguments:
- ``log_buffer_size`` (int): log buffer in bytes, 0 or more. Used only
while ``autoflush`` is off; ``0`` selects the system default size.
Buffered lines are written when the buffer fills or the core is closed.
- ``log_path`` (str): log file, at most 199 UTF-8 bytes. The file is
created (or overwritten) when the first line is logged.
- ``log_level`` (int or :class:`~brainaccess.core.log_level.LogLevel`):
log verbosity.
- ``append_logs`` (bool): ``True`` appends to an existing file,
``False`` overwrites it.
- ``timestamps_enabled`` (bool): timestamp each log line.
- ``autoflush`` (bool): write each line to disk at once. Slower, but
nothing is lost if the program crashes; ``log_buffer_size`` is then
ignored.
- ``thread_ids_enabled`` (bool): add the thread ID to each log line.
- ``chunk_size`` (int): samples per data chunk, 1 to 100. Takes effect at
the next stream start.
- ``enable_logs`` (bool): ``False`` turns all logging off.
- ``update_path`` (str): firmware file for
:meth:`~brainaccess.core.eeg_manager.EEGManager.start_update`, at most
199 UTF-8 bytes. A missing file is reported when the update starts.
- ``adapter_index`` (int): Bluetooth adapter, 0 to 255. Used on Linux
only, where it selects ``hci<adapter_index>``; Windows and macOS use the
system default adapter. The adapter is checked when you scan or connect,
not here.
Returns
-------
bool
``True`` when the settings were applied.
Raises
------
BrainAccessException
If a name is unknown, a value has the wrong type or is out of range, a
string is too long, or the core is not initialized. Nothing is changed
when an exception is raised.
Examples
--------
Log everything to a file of your own:
>>> from brainaccess.core import set_config_fields
>>> from brainaccess.core.log_level import LogLevel
>>> set_config_fields(
... log_level=LogLevel.DEBUG,
... log_path="logs/session.log",
... append_logs=False,
... )
True
"""
if not fields:
return True
cfg = _get_config()
for k, v in fields.items():
if k == "log_buffer_size":
if not (isinstance(v, int) and v >= 0):
raise BrainAccessException(
"log_buffer_size must be a non-negative int")
cfg.log_buffer_size = v
elif k == "log_path":
cfg.log_path = _to_cstr_200(str(v))
elif k == "log_level":
cfg.log_level = _as_int_log_level(v)
elif k == "append_logs":
cfg.append_logs = bool(v)
elif k == "timestamps_enabled":
cfg.timestamps_enabled = bool(v)
elif k == "autoflush":
cfg.autoflush = bool(v)
elif k == "thread_ids_enabled":
cfg.thread_ids_enabled = bool(v)
elif k == "chunk_size":
# bacore rejects values outside 1..100 (bacore.cpp, ba_core_set_config)
if not (isinstance(v, int) and 1 <= v <= 100):
raise BrainAccessException(
"chunk_size must be an int in 1..100")
cfg.chunk_size = v
elif k == "enable_logs":
cfg.enable_logs = bool(v)
elif k == "update_path":
p = Path(str(v))
cfg.update_path = _to_cstr_200(str(p))
elif k == "adapter_index":
if not (isinstance(v, int) and 0 <= v <= 255):
raise BrainAccessException(
"adapter_index must be in [0, 255]")
cfg.adapter_index = v
else:
raise BrainAccessException(f"Unknown config field: {k}")
return _set_config(cfg)
[docs]
def config_set_log_level(log_level: LogLevel) -> bool:
"""Set the log verbosity.
Parameters
----------
log_level : ~brainaccess.core.log_level.LogLevel
Lowest severity to log; more severe messages are logged too.
Returns
-------
bool
``True`` when the setting was applied.
Raises
------
BrainAccessException
If ``log_level`` is not a :class:`~brainaccess.core.log_level.LogLevel`
value, or the core is not initialized.
"""
return set_config_fields(log_level=log_level)
[docs]
def config_set_chunk_size(chunk_size: int) -> bool:
"""Set the number of samples per data chunk.
A chunk is what the callback set with
:meth:`~brainaccess.core.eeg_manager.EEGManager.set_callback_chunk` receives.
The value takes effect at the next stream start.
Parameters
----------
chunk_size : int
Samples per chunk, 1 to 100 (default ``25``).
Returns
-------
bool
``True`` when the setting was applied.
Raises
------
BrainAccessException
If ``chunk_size`` is not an integer from 1 to 100, or the core is not
initialized.
"""
return set_config_fields(chunk_size=chunk_size)
[docs]
def config_set_adapter_index(adapter_index: int) -> bool:
"""Select the Bluetooth adapter used for scanning and connecting.
Only Linux can choose an adapter: ``adapter_index`` selects ``hci<N>``.
Windows and macOS ignore it and use the system default adapter. The adapter is
checked when you scan or connect, not here. :func:`close` resets the
index to 0.
Parameters
----------
adapter_index : int
Adapter number, 0 to 255 (default ``0``).
Returns
-------
bool
``True`` when the setting was applied.
Raises
------
BrainAccessException
If ``adapter_index`` is not an integer from 0 to 255, or the core is not
initialized.
"""
return set_config_fields(adapter_index=adapter_index)
[docs]
def config_enable_logging(enable: bool) -> bool:
"""Turn the library's log file on or off.
Parameters
----------
enable : bool
``True`` to log (the default state), ``False`` to turn all logging off.
Returns
-------
bool
``True`` when the setting was applied.
Raises
------
BrainAccessException
If the core is not initialized.
"""
return set_config_fields(enable_logs=bool(enable))
[docs]
def set_config_path(
file_path: str, append: bool = True, buffer_size: int = 512
) -> bool:
"""Choose the log file.
By default the library logs to ``bacore.log`` in the current directory and
overwrites it. The file is created when the first line is logged.
Parameters
----------
file_path : str
Absolute or relative path of the log file, at most 199 UTF-8 bytes.
append : bool, optional
``True`` (default here) appends to an existing file; ``False``
overwrites it. The library's own default, without calling this function,
is to overwrite.
buffer_size : int, optional
Log buffer in bytes (default ``512``). Lines are written when the buffer
fills or the core is closed, so a smaller value keeps the file more
current. Ignored while ``autoflush`` is on; ``0`` selects the system
default size.
Returns
-------
bool
``True`` when the settings were applied.
Raises
------
BrainAccessException
If the path is longer than 199 UTF-8 bytes, ``buffer_size`` is negative,
or the core is not initialized. The path is not checked for existence or
write access.
"""
return set_config_fields(
log_path=str(file_path),
append_logs=bool(append),
log_buffer_size=int(buffer_size),
)
[docs]
def set_config_timestamp(enable: bool = True) -> bool:
"""Turn timestamps in log lines on or off.
Parameters
----------
enable : bool, optional
``True`` (default) adds a timestamp to each line, ``False`` omits it.
Returns
-------
bool
``True`` when the setting was applied.
Raises
------
BrainAccessException
If the core is not initialized.
"""
return set_config_fields(timestamps_enabled=bool(enable))
[docs]
def set_config_autoflush(enable: bool = True) -> bool:
"""Turn immediate writing of log lines on or off.
With autoflush on, each line reaches the file at once, so nothing is lost if
the program crashes, at some cost in speed. With it off, lines are buffered
(see ``buffer_size`` of :func:`set_config_path`).
Parameters
----------
enable : bool, optional
``True`` (default here) writes every line at once. The library's own
default, without calling this function, is off.
Returns
-------
bool
``True`` when the setting was applied.
Raises
------
BrainAccessException
If the core is not initialized.
"""
return set_config_fields(autoflush=bool(enable))
[docs]
def set_config_thread_id(enable: bool = True) -> bool:
"""Turn thread IDs in log lines on or off.
Useful when debugging a multi-threaded program.
Parameters
----------
enable : bool, optional
``True`` (default) adds the thread ID to each line, ``False`` omits it.
Returns
-------
bool
``True`` when the setting was applied.
Raises
------
BrainAccessException
If the core is not initialized.
"""
return set_config_fields(thread_ids_enabled=bool(enable))
[docs]
def set_config_update_path(file_path: str) -> bool:
"""Set the firmware file used by a headset update.
Parameters
----------
file_path : str
Path of the firmware file, at most 199 UTF-8 bytes.
Returns
-------
bool
``True`` when the path was stored.
Raises
------
BrainAccessException
If the path is too long or the core is not initialized. A missing file is
reported by :meth:`~brainaccess.core.eeg_manager.EEGManager.start_update`.
"""
return set_config_fields(update_path=str(file_path))