From e8d634c232a5add193bde88fbd4a0a2e9ee1c56c Mon Sep 17 00:00:00 2001 From: leorangessi <2673755910@qq.com> Date: Wed, 11 Nov 2026 19:48:18 +0800 Subject: [PATCH 1/2] Add ExpandableEEG32 serial and WiFi boards --- .../brainflow/board_controller_library.cs | 4 +- .../src/main/java/brainflow/BoardIds.java | 4 +- julia_package/brainflow/src/board_shim.jl | 2 + matlab_package/brainflow/BoardIds.m | 2 + nodejs_package/brainflow/brainflow.types.ts | 4 +- python_package/brainflow/board_shim.py | 2 + .../test_expandable_config_board_commands.py | 261 +++++++++++++++ .../test_expandable_eeg32_wifi_channels.py | 309 ++++++++++++++++++ rust_package/brainflow/src/ffi/constants.rs | 2 + src/board_controller/board_controller.cpp | 8 + src/board_controller/brainflow_boards.cpp | 34 ++ src/board_controller/build.cmake | 2 + .../openbci/expandable_eeg32.cpp | 199 +++++++++++ .../openbci/expandable_eeg32_wifi.cpp | 240 ++++++++++++++ .../openbci/inc/expandable_eeg32.h | 24 ++ .../openbci/inc/expandable_eeg32_wifi.h | 28 ++ .../inc/expandable_eeg32_wifi_gain_tracker.h | 42 +++ src/utils/inc/brainflow_constants.h | 4 +- 18 files changed, 1167 insertions(+), 4 deletions(-) create mode 100644 python_package/examples/tests/test_expandable_config_board_commands.py create mode 100644 python_package/examples/tests/test_expandable_eeg32_wifi_channels.py create mode 100644 src/board_controller/openbci/expandable_eeg32.cpp create mode 100644 src/board_controller/openbci/expandable_eeg32_wifi.cpp create mode 100644 src/board_controller/openbci/inc/expandable_eeg32.h create mode 100644 src/board_controller/openbci/inc/expandable_eeg32_wifi.h create mode 100644 src/board_controller/openbci/inc/expandable_eeg32_wifi_gain_tracker.h diff --git a/csharp_package/brainflow/brainflow/board_controller_library.cs b/csharp_package/brainflow/brainflow/board_controller_library.cs index 83d134a4c..036885a01 100644 --- a/csharp_package/brainflow/brainflow/board_controller_library.cs +++ b/csharp_package/brainflow/brainflow/board_controller_library.cs @@ -124,7 +124,9 @@ public enum BoardIds IRONBCI_32_BOARD = 65, NEUROPAWN_KNIGHT_BOARD_IMU = 66, MUSE_S_ATHENA_BOARD = 67, - SHIMMER3_BOARD = 68 + SHIMMER3_BOARD = 68, + EXPANDABLE_EEG_32_WIFI_BOARD = 69, + EXPANDABLE_EEG_32_BOARD = 70 }; diff --git a/java_package/brainflow/src/main/java/brainflow/BoardIds.java b/java_package/brainflow/src/main/java/brainflow/BoardIds.java index e6b24ab11..92593ba52 100644 --- a/java_package/brainflow/src/main/java/brainflow/BoardIds.java +++ b/java_package/brainflow/src/main/java/brainflow/BoardIds.java @@ -74,7 +74,9 @@ public enum BoardIds IRONBCI_32_BOARD(65), NEUROPAWN_KNIGHT_BOARD_IMU(66), MUSE_S_ATHENA_BOARD(67), - SHIMMER3_BOARD(68); + SHIMMER3_BOARD(68), + EXPANDABLE_EEG_32_WIFI_BOARD(69), + EXPANDABLE_EEG_32_BOARD(70); private final int board_id; private static final Map bi_map = new HashMap (); diff --git a/julia_package/brainflow/src/board_shim.jl b/julia_package/brainflow/src/board_shim.jl index b1e05f60c..7b4b0f237 100644 --- a/julia_package/brainflow/src/board_shim.jl +++ b/julia_package/brainflow/src/board_shim.jl @@ -70,6 +70,8 @@ export BrainFlowInputParams NEUROPAWN_KNIGHT_BOARD_IMU = 66 MUSE_S_ATHENA_BOARD = 67 SHIMMER3_BOARD = 68 + EXPANDABLE_EEG_32_WIFI_BOARD = 69 + EXPANDABLE_EEG_32_BOARD = 70 end diff --git a/matlab_package/brainflow/BoardIds.m b/matlab_package/brainflow/BoardIds.m index a30390909..38721131a 100644 --- a/matlab_package/brainflow/BoardIds.m +++ b/matlab_package/brainflow/BoardIds.m @@ -68,5 +68,7 @@ NEUROPAWN_KNIGHT_BOARD_IMU(66) MUSE_S_ATHENA_BOARD(67) SHIMMER3_BOARD(68) + EXPANDABLE_EEG_32_WIFI_BOARD(69) + EXPANDABLE_EEG_32_BOARD(70) end end diff --git a/nodejs_package/brainflow/brainflow.types.ts b/nodejs_package/brainflow/brainflow.types.ts index 5aabeaed5..f14f0eca8 100644 --- a/nodejs_package/brainflow/brainflow.types.ts +++ b/nodejs_package/brainflow/brainflow.types.ts @@ -77,7 +77,9 @@ export enum BoardIds { IRONBCI_32_BOARD = 65, NEUROPAWN_KNIGHT_BOARD_IMU = 66, MUSE_S_ATHENA_BOARD = 67, - SHIMMER3_BOARD = 68 + SHIMMER3_BOARD = 68, + EXPANDABLE_EEG_32_WIFI_BOARD = 69, + EXPANDABLE_EEG_32_BOARD = 70, } export enum IpProtocolTypes { diff --git a/python_package/brainflow/board_shim.py b/python_package/brainflow/board_shim.py index e18211334..4c1c0426f 100644 --- a/python_package/brainflow/board_shim.py +++ b/python_package/brainflow/board_shim.py @@ -83,6 +83,8 @@ class BoardIds(enum.IntEnum): NEUROPAWN_KNIGHT_BOARD_IMU = 66 #: MUSE_S_ATHENA_BOARD = 67 #: SHIMMER3_BOARD = 68 #: + EXPANDABLE_EEG_32_WIFI_BOARD = 69 #: + EXPANDABLE_EEG_32_BOARD = 70 #: class IpProtocolTypes(enum.IntEnum): diff --git a/python_package/examples/tests/test_expandable_config_board_commands.py b/python_package/examples/tests/test_expandable_config_board_commands.py new file mode 100644 index 000000000..f125ac14f --- /dev/null +++ b/python_package/examples/tests/test_expandable_config_board_commands.py @@ -0,0 +1,261 @@ +""" +Real-device test: send config_board strings and report BrainFlow OK vs INVALID_ARGUMENTS. + +Why xL161000X may fail with INVALID_ARGUMENTS: + - Board MUST be EXPANDABLE_EEG_32_WIFI_BOARD (69). On CYTON_DAISY_WIFI (6) etc., + channel letter 'L' is not in the 16-letter table -> INVALID_ARGUMENTS before HTTP. + - DLL must be your rebuilt BoardController.dll (32-letter ExpandableEeg32WifiGainTracker). + +Fix nptyping first (BrainFlow pins this version): + py3.9 -m pip install "nptyping==1.4.4" + +Usage (PowerShell): + $env:PYTHONPATH="E:\\Interesting\\BCI\\brainflow-master\\python_package" + python python_package/examples/tests/test_expandable_config_board_commands.py ^ + --ip 192.168.4.1 --port 6677 + +Optional: --board 69 (default) or 6 to demonstrate Daisy rejecting L. +""" + +from __future__ import annotations + +import argparse +import os +import platform +import struct +import sys +from datetime import datetime +from pathlib import Path + +_REPO = Path(__file__).resolve().parents[3] +if str(_REPO / "python_package") not in sys.path: + sys.path.insert(0, str(_REPO / "python_package")) + +try: + from brainflow.board_shim import ( + BoardControllerDLL, + BoardIds, + BoardShim, + BrainFlowInputParams, + IpProtocolTypes, + ) + from brainflow.exit_codes import BrainFlowError, BrainFlowExitCodes +except Exception as e: + msg = str(e).lower() + if "nptyping" in msg or "invalidargumentserror" in type(e).__name__.lower(): + print( + "\nBrainFlow needs nptyping 1.4.4 (see python_package/setup.py).\n" + " py3.9 -m pip install \"nptyping==1.4.4\"\n", + file=sys.stderr, + ) + raise + +def _brainflow_dll_relative_name() -> str: + if platform.system() == "Windows": + return ( + "lib\\BoardController32.dll" + if struct.calcsize("P") * 8 != 64 + else "lib\\BoardController.dll" + ) + if platform.system() == "Darwin": + return "lib/libBoardController.dylib" + return "lib/libBoardController.so" + + +def resolve_board_controller_dll_path() -> Path: + """Same path BrainFlow uses (pkg_resources under python_package/brainflow).""" + import pkg_resources + + rel = _brainflow_dll_relative_name() + return Path(pkg_resources.resource_filename("brainflow", rel)).resolve() + + +def _format_dll_stat(path: Path) -> str: + if not path.is_file(): + return "missing" + st = path.stat() + mtime = datetime.fromtimestamp(st.st_mtime).strftime("%Y-%m-%d %H:%M:%S") + return f"size={st.st_size} bytes, mtime={mtime}" + + +def _module_path_from_handle(handle: int) -> str | None: + import ctypes + + if not handle: + return None + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + GetModuleFileNameW = kernel32.GetModuleFileNameW + GetModuleFileNameW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint32] + GetModuleFileNameW.restype = ctypes.c_uint32 + buf = ctypes.create_unicode_buffer(32768) + n = GetModuleFileNameW(ctypes.c_void_p(handle), buf, len(buf)) + if not n: + return None + return buf.value + + +def _loaded_board_controller_path_windows(dll_instance) -> str | None: + if platform.system() != "Windows": + return None + handle = getattr(dll_instance, "_handle", None) + if handle: + return _module_path_from_handle(handle) + import ctypes + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + handle = kernel32.GetModuleHandleW("BoardController.dll") + return _module_path_from_handle(handle) if handle else None + + +def log_board_controller_dll_paths() -> None: + configured = resolve_board_controller_dll_path() + print("BoardController library:") + print(f" configured (BrainFlow pkg_resources): {configured}") + print(f" on disk: {_format_dll_stat(configured)}") + + # Load native lib (same as first BoardShim call) + dll = BoardControllerDLL.get_instance() + + loaded = _loaded_board_controller_path_windows(dll.lib) + if loaded: + loaded_path = Path(loaded) + print(f" loaded in process (GetModuleHandleW): {loaded_path}") + print(f" loaded file: {_format_dll_stat(loaded_path)}") + if loaded_path.resolve() != configured.resolve(): + print(" WARNING: loaded path differs from configured pkg_resources path!") + elif platform.system() == "Windows": + print(" loaded in process: (BoardController.dll not found in module list yet)") + print() + + +# Channel letters (must match ExpandableEeg32WifiGainTracker / GUI 32ch map) +OPEN_CHARS = "12345678QWERTYUIASDFGHJKZXCVBNML" + + +def letter_for_channel(ch: int) -> str: + if not (1 <= ch <= 32): + raise ValueError(ch) + return OPEN_CHARS[ch - 1] + + +def impedance_on_cmd(ch: int) -> str: + """OpenBCI GUI style when enabling impedance on one channel (see setCheckingImpedanceCyton).""" + c = letter_for_channel(ch) + return f"x{c}000100Xz{c}01Z" + + +def impedance_off_cmd(ch: int) -> str: + c = letter_for_channel(ch) + return f"x{c}060110Xz{c}00Z" + + +def impedance_check_cmd(ch: int) -> str: + """GUI 'Check' path often uses x...060110X + z...00Z (ch1 example: x1060110Xz100Z).""" + c = letter_for_channel(ch) + if ch <= 8: + return f"x{c}060110Xz{c}00Z" + return f"x{c}060110Xz{c}00Z" + + +# Power / channel on-off +DEFAULT_CMDS = [ + ("invalid_digit9", "x9060110X"), + ("ch32_power_off_user", "xL161000X"), + ("ch32_power_off_alt", "xL160110X"), + ("ch32_power_on", "xL060110X"), + ("ch1_power_off", "x1160110X"), + ("single_L", "L"), + ("single_l_close", "l"), +] + +# Impedance (BrainFlow only validates x...X letters; z...Z is forwarded as-is) +IMPEDANCE_CMDS = [ + ("imp_prefix_z", "z"), + ("imp_suffix_Z", "Z"), + ("imp_ch1_gui_check", "x1060110Xz100Z"), + ("imp_ch1_on", impedance_on_cmd(1)), + ("imp_ch1_off", impedance_off_cmd(1)), + ("imp_ch8_on", impedance_on_cmd(8)), + ("imp_ch16_on", impedance_on_cmd(16)), + ("imp_ch16_off", impedance_off_cmd(16)), + ("imp_ch17_on", impedance_on_cmd(17)), + ("imp_ch17_gui_log", "xA000100XzA01Z"), + ("imp_ch17_off", impedance_off_cmd(17)), + ("imp_ch32_on", impedance_on_cmd(32)), + ("imp_ch32_off", impedance_off_cmd(32)), +] + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("--ip", default="192.168.4.1") + p.add_argument("--port", type=int, default=6677) + p.add_argument( + "--board", + type=int, + default=69, + help="69=EXPANDABLE_EEG_32_WIFI_BOARD (L valid). 6=CYTON_DAISY_WIFI (L invalid).", + ) + p.add_argument("--extra", action="append", default=[], help="Extra command to test (repeatable)") + p.add_argument("--impedance-only", action="store_true", help="Only run IMPEDANCE_CMDS (+ --extra)") + p.add_argument("--skip-impedance", action="store_true", help="Skip IMPEDANCE_CMDS") + p.add_argument( + "--dll-only", + action="store_true", + help="Print BoardController.dll paths and exit (no WiFi / config_board tests)", + ) + args = p.parse_args() + + if args.dll_only: + log_board_controller_dll_paths() + return 0 + + params = BrainFlowInputParams() + params.ip_address = args.ip + params.ip_port = args.port + params.ip_protocol = int(IpProtocolTypes.TCP) + + try: + bid = BoardIds(args.board) + bname = bid.name + except ValueError: + bname = f"unknown({args.board})" + print(f"board_id={args.board} ({bname})") + print(f"ip={args.ip} port={args.port}") + log_board_controller_dll_paths() + + board = BoardShim(args.board, params) + board.prepare_session() + try: + if args.impedance_only: + steps = list(IMPEDANCE_CMDS) + elif args.skip_impedance: + steps = list(DEFAULT_CMDS) + else: + steps = list(DEFAULT_CMDS) + list(IMPEDANCE_CMDS) + steps += [(f"extra_{i}", c) for i, c in enumerate(args.extra)] + + for label, cmd in steps: + try: + resp = board.config_board(cmd) + ok = "OK" + tail = repr(resp[:120]) if resp else "''" + except BrainFlowError as e: + ok = "FAIL" + tail = f"{e} (exit_code={e.exit_code})" + if e.exit_code == BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR.value: + tail += " <- gain_tracker rejected x...X (wrong board id or old DLL?)" + print(f" [{ok:4}] {label:24} cmd={cmd!r}") + print(f" {tail}") + print( + "\nDone. Impedance strings use OpenBCI GUI pattern x{ch}000100Xz{ch}01Z (on) / " + "x{ch}060110Xz{ch}00Z (off). Ch17-32 use letters A..L in both x and z parts." + ) + print("If xL... or xA000100XzA01Z fail on GUI but OK here, GUI uses wrong board_id or old DLL.") + return 0 + finally: + board.release_session() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/python_package/examples/tests/test_expandable_eeg32_wifi_channels.py b/python_package/examples/tests/test_expandable_eeg32_wifi_channels.py new file mode 100644 index 000000000..1ca1b5cf0 --- /dev/null +++ b/python_package/examples/tests/test_expandable_eeg32_wifi_channels.py @@ -0,0 +1,309 @@ +""" +EXPANDABLE_EEG_32_WIFI_BOARD — full validation for 32-channel mappings + streaming. + +================================================================================ +TEST PLAN(与固件/OpenBCI 约定一致部分;BrainFlow 侧校验 x…X 字母表) +================================================================================ +前置 + - 拷贝 compiled/Debug|Release/BoardController.dll → python_package/brainflow/lib/ + - pip: numpy, nptyping==1.4.4 + - 帽端 WiFi 已连接;PC 与 shield 在同一网段;--ip-port 与 HTTP /tcp 配置一致 + +阶段 0 — BrainFlow 校验(不应发往无效字母) + 0.1 发送非法 x9060110X(通道字母 '9'),期望 INVALID_ARGUMENTS + +阶段 1 — x…X 依次「通电开启」32 路(POWER=0,GAIN=24 即 '6') + 对 ch=1..32:cmd = x + LETTER(ch) + "060110X" + 期望:每步 STATUS_OK(ExpandableEeg32WifiGainTracker 识别 32 个字母) + +阶段 2 — x…X 依次「掉电关闭」32 路(POWER=1) + 对 ch=1..32:cmd = x + LETTER(ch) + "160110X" + 期望:每步 STATUS_OK + +阶段 3 — 恢复默认 + 发送 "d"(与 Cyton+Daisy 一致),期望 STATUS_OK + +阶段 4 — 单字符「开启」类命令(与 Cyton 1–16 + 扩展 17–32 映射) + ch 1–8: '1'..'8' + ch 9–16: Q W E R T Y U I + ch 17–24: A S D F G H J K + ch 25–32: Z X C V B N M L + 依次各发送 1 字符,期望 STATUS_OK(由 shield 转发至板卡) + +阶段 5 — 单字符「关闭」 + ch 1–8: ! @ # $ % ^ & * (第 8 路关闭为 *,与常见 Cyton 文档一致) + ch 9–16: q w e r t y u i + ch 17–32: a s d f g h j k z x c v b n m l (与 OPEN_CHARS 大写一一对应) + 依次发送,期望 STATUS_OK + +阶段 6 — 阻抗通道指定(单字符,与 OpenBCI Cyton 选通道测阻抗同一风格) + 说明:板卡描述无 resistance_channels;此处仅验证命令被 BrainFlow 接受并转发。 + 可选:先发 'z' 再逐通道发 OPEN_CHAR(--impedance-with-z);默认仅逐通道 OPEN_CHAR。 + +阶段 7 — 采集与健康检查 + start_stream → sleep → stop_stream → get_board_data 形状 (num_rows, N),EEG 有限值比例 + +================================================================================ +""" + +from __future__ import annotations + +import argparse +import logging +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, List, Tuple + +import numpy as np + +_REPO_ROOT = Path(__file__).resolve().parents[3] +_PY_PKG = _REPO_ROOT / "python_package" +if str(_PY_PKG) not in sys.path: + sys.path.insert(0, str(_PY_PKG)) + +from brainflow.board_shim import BoardIds, BoardShim, BrainFlowInputParams, IpProtocolTypes +from brainflow.exit_codes import BrainFlowError, BrainFlowExitCodes + +# Ch 1–16: Cyton + Daisy;17–32:扩展(与 C++ ExpandableEeg32WifiGainTracker 一致) +OPEN_CHARS = ( + "12345678" + "QWERTYUI" + "ASDFGHJK" + "ZXCVBNML" +) + +# 单字符关闭:前 8 路为 !@#$%^&*(Cyton 常见映射;原 "!@#$%^&" 仅 7 个符号需补第 8 路) +# 9–16: qwertyui;17–32: asdfghjk + zxcvbnml +CLOSE_CHARS = ( + "!@#$%^&*" + "qwertyui" + "asdfghjk" + "zxcvbnml" +) +assert len(OPEN_CHARS) == 32 and len(CLOSE_CHARS) == 32 + + +def letter_for_channel(ch: int) -> str: + if not (1 <= ch <= 32): + raise ValueError(ch) + return OPEN_CHARS[ch - 1] + + +@dataclass +class RunSummary: + phase: str + passed: int = 0 + failed: int = 0 + errors: List[str] = field(default_factory=list) + + +def _ensure_dll(lib_dir: Path, compiled_debug: Path, compiled_release: Path) -> None: + dst = lib_dir / "BoardController.dll" + if dst.is_file(): + return + for src in (compiled_debug, compiled_release): + if src.is_file(): + import shutil + + lib_dir.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + logging.info("Copied %s -> %s", src, dst) + return + logging.warning("BoardController.dll missing; copy from compiled/Debug or Release.") + + +def _run_phase( + board: BoardShim, + phase_name: str, + steps: List[Tuple[str, str]], + delay_s: float, + log_every: int, +) -> RunSummary: + s = RunSummary(phase=phase_name) + for i, (label, cmd) in enumerate(steps): + try: + board.config_board(cmd) + s.passed += 1 + if (i + 1) % log_every == 0 or i == 0: + logging.info("[%s] OK %s cmd=%r", phase_name, label, cmd) + except BrainFlowError as e: + s.failed += 1 + msg = f"{label} cmd={cmd!r} -> {e}" + s.errors.append(msg) + logging.error("[%s] FAIL %s", phase_name, msg) + if delay_s > 0: + time.sleep(delay_s) + return s + + +def main() -> int: + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") + parser = argparse.ArgumentParser(description="Expandable 32ch full wire + BrainFlow test") + parser.add_argument("--ip-address", default="192.168.4.1") + parser.add_argument("--ip-port", type=int, default=6677) + parser.add_argument("--stream-seconds", type=float, default=2.0) + parser.add_argument("--cmd-delay", type=float, default=0.05, help="delay between config_board calls") + parser.add_argument("--log-every", type=int, default=8, help="log every N steps within long loops") + parser.add_argument( + "--impedance-with-z", + action="store_true", + help="before impedance chars, send 'z' once (firmware-dependent)", + ) + parser.add_argument("--skip-stream", action="store_true") + args = parser.parse_args() + + lib_dir = _REPO_ROOT / "python_package" / "brainflow" / "lib" + _ensure_dll( + lib_dir, + _REPO_ROOT / "compiled" / "Debug" / "BoardController.dll", + _REPO_ROOT / "compiled" / "Release" / "BoardController.dll", + ) + + params = BrainFlowInputParams() + params.ip_address = args.ip_address + params.ip_port = args.ip_port + params.ip_protocol = int(IpProtocolTypes.TCP) + + board = BoardShim(BoardIds.EXPANDABLE_EEG_32_WIFI_BOARD, params) + BoardShim.enable_board_logger() + + n_rows = BoardShim.get_num_rows(board.get_board_id()) + eeg_idx = np.array(BoardShim.get_eeg_channels(board.get_board_id())) + + all_summaries: List[RunSummary] = [] + + print("\n========== TEST PLAN (see module docstring) ==========\n") + + try: + logging.info("prepare_session()") + board.prepare_session() + + # ----- Phase 0 ----- + try: + board.config_board("x9060110X") + logging.error("Phase0: expected failure for x9060110X") + all_summaries.append(RunSummary("phase0_invalid_x", passed=0, failed=1, errors=["no exception"])) + return 1 + except BrainFlowError as e: + if e.exit_code != BrainFlowExitCodes.INVALID_ARGUMENTS_ERROR.value: + logging.error("Phase0: wrong code %s", e.exit_code) + return 1 + logging.info("Phase0 OK: invalid x9060110X rejected") + all_summaries.append(RunSummary("phase0_invalid_x", passed=1, failed=0)) + + # ----- Phase 1: x on ----- + steps_x_on = [(f"ch{c}_xon", f"x{letter_for_channel(c)}060110X") for c in range(1, 33)] + all_summaries.append( + _run_phase(board, "phase1_x_power_on", steps_x_on, args.cmd_delay, args.log_every) + ) + + # ----- Phase 2: x off ----- + steps_x_off = [(f"ch{c}_xoff", f"x{letter_for_channel(c)}160110X") for c in range(1, 33)] + all_summaries.append( + _run_phase(board, "phase2_x_power_off", steps_x_off, args.cmd_delay, args.log_every) + ) + + # ----- Phase 3: defaults ----- + s3 = RunSummary("phase3_defaults_d") + try: + board.config_board("d") + s3.passed = 1 + logging.info("Phase3 OK: d") + except BrainFlowError as e: + s3.failed = 1 + s3.errors.append(str(e)) + logging.error("Phase3 FAIL: %s", e) + all_summaries.append(s3) + + # ----- Phase 4: single-char open ----- + steps_sc_on = [(f"ch{c}_sc_open", OPEN_CHARS[c - 1]) for c in range(1, 33)] + all_summaries.append( + _run_phase(board, "phase4_single_char_open", steps_sc_on, args.cmd_delay, args.log_every) + ) + + # ----- Phase 5: single-char close ----- + steps_sc_off = [(f"ch{c}_sc_close", CLOSE_CHARS[c - 1]) for c in range(1, 33)] + all_summaries.append( + _run_phase(board, "phase5_single_char_close", steps_sc_off, args.cmd_delay, args.log_every) + ) + + # ----- Phase 6: impedance channel select (same 32 chars as OPEN_CHARS; optional z/Z) ----- + steps_imp: List[Tuple[str, str]] = [] + if args.impedance_with_z: + steps_imp.append(("imp_prefix_z", "z")) + for c in range(1, 33): + steps_imp.append((f"imp_ch{c}", OPEN_CHARS[c - 1])) + if args.impedance_with_z: + steps_imp.append(("imp_suffix_Z", "Z")) + all_summaries.append( + _run_phase(board, "phase6_impedance_select", steps_imp, args.cmd_delay, args.log_every) + ) + + # ----- Phase 7: stream ----- + if not args.skip_stream: + board.config_board("d") + time.sleep(0.2) + logging.info("Phase7 start_stream %.1fs", args.stream_seconds) + board.start_stream(45000) + time.sleep(args.stream_seconds) + board.stop_stream() + n_avail = board.get_board_data_count() + s7 = RunSummary("phase7_stream") + if n_avail <= 0: + s7.failed = 1 + s7.errors.append("no samples") + logging.error("Phase7: no samples") + else: + data = board.get_board_data(min(n_avail, 5000)) + if data.shape[0] != n_rows: + s7.failed = 1 + s7.errors.append(f"rows {data.shape[0]} != {n_rows}") + else: + eeg = data[eeg_idx, :] + finite_ratio = float(np.mean(np.isfinite(eeg))) + logging.info( + "Phase7 OK: shape=%s finite_eeg=%.4f", + data.shape, + finite_ratio, + ) + s7.passed = 1 + all_summaries.append(s7) + + board.release_session() + + # ---------- Summary ---------- + print("\n========== RESULT SUMMARY ==========") + total_pass = sum(s.passed for s in all_summaries) + total_fail = sum(s.failed for s in all_summaries) + for s in all_summaries: + line = f" {s.phase}: passed={s.passed} failed={s.failed}" + if s.errors: + line += f" errors={len(s.errors)}" + print(line) + for err in s.errors[:5]: + print(f" - {err}") + if len(s.errors) > 5: + print(f" ... and {len(s.errors) - 5} more") + print(f"\nTOTAL: passed_steps={total_pass} failed_steps={total_fail}") + if total_fail > 0: + print("OVERALL: FAIL") + return 1 + print("OVERALL: PASS") + return 0 + + except BrainFlowError as e: + logging.error("BrainFlowError: %s", e, exc_info=True) + if board.is_prepared(): + board.release_session() + return 2 + except Exception: + logging.exception("Unexpected error") + if board.is_prepared(): + board.release_session() + return 3 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rust_package/brainflow/src/ffi/constants.rs b/rust_package/brainflow/src/ffi/constants.rs index 37d78ddfa..98c942b57 100644 --- a/rust_package/brainflow/src/ffi/constants.rs +++ b/rust_package/brainflow/src/ffi/constants.rs @@ -104,6 +104,8 @@ pub enum BoardIds { NeuropawnKnightBoardImu = 66, MuseSAthenaBoard = 67, Shimmer3Board = 68, + ExpandableEeg32WifiBoard = 69, + ExpandableEeg32Board = 70, } #[repr(i32)] #[derive(FromPrimitive, ToPrimitive, Debug, Copy, Clone, Hash, PartialEq, Eq)] diff --git a/src/board_controller/board_controller.cpp b/src/board_controller/board_controller.cpp index 612965994..72383acd0 100644 --- a/src/board_controller/board_controller.cpp +++ b/src/board_controller/board_controller.cpp @@ -32,6 +32,8 @@ #include "cyton.h" #include "cyton_daisy.h" #include "cyton_daisy_wifi.h" +#include "expandable_eeg32.h" +#include "expandable_eeg32_wifi.h" #include "cyton_wifi.h" #include "emotibit.h" #include "enophone.h" @@ -102,6 +104,12 @@ int prepare_session (int board_id, const char *json_brainflow_input_params) std::shared_ptr board = NULL; switch (static_cast (board_id)) { + case BoardIds::EXPANDABLE_EEG_32_WIFI_BOARD: + board = std::shared_ptr (new ExpandableEeg32Wifi (params)); + break; + case BoardIds::EXPANDABLE_EEG_32_BOARD: + board = std::shared_ptr (new ExpandableEeg32 (params)); + break; case BoardIds::PLAYBACK_FILE_BOARD: board = std::shared_ptr (new PlaybackFileBoard (params)); break; diff --git a/src/board_controller/brainflow_boards.cpp b/src/board_controller/brainflow_boards.cpp index 9493e3f9a..eec145177 100644 --- a/src/board_controller/brainflow_boards.cpp +++ b/src/board_controller/brainflow_boards.cpp @@ -1217,6 +1217,40 @@ BrainFlowBoards::BrainFlowBoards() {"battery_channel", 16}, {"other_channels", {17}} }; + + brainflow_boards_json["boards"]["69"]["default"] = + { + {"name", "ExpandableEeg32Wifi"}, + {"sampling_rate", 250}, + {"package_num_channel", 0}, + {"timestamp_channel", 46}, + {"marker_channel", 47}, + {"num_rows", 48}, + {"eeg_channels", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}}, + {"emg_channels", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}}, + {"ecg_channels", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}}, + {"eog_channels", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}}, + {"accel_channels", {33, 34, 35}}, + {"analog_channels", {43, 44, 45}}, + {"other_channels", {36, 37, 38, 39, 40, 41, 42}} + }; + + brainflow_boards_json["boards"]["70"]["default"] = + { + {"name", "ExpandableEeg32"}, + {"sampling_rate", 250}, + {"package_num_channel", 0}, + {"timestamp_channel", 46}, + {"marker_channel", 47}, + {"num_rows", 48}, + {"eeg_channels", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}}, + {"emg_channels", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}}, + {"ecg_channels", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}}, + {"eog_channels", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}}, + {"accel_channels", {33, 34, 35}}, + {"analog_channels", {43, 44, 45}}, + {"other_channels", {36, 37, 38, 39, 40, 41, 42}} + }; } BrainFlowBoards boards_struct; diff --git a/src/board_controller/build.cmake b/src/board_controller/build.cmake index f3fb0d790..9da628722 100644 --- a/src/board_controller/build.cmake +++ b/src/board_controller/build.cmake @@ -42,6 +42,8 @@ SET (BOARD_CONTROLLER_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/openbci/openbci_wifi_shield_board.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/openbci/ganglion_wifi.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/openbci/cyton_wifi.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/openbci/expandable_eeg32_wifi.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/openbci/expandable_eeg32.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/openbci/cyton_daisy_wifi.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/openbci/ganglion.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/openbci/ganglion_native.cpp diff --git a/src/board_controller/openbci/expandable_eeg32.cpp b/src/board_controller/openbci/expandable_eeg32.cpp new file mode 100644 index 000000000..d82472efa --- /dev/null +++ b/src/board_controller/openbci/expandable_eeg32.cpp @@ -0,0 +1,199 @@ +#include + +#include "custom_cast.h" +#include "expandable_eeg32.h" +#include "serial.h" +#include "timestamp.h" + +#define START_BYTE 0xA0 +#define END_BYTE_STANDARD 0xC0 +#define END_BYTE_ANALOG 0xC1 +#define END_BYTE_MAX 0xC6 +#define NUM_BANK_PACKETS 4 + + +int ExpandableEeg32::config_board (std::string conf, std::string &response) +{ + if (gain_tracker.apply_config (conf) == (int)OpenBCICommandTypes::INVALID_COMMAND) + { + safe_logger (spdlog::level::warn, "invalid command: {}", conf.c_str ()); + return (int)BrainFlowExitCodes::INVALID_ARGUMENTS_ERROR; + } + int res = OpenBCISerialBoard::config_board (conf, response); + if (res != (int)BrainFlowExitCodes::STATUS_OK) + { + gain_tracker.revert_config (); + } + return res; +} + +void ExpandableEeg32::read_thread () +{ + // 4 consecutive 33-byte Cyton packets -> one 32-ch BrainFlow row (same layout as WiFi). + // Firmware may send either: + // A) same sample_id x4 (like WiFi 32ch / SD 32ch), or + // B) sequential ids (0,1,2,3,4,5,6,7,...) as a Daisy-style extension. + // Resync: if the next id is neither "same as first" nor "first+seq", start a new group. + int res; + unsigned char b[32]; + double accel[3] = {0.}; + int analog[3] = {0}; + int analog_count = 0; + int accel_count = 0; + int aux_count = 0; + int sequence_count = 0; + unsigned char raw_ids[NUM_BANK_PACKETS] = {0}; + unsigned char raw_ends[NUM_BANK_PACKETS] = {0}; + int num_rows = board_descr["default"]["num_rows"]; + double *package = new double[num_rows]; + for (int i = 0; i < num_rows; i++) + { + package[i] = 0.0; + } + double accel_scale = (double)(0.002 / (pow (2, 4))); + + while (keep_alive) + { + res = serial->read_from_serial_port (b, 1); + if (res != 1) + { + safe_logger (spdlog::level::debug, "unable to read 1 byte"); + continue; + } + if (b[0] != START_BYTE) + { + continue; + } + + int remaining_bytes = 32; + int pos = 0; + while ((remaining_bytes > 0) && (keep_alive)) + { + res = serial->read_from_serial_port (b + pos, remaining_bytes); + remaining_bytes -= res; + pos += res; + } + if (!keep_alive) + { + break; + } + + if ((b[31] < END_BYTE_STANDARD) || (b[31] > END_BYTE_MAX)) + { + safe_logger (spdlog::level::warn, "Wrong end byte {}", b[31]); + continue; + } + + unsigned char sample_id = b[0]; + if (sequence_count > 0) + { + unsigned char first_id = raw_ids[0]; + unsigned char expect_same = first_id; + unsigned char expect_seq = (unsigned char)((first_id + sequence_count) & 0xFF); + if ((sample_id != expect_same) && (sample_id != expect_seq)) + { + safe_logger (spdlog::level::debug, + "32ch serial resync: group_len={} first_id={} got={}", sequence_count, + (int)first_id, (int)sample_id); + sequence_count = 0; + } + } + + if (sequence_count == 0) + { + for (int i = 0; i < num_rows; i++) + { + package[i] = 0.0; + } + package[board_descr["default"]["package_num_channel"].get ()] = (double)sample_id; + aux_count = 0; + analog_count = 0; + accel_count = 0; + analog[0] = analog[1] = analog[2] = 0; + accel[0] = accel[1] = accel[2] = 0.; + } + + int bank = sequence_count; + raw_ids[bank] = sample_id; + raw_ends[bank] = b[31]; + + for (int i = 0; i < 8; i++) + { + int gain_index = bank * 8 + i; + double eeg_scale = (double)(4.5 / float ((pow (2, 23) - 1)) / + gain_tracker.get_gain_for_channel (gain_index) * 1000000.); + package[i + 1 + bank * 8] = eeg_scale * cast_24bit_to_int32 (b + 1 + 3 * i); + } + + package[37] += (double)b[25]; + package[38] += (double)b[26]; + package[39] += (double)b[27]; + package[40] += (double)b[28]; + package[41] += (double)b[29]; + package[42] += (double)b[30]; + aux_count++; + + if (b[31] == END_BYTE_STANDARD) + { + int32_t accel_temp[3] = {0}; + accel_temp[0] = cast_16bit_to_int32 (b + 25); + accel_temp[1] = cast_16bit_to_int32 (b + 27); + accel_temp[2] = cast_16bit_to_int32 (b + 29); + if (accel_temp[0] != 0) + { + if (accel_count == 0) + { + accel[0] = accel_scale * accel_temp[0]; + accel[1] = accel_scale * accel_temp[1]; + accel[2] = accel_scale * accel_temp[2]; + } + else + { + accel[0] += accel_scale * accel_temp[0]; + accel[1] += accel_scale * accel_temp[1]; + accel[2] += accel_scale * accel_temp[2]; + } + accel_count++; + } + package[33] = (accel_count > 0) ? (accel[0] / accel_count) : accel[0]; + package[34] = (accel_count > 0) ? (accel[1] / accel_count) : accel[1]; + package[35] = (accel_count > 0) ? (accel[2] / accel_count) : accel[2]; + } + + if (b[31] == END_BYTE_ANALOG) + { + analog[0] += cast_16bit_to_int32 (b + 25); + analog[1] += cast_16bit_to_int32 (b + 27); + analog[2] += cast_16bit_to_int32 (b + 29); + analog_count++; + package[43] = (analog_count > 0) ? (analog[0] / (double)analog_count) : 0.0; + package[44] = (analog_count > 0) ? (analog[1] / (double)analog_count) : 0.0; + package[45] = (analog_count > 0) ? (analog[2] / (double)analog_count) : 0.0; + } + + sequence_count++; + if (sequence_count == NUM_BANK_PACKETS) + { + if (aux_count > 0) + { + package[37] /= (double)aux_count; + package[38] /= (double)aux_count; + package[39] /= (double)aux_count; + package[40] /= (double)aux_count; + package[41] /= (double)aux_count; + package[42] /= (double)aux_count; + } + // Overlay 4 raw sample_ids into other_channels 37-40 for the test tool. + // Aux averages remain in 41-42 (partial). End byte of last sub-packet -> 36. + package[36] = (double)raw_ends[3]; + package[37] = (double)raw_ids[0]; + package[38] = (double)raw_ids[1]; + package[39] = (double)raw_ids[2]; + package[40] = (double)raw_ids[3]; + package[board_descr["default"]["timestamp_channel"].get ()] = get_timestamp (); + push_package (package); + sequence_count = 0; + } + } + delete[] package; +} diff --git a/src/board_controller/openbci/expandable_eeg32_wifi.cpp b/src/board_controller/openbci/expandable_eeg32_wifi.cpp new file mode 100644 index 000000000..c0449bdd9 --- /dev/null +++ b/src/board_controller/openbci/expandable_eeg32_wifi.cpp @@ -0,0 +1,240 @@ +#include "expandable_eeg32_wifi.h" +#include "custom_cast.h" +#include "timestamp.h" + +#ifndef _WIN32 +#include +#endif + +#define START_BYTE 0xA0 +#define END_BYTE_STANDARD 0xC0 +#define END_BYTE_ANALOG 0xC1 +#define END_BYTE_MAX 0xC6 + +std::string ExpandableEeg32Wifi::translate_user_config_to_device (const std::string &conf) +{ + // Ch 1-16: native OpenBCI symbols. Ch 17-32: second-bank A-L / a-l per board spec. + // Replace with a mapping table if your firmware uses different wire codes. + return conf; +} + +// load default settings for cyton boards +int ExpandableEeg32Wifi::prepare_session () +{ + int res = OpenBCIWifiShieldBoard::prepare_session (); + if (res != (int)BrainFlowExitCodes::STATUS_OK) + { + return res; + } + return send_config ("d"); +} + +int ExpandableEeg32Wifi::config_board (std::string conf, std::string &response) +{ + std::string wire_config = translate_user_config_to_device (conf); + if (gain_tracker.apply_config (wire_config) == (int)OpenBCICommandTypes::INVALID_COMMAND) + { + safe_logger (spdlog::level::warn, "invalid command: {}", conf.c_str ()); + return (int)BrainFlowExitCodes::INVALID_ARGUMENTS_ERROR; + } + int res = OpenBCIWifiShieldBoard::config_board (wire_config, response); + if (res != (int)BrainFlowExitCodes::STATUS_OK) + { + gain_tracker.revert_config (); + } + return res; +} + +void ExpandableEeg32Wifi::read_thread () +{ + // format is the same as for cyton but need to join two packages together + /* + Byte 1: 0xA0 + Byte 2: Sample Number + Bytes 3-5: Data value for EEG channel 1 + Bytes 6-8: Data value for EEG channel 2 + Bytes 9-11: Data value for EEG channel 3 + Bytes 12-14: Data value for EEG channel 4 + Bytes 15-17: Data value for EEG channel 5 + Bytes 18-20: Data value for EEG channel 6 + Bytes 21-23: Data value for EEG channel 6 + Bytes 24-26: Data value for EEG channel 8 + Aux Data Bytes 27-32: 6 bytes of data + Byte 33: 0xCX where X is 0-F in hex + */ + int res; + unsigned char b[OpenBCIWifiShieldBoard::package_size]; + int num_rows = board_descr["default"]["num_rows"]; + double *package = new double[num_rows]; + for (int i = 0; i < num_rows; i++) + { + package[i] = 0.0; + } + bool first_sample = true; + double accel[3] = {0.}; + unsigned char last_sample_id = 0; + double accel_scale = (double)(0.002 / (pow (2, 4))); + int sequence_count = 0; + + while (keep_alive) + { + res = server_socket->recv (b, OpenBCIWifiShieldBoard::package_size); + if (res != OpenBCIWifiShieldBoard::package_size) + { + if (res < 0) + { +#ifdef _WIN32 + safe_logger (spdlog::level::warn, "WSAGetLastError is {}", WSAGetLastError ()); +#else + safe_logger (spdlog::level::warn, "errno {} message {}", errno, strerror (errno)); +#endif + } + + continue; + } + + if (b[0] != START_BYTE) + { + continue; + } + unsigned char *bytes = b + 1; // for better consistency between plain cyton and wifi, in + // plain cyton index is shifted by 1 + + if ((bytes[31] < END_BYTE_STANDARD) || (bytes[31] > END_BYTE_MAX)) + { + safe_logger (spdlog::level::warn, "Wrong end byte {}", bytes[31]); + continue; + } + + + if (last_sample_id != bytes[0]) + { + first_sample = true; + sequence_count = 0; + } + last_sample_id = bytes[0]; + + // place unprocessed bytes to other_channels for all modes + // if (first_sample) + // { + package[0] = (double)bytes[0]; + // eeg + for (int i = 0; i < 8; i++) + { + int gain_index = sequence_count * 8 + i; + double eeg_scale = (double)(4.5 / float ((pow (2, 23) - 1)) / + gain_tracker.get_gain_for_channel (gain_index) * 1000000.); + package[i + 1 + sequence_count * 8] = + eeg_scale * cast_24bit_to_int32 (bytes + 1 + 3 * i); + } + // other_channels + // package[21] = (double)bytes[25]; + // package[22] = (double)bytes[26]; + // package[23] = (double)bytes[27]; + // package[24] = (double)bytes[28]; + // package[25] = (double)bytes[29]; + // package[26] = (double)bytes[30]; + // } + // else + // { + // // eeg + // for (int i = 0; i < 8; i++) + // { + // double eeg_scale = (double)(4.5 / float ((pow (2, 23) - 1)) / + // gain_tracker.get_gain_for_channel (i + 8) * 1000000.); + // package[i + 9] = eeg_scale * cast_24bit_to_int32 (bytes + 1 + 3 * i); + // } + // need to average other_channels + package[37] += (double)bytes[25]; + package[38] += (double)bytes[28]; + package[39] += (double)bytes[27]; + package[40] += (double)bytes[28]; + package[41] += (double)bytes[29]; + package[42] += (double)bytes[30]; + package[37] /= 2.0; + package[38] /= 2.0; + package[39] /= 2.0; + package[40] /= 2.0; + package[41] /= 2.0; + package[42] /= 2.0; + package[36] = (double)bytes[31]; + // } + + // place processed accel data + if (bytes[31] == END_BYTE_STANDARD) + { + int32_t accel_temp[3] = {0}; + accel_temp[0] = cast_16bit_to_int32 (bytes + 25); + accel_temp[1] = cast_16bit_to_int32 (bytes + 27); + accel_temp[2] = cast_16bit_to_int32 (bytes + 29); + + if (first_sample) + { + package[0] = (double)bytes[0]; + + // accel + if (accel_temp[0] != 0) + { + accel[0] = accel_scale * accel_temp[0]; + accel[1] = accel_scale * accel_temp[1]; + accel[2] = accel_scale * accel_temp[2]; + } + } + else + { + // need to average accel data + if (accel_temp[0] != 0) + { + accel[0] += accel_scale * accel_temp[0]; + accel[1] += accel_scale * accel_temp[1]; + accel[2] += accel_scale * accel_temp[2]; + + accel[0] /= 2.f; + accel[1] /= 2.f; + accel[2] /= 2.f; + } + + package[36] = (double)bytes[31]; + } + + package[33] = accel[0]; + package[34] = accel[1]; + package[35] = accel[2]; + } + // place processed analog data + if (bytes[31] == END_BYTE_ANALOG) + { + if (first_sample) + { + package[0] = (double)bytes[0]; + // analog + package[43] = cast_16bit_to_int32 (bytes + 25); + package[44] = cast_16bit_to_int32 (bytes + 27); + package[45] = cast_16bit_to_int32 (bytes + 29); + } + else + { + // need to average analog data + package[43] += cast_16bit_to_int32 (bytes + 25); + package[44] += cast_16bit_to_int32 (bytes + 27); + package[45] += cast_16bit_to_int32 (bytes + 29); + package[43] /= (float)(sequence_count + 1); + package[44] /= (float)(sequence_count + 1); + package[45] /= (float)(sequence_count + 1); + package[36] = (double)bytes[31]; // cyton end byte + } + } + // commit package (4 WiFi frames = 32 EEG channels for this board_id) + sequence_count++; + if (4 == sequence_count) + { + package[board_descr["default"]["timestamp_channel"].get ()] = get_timestamp (); + push_package (package); + first_sample = false; + // Must reset before next frame: otherwise same sample_id could yield gain_index 32..39 + // and debug STL asserts on current_gains[gain_index]. + sequence_count = 0; + } + } + delete[] package; +} diff --git a/src/board_controller/openbci/inc/expandable_eeg32.h b/src/board_controller/openbci/inc/expandable_eeg32.h new file mode 100644 index 000000000..e2a30ead8 --- /dev/null +++ b/src/board_controller/openbci/inc/expandable_eeg32.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include + +#include "expandable_eeg32_wifi_gain_tracker.h" +#include "openbci_serial_board.h" + +class ExpandableEeg32 : public OpenBCISerialBoard +{ +protected: + ExpandableEeg32GainTracker gain_tracker; + + void read_thread (); + +public: + ExpandableEeg32 (struct BrainFlowInputParams params) + : OpenBCISerialBoard (params, (int)BoardIds::EXPANDABLE_EEG_32_BOARD) + { + } + + int config_board (std::string config, std::string &response); +}; diff --git a/src/board_controller/openbci/inc/expandable_eeg32_wifi.h b/src/board_controller/openbci/inc/expandable_eeg32_wifi.h new file mode 100644 index 000000000..3374cf029 --- /dev/null +++ b/src/board_controller/openbci/inc/expandable_eeg32_wifi.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +#include "expandable_eeg32_wifi_gain_tracker.h" +#include "openbci_wifi_shield_board.h" + +class ExpandableEeg32Wifi : public OpenBCIWifiShieldBoard +{ +protected: + ExpandableEeg32WifiGainTracker gain_tracker; + + void read_thread (); + + /** Map user symbols to wire protocol if needed; currently passthrough. */ + static std::string translate_user_config_to_device (const std::string &conf); + +public: + // 32 EEG rows per merged packet; see brainflow_boards ExpandableEeg32Wifi + ExpandableEeg32Wifi (struct BrainFlowInputParams params) + : OpenBCIWifiShieldBoard (params, (int)BoardIds::EXPANDABLE_EEG_32_WIFI_BOARD) + { + } + + int prepare_session (); + int config_board (std::string config, std::string &response); +}; diff --git a/src/board_controller/openbci/inc/expandable_eeg32_wifi_gain_tracker.h b/src/board_controller/openbci/inc/expandable_eeg32_wifi_gain_tracker.h new file mode 100644 index 000000000..660dc0a29 --- /dev/null +++ b/src/board_controller/openbci/inc/expandable_eeg32_wifi_gain_tracker.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +#include "openbci_gain_tracker.h" + +/** + * Gain / x-command channel letters for EXPANDABLE_EEG_32_BOARD and + * EXPANDABLE_EEG_32_WIFI_BOARD. + * + * Ch 1-16: same Cyton+Daisy letters as OpenBCIGainTracker (1-8, QWERTYUI for on / impedance; + * !@#$%^& and qwertyui for single-char off on the wire per OpenBCI docs). + * Ch 17-32: A S D F G H J K Z X C V B N M L (on / impedance); a s d f g h j k z x c v b n m l + * (off). + */ +class ExpandableEeg32GainTracker : public OpenBCIGainTracker +{ +public: + ExpandableEeg32GainTracker () : OpenBCIGainTracker (std::vector (32, 24)) + { + channel_letters = std::vector {'1', '2', '3', '4', '5', '6', '7', '8', 'Q', 'W', 'E', + 'R', 'T', 'Y', 'U', 'I', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'Z', 'X', 'C', 'V', + 'B', 'N', 'M', 'L'}; + } + + int apply_config (std::string config) override + { + if (config.size () == 1) + { + if (config.at (0) == 'd') + { + std::copy (current_gains.begin (), current_gains.end (), old_gains.begin ()); + std::fill (current_gains.begin (), current_gains.end (), 24); + } + } + + return OpenBCIGainTracker::apply_config (config); + } +}; + +using ExpandableEeg32WifiGainTracker = ExpandableEeg32GainTracker; diff --git a/src/utils/inc/brainflow_constants.h b/src/utils/inc/brainflow_constants.h index 8b31b0df2..b8cdd0339 100644 --- a/src/utils/inc/brainflow_constants.h +++ b/src/utils/inc/brainflow_constants.h @@ -97,9 +97,11 @@ enum class BoardIds : int NEUROPAWN_KNIGHT_BOARD_IMU = 66, MUSE_S_ATHENA_BOARD = 67, SHIMMER3_BOARD = 68, + EXPANDABLE_EEG_32_WIFI_BOARD = 69, + EXPANDABLE_EEG_32_BOARD = 70, // use it to iterate FIRST = PLAYBACK_FILE_BOARD, - LAST = SHIMMER3_BOARD + LAST = EXPANDABLE_EEG_32_BOARD }; enum class IpProtocolTypes : int From aa6f34601fdf364d4aef0837b1e495d1ba4414f1 Mon Sep 17 00:00:00 2001 From: leorangessi <2673755910@qq.com> Date: Thu, 12 Nov 2026 20:05:31 +0800 Subject: [PATCH 2/2] Preserve ExpandableEEG32 serial command framing --- .../openbci/openbci_serial_board.cpp | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/board_controller/openbci/openbci_serial_board.cpp b/src/board_controller/openbci/openbci_serial_board.cpp index c7e6556a4..8634a6bbf 100644 --- a/src/board_controller/openbci/openbci_serial_board.cpp +++ b/src/board_controller/openbci/openbci_serial_board.cpp @@ -73,9 +73,14 @@ int OpenBCISerialBoard::config_board (std::string config, std::string &response) int OpenBCISerialBoard::send_to_board (const char *msg) { - int length = (int)strlen (msg); + std::string command (msg); + if (board_id == (int)BoardIds::EXPANDABLE_EEG_32_BOARD) + { + command += '\n'; + } + int length = (int)command.size (); safe_logger (spdlog::level::debug, "sending {} to the board", msg); - int res = serial->send_to_serial_port ((const void *)msg, length); + int res = serial->send_to_serial_port (command.data (), length); if (res != length) { return (int)BrainFlowExitCodes::BOARD_WRITE_ERROR; @@ -86,9 +91,14 @@ int OpenBCISerialBoard::send_to_board (const char *msg) int OpenBCISerialBoard::send_to_board (const char *msg, std::string &response) { - int length = (int)strlen (msg); + std::string command (msg); + if (board_id == (int)BoardIds::EXPANDABLE_EEG_32_BOARD) + { + command += '\n'; + } + int length = (int)command.size (); safe_logger (spdlog::level::debug, "sending {} to the board", msg); - int res = serial->send_to_serial_port ((const void *)msg, length); + int res = serial->send_to_serial_port (command.data (), length); if (res != length) { response = ""; @@ -264,6 +274,11 @@ int OpenBCISerialBoard::start_stream (int buffer_size, const char *streamer_para return res; } + if (board_id == (int)BoardIds::EXPANDABLE_EEG_32_BOARD) + { + serial->flush_buffer (); + } + // start streaming int send_res = send_to_board ("b"); if (send_res != (int)BrainFlowExitCodes::STATUS_OK)