diff --git a/.gitignore b/.gitignore index 3ee526e..6b72310 100644 --- a/.gitignore +++ b/.gitignore @@ -24,9 +24,10 @@ settings.local.json # misc .codegraph/ delay_capture*/ +/hardware_captures/ # Audio latency test outputs (large XDF recordings, plots, CLI logs) scripts/audio_latency_test/recordings/ # Python cache -__pycache__/ \ No newline at end of file +__pycache__/ diff --git a/README.md b/README.md index ea7b91a..f723400 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,8 @@ sudo dnsmasq -d --port=0 --interface=en10 --bind-interfaces \ `--port=0` disables dnsmasq's DNS server, so it only hands out the one address; `-d` keeps it in the foreground (Ctrl+C stops it). The amplifier picks the lease up within a minute, without a restart, and it must be running whenever the amplifier powers up. +A DHCP-only example for an isolated amplifier link is provided in `scripts/na500_dhcp.conf`. Set the adapter to `10.10.10.61/24` and update the example's interface (`en10`) to match your adapter. On macOS with Homebrew, run `sudo /opt/homebrew/sbin/dnsmasq --no-daemon --conf-file="$PWD/scripts/na500_dhcp.conf"` from the repository root and leave it running during testing. It leases `10.10.10.62` and advertises neither a gateway nor a DNS server. + Differences from the NA400 that this app handles automatically: - **Scaling**: 0.044703 µV/bit (±375 mV over 24 bits, matching the GES 500 datasheet and Net Station 6). @@ -154,6 +156,7 @@ Differences from the NA400 that this app handles automatically: - **Front end**: the NA500's EEG reads full scale until its buffered reference is switched on, every `cmd_Stop` switches it off, and switch commands sent within ~20 ms of power-on are lost; the app waits briefly after power-on and enables the buffered reference before each `cmd_Start`. - **Physio16**: the NA500 never reports whether a Physio16 is attached, so the app always streams its 16 physio channels (PIB1-16) after the EEG. Physio gains persist on the amplifier, so the app sets them to 12, the power-on default, before each start; the physio is then scaled like the EEG (±375 mV range) and needs no realignment delay. - **Triggers**: the app enables the NA500's DB9 digital inputs (without that they read as all 16 active) and its BNC input. Each rising edge on BNC in appears in the `_DIN` stream as bit 16 (value `0x10000`) for 1 ms, alongside the 16 DB9 bits. The EEG trails a BNC-in event by about 1.5 samples (the ADC filter's delay); no correction is applied, as in Net Station. +- **BNC input blanking**: the connector defaults to TMS blanking (mode 2), which also creates input events. At stream setup it sends `cmd_SetBlankingPulseWidth` = 1000 µs before `cmd_SetBncInMode` = 2, including when joining an already-running amplifier; reinitialization reapplies both. Blanking stays enabled between pulses. Mode and width are fixed in the connector, with no additional setting required. Modes 0, 1 and 3 disable blanking. Setup fails if either command is rejected. The mock preserves BNC events in mode 2 but does not simulate analog EEG gating. - **BNC output trigger**: the GUI's *BNC Trigger* button (enabled while linked to an NA500) and the remote control `trigger` command send a TTL pulse (0 to 5 V) on the BNC output: 1 ms by default, or 100-1600 µs via `trigger `. The amplifier makes each pulse about 6.7% longer than set (a 1 ms setting measures 1.07 ms); the app sends the width as is, as Net Station does. Cable BNC out to BNC in to see each pulse in the `_DIN` stream. The mock (`--amp-type NA500`) loops its BNC output back to its BNC input. - **Clock**: the NA500 stamps packets with its own clock, which is not synchronized; the app sets it with `cmd_SetAmpTime` at power-on, as Net Station does. - **Single client**: while Net Station (or any other client) is linked to the NA500, this app's connections are accepted but not serviced — and vice versa. Unlink Net Station before using this app; concurrent monitoring is not possible on the NA500 (unlike the NA400). diff --git a/docs/NA500_AmpServer.md b/docs/NA500_AmpServer.md index 1eafa84..e957092 100644 --- a/docs/NA500_AmpServer.md +++ b/docs/NA500_AmpServer.md @@ -139,3 +139,62 @@ lost if its command is sent the instant the notification port connects, before t buffered; the gap shows in the packet counter. Read the data port continuously. - With no net attached the net code is 255. Digital inputs read 0 until `cmd_SetDinEnable`, then idle at `0xFFFF` (active low). The first reserved byte read 3 at idle on the unit we measured. + +## BNC input blanking + +The FPGA needs `cmd_SetBlankingPulseWidth` (100–1600 µs) before +`cmd_SetBncInMode` = 2 to enable TMS blanking. Modes 0, 1 and 3 disable it. +Mode 2 remains armed between pulses and still produces BNC input events +(bit 2 of the first reserved byte, exposed by the connector as DIN bit 16). +The connector applies a fixed default of 1000 µs and mode 2 during stream setup, +including when joining an already-running amplifier, and after reinitialization. + +### Hardware comparison, 2026-11-15 + +Tested serial 0001 (firmware 0.4.9, FPGA 0.6.1.f0, PCB 4.1.0.0) with BNC OUT +cabled to BNC IN, open EEG inputs, and no external signal source. Recorded all +256 EEG channels at 4000 Hz native, without LSL processing. In each recording, +the mode sequence was 1 → 2 → 2 → 1; output pulses stayed at a 1000 µs setting, +spaced 0.5 seconds apart. The blanking width was sent before each mode change. + +| Blanking width | Mode 1 input events | Mode 2 input events | +|---|---:|---:| +| 1000 µs | 40/40 | 40/40 | +| 1600 µs | 20/20 | 20/20 | + +All comparison blocks had contiguous packet counters and 250 µs timestamp +increments. None of the 120 analyzed event windows showed EEG saturation. +Mode 1 stayed near its roughly 1 µV background variation. Mode 2 produced a +repeatable transient, with the median absolute EEG response across channels and +events peaking around 1 mV at +0.5 ms. The later portion of the response moved +later at 1600 µs, while the output pulse width stayed unchanged. The effect +appeared in both mode-2 blocks and disappeared on return to mode 1. + +![Mode 1 versus mode 2 at two blanking widths](measurements/na500_bnc_blanking_20261115.png) + +These measurements demonstrate a width-dependent response in the EEG hardware +path and preserved input events. The open-input waveform is a switching +transient; this does not establish suppression of a known input signal or TMS +artifact. Its duration must not be interpreted as the exact analog gate width. +A driven-input test or direct gate measurement is still needed for those checks. + +The [measurement summary](measurements/na500_bnc_blanking_20261115.json) includes +per-block event counts and continuity checks. To repeat the experiment, unlink +other AmpServer clients and run from the repository root: + +```bash +python scripts/bnc_blanking_capture.py --host 10.10.10.62 \ + --out hardware_captures/bnc-1000us +python scripts/bnc_blanking_analyze.py hardware_captures/bnc-1000us +python scripts/bnc_blanking_capture.py --host 10.10.10.62 --width 1600 --pulses 10 \ + --out hardware_captures/bnc-1600us +python scripts/bnc_blanking_analyze.py hardware_captures/bnc-1600us +``` + +The capture utility saves complete raw PacketFormat2 payloads, command replies, +notifications and block boundaries. Analysis saves event epochs, metrics and a +plot; it needs NumPy and Matplotlib from `scripts/requirements.txt`. Acquisition +is stopped and powered down after capture. The last test width and mode 2 are +programmed before stopping; the connector reapplies its 1000 µs default on the +next stream setup. Large local recordings under `hardware_captures/` are ignored +by Git. diff --git a/docs/measurements/na500_bnc_blanking_20261115.json b/docs/measurements/na500_bnc_blanking_20261115.json new file mode 100644 index 0000000..4258e97 --- /dev/null +++ b/docs/measurements/na500_bnc_blanking_20261115.json @@ -0,0 +1,202 @@ +[ + { + "amplifier_details": "(sendCommand_return (status complete) (amp_details (serial_number 0001) (amp_type NA500) (legacy_board false) (packet_format 2) (system_version 0.4.9) (fpga_version 0.6.1.f0) (pcb_version 4.1.0.0) (number_of_channels 256) (feature_flags 0))", + "complete": true, + "capture_errors": [], + "sample_count": 196456, + "bytes": 248320384, + "requested_rate_hz": 4000, + "blocks": [ + { + "block": 1, + "mode": 1, + "sent": 20, + "events": 20, + "samples": 44272, + "usable_epochs": 20, + "gate_normalized_increment": 1.0341614906832297, + "counter_discontinuities": 0, + "median_timestamp_step_us": 250.0, + "timestamp_discontinuities": 0 + }, + { + "block": 2, + "mode": 2, + "sent": 20, + "events": 20, + "samples": 44216, + "usable_epochs": 20, + "gate_normalized_increment": 265.86692176870747, + "counter_discontinuities": 0, + "median_timestamp_step_us": 250.0, + "timestamp_discontinuities": 0 + }, + { + "block": 3, + "mode": 2, + "sent": 20, + "events": 20, + "samples": 44248, + "usable_epochs": 20, + "gate_normalized_increment": 269.9619584675976, + "counter_discontinuities": 0, + "median_timestamp_step_us": 250.0, + "timestamp_discontinuities": 0 + }, + { + "block": 4, + "mode": 1, + "sent": 20, + "events": 20, + "samples": 44216, + "usable_epochs": 20, + "gate_normalized_increment": 0.9853896103896103, + "counter_discontinuities": 0, + "median_timestamp_step_us": 250.0, + "timestamp_discontinuities": 0 + } + ], + "usable_epochs": 80, + "useful_channels": 256, + "plotted_channel": 231, + "overall_epoch_rail_fraction": 0.0, + "modes": { + "1": { + "events": 40, + "median_baseline_abs_increment_counts": 22.0, + "gate_0_5_to_2ms_normalized_increment_median": 1.0, + "gate_0_5_to_2ms_normalized_increment_q25_q75": [ + 0.9143668831168831, + 1.1358901515151516 + ], + "gate_exact_repeat_fraction": 0.013671875, + "baseline_exact_repeat_fraction": 0.013568239795918367 + }, + "2": { + "events": 40, + "median_baseline_abs_increment_counts": 21.0, + "gate_0_5_to_2ms_normalized_increment_median": 265.86692176870747, + "gate_0_5_to_2ms_normalized_increment_q25_q75": [ + 171.7729591836735, + 305.0119047619048 + ], + "gate_exact_repeat_fraction": 0.0001255580357142857, + "baseline_exact_repeat_fraction": 0.014198022959183673 + } + }, + "absolute_response": { + "1": { + "peak_of_median_absolute_eeg_uv": 0.9748096368750749, + "peak_time_ms": 5.75, + "median_abs_baseline_uv": 0.8516469780279666, + "last_time_median_response_exceeds_5uv_ms": null + }, + "2": { + "peak_of_median_absolute_eeg_uv": 988.5304132286383, + "peak_time_ms": 0.5, + "median_abs_baseline_uv": 0.8240494192862995, + "last_time_median_response_exceeds_5uv_ms": 2.0 + } + } + }, + { + "amplifier_details": "(sendCommand_return (status complete) (amp_details (serial_number 0001) (amp_type NA500) (legacy_board false) (packet_format 2) (system_version 0.4.9) (fpga_version 0.6.1.f0) (pcb_version 4.1.0.0) (number_of_channels 256) (feature_flags 0))", + "complete": true, + "capture_errors": [], + "sample_count": 115992, + "bytes": 146613888, + "requested_rate_hz": 4000, + "blocks": [ + { + "block": 1, + "mode": 1, + "sent": 10, + "events": 10, + "samples": 24144, + "usable_epochs": 10, + "gate_normalized_increment": 1.0050112930547714, + "counter_discontinuities": 0, + "median_timestamp_step_us": 250.0, + "timestamp_discontinuities": 0 + }, + { + "block": 2, + "mode": 2, + "sent": 10, + "events": 10, + "samples": 24136, + "usable_epochs": 10, + "gate_normalized_increment": 226.27023809523808, + "counter_discontinuities": 0, + "median_timestamp_step_us": 250.0, + "timestamp_discontinuities": 0 + }, + { + "block": 3, + "mode": 2, + "sent": 10, + "events": 10, + "samples": 24072, + "usable_epochs": 10, + "gate_normalized_increment": 267.8337585034013, + "counter_discontinuities": 0, + "median_timestamp_step_us": 250.0, + "timestamp_discontinuities": 0 + }, + { + "block": 4, + "mode": 1, + "sent": 10, + "events": 10, + "samples": 24144, + "usable_epochs": 10, + "gate_normalized_increment": 1.0616883116883118, + "counter_discontinuities": 0, + "median_timestamp_step_us": 250.0, + "timestamp_discontinuities": 0 + } + ], + "usable_epochs": 40, + "useful_channels": 256, + "plotted_channel": 231, + "overall_epoch_rail_fraction": 0.0, + "modes": { + "1": { + "events": 20, + "median_baseline_abs_increment_counts": 22.0, + "gate_0_5_to_2ms_normalized_increment_median": 1.0553359683794468, + "gate_0_5_to_2ms_normalized_increment_q25_q75": [ + 0.9318181818181819, + 1.1002628324056896 + ], + "gate_exact_repeat_fraction": 0.012388392857142856, + "baseline_exact_repeat_fraction": 0.01329719387755102 + }, + "2": { + "events": 20, + "median_baseline_abs_increment_counts": 20.5, + "gate_0_5_to_2ms_normalized_increment_median": 236.04183673469387, + "gate_0_5_to_2ms_normalized_increment_q25_q75": [ + 189.994489063568, + 304.6768707482993 + ], + "gate_exact_repeat_fraction": 0.0017578125, + "baseline_exact_repeat_fraction": 0.014182079081632652 + } + }, + "absolute_response": { + "1": { + "peak_of_median_absolute_eeg_uv": 1.0938668737606123, + "peak_time_ms": 1.5, + "median_abs_baseline_uv": 0.8641913229105427, + "last_time_median_response_exceeds_5uv_ms": null + }, + "2": { + "peak_of_median_absolute_eeg_uv": 1048.3299895208709, + "peak_time_ms": 0.5, + "median_abs_baseline_uv": 0.8188036023354046, + "last_time_median_response_exceeds_5uv_ms": 2.75 + } + } + } +] \ No newline at end of file diff --git a/docs/measurements/na500_bnc_blanking_20261115.png b/docs/measurements/na500_bnc_blanking_20261115.png new file mode 100644 index 0000000..0ff0035 Binary files /dev/null and b/docs/measurements/na500_bnc_blanking_20261115.png differ diff --git a/mock/include/NA500Server.h b/mock/include/NA500Server.h index 3848df8..6ae80cd 100644 --- a/mock/include/NA500Server.h +++ b/mock/include/NA500Server.h @@ -54,7 +54,7 @@ class NA500Server { std::atomic stopping_{false}; std::atomic streaming_{false}; std::atomic dinEnabled_{false}; - std::atomic bncInEvents_{false}; // cmd_SetBncInMode 1; reset when the session ends + std::atomic bncInEvents_{false}; // cmd_SetBncInMode 1 or 2; reset when the session ends // BNC out: cmd_SetBncOutMode 1 (manual) arms cmd_SetTriggerBncManualOut; // reset when the session ends, like the BNC input. Each pulse is looped back to the BNC input, // as if a cable joined the two, so it shows up in the data stream. diff --git a/mock/src/NA500Server.cpp b/mock/src/NA500Server.cpp index 40a4727..57f4b9a 100644 --- a/mock/src/NA500Server.cpp +++ b/mock/src/NA500Server.cpp @@ -278,7 +278,7 @@ std::vector NA500Server::execute(const std::string& name, long long return {OK}; } if (name == "cmd_SetBncInMode") { - bncInEvents_ = value == 1; + bncInEvents_ = value == 1 || value == 2; return {OK}; } if (name == "cmd_SetBncOutMode") { @@ -382,9 +382,9 @@ void NA500Server::streamLoop() { // drive is on (the NA500 impedance state runs with it off). std::fill(std::begin(packet.eegData), std::end(packet.eegData), -8388608); } - // BNC in (event mode) reports a 1 ms event at each rising edge; the mock - // drives it from the test-jig pulse that also pulls DIN 1 low, and from - // BNC out pulses (looped back). + // BNC in (event or TMS blanking mode) reports a 1 ms event at each + // rising edge; the mock drives it from the test-jig pulse that also + // pulls DIN 1 low, and from BNC out pulses (looped back). const uint16_t din = packet.digitalInputs; const bool bncOutPulse = bncOutPulses_.exchange(0) > 0; if (bncInEvents_ && (((prevDin & 1) && !(din & 1)) || bncOutPulse)) { diff --git a/scripts/bnc_blanking_analyze.py b/scripts/bnc_blanking_analyze.py new file mode 100644 index 0000000..c6db58d --- /dev/null +++ b/scripts/bnc_blanking_analyze.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Analyze the raw capture from bnc_blanking_capture.py; retain event epochs.""" + +import argparse +import json +import os +import pathlib + +os.environ.setdefault('MPLCONFIGDIR', '/private/tmp/egi-bnc-matplotlib') +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt +import numpy as np + +PACKET = np.dtype(dict(names=['counter', 'timestamp', 'flags', 'eeg'], + formats=['= start + pre) & (edges < end - post)] + rows.append(dict(block=block['number'], mode=block['mode'], + sent=len(block['pulses']), events=len(found), samples=end-start)) + for edge in found: + idx = edge + offsets + # Exclude incomplete epochs rather than interpreting gaps as gating. + if not np.all(np.diff(packets['counter'][idx].astype(np.int64)) == 1): + continue + epochs.append(packets['eeg'][idx].copy()) + modes.append(block['mode']) + blocks.append(block['number']) + positions.append(int(edge)) + if not epochs: + raise RuntimeError(f'No usable BNC event epochs: {rows}') + epochs = np.asarray(epochs) + modes, blocks = np.asarray(modes), np.asarray(blocks) + baseline = (time_ms >= -15) & (time_ms <= -3) + rail = np.abs(epochs.astype(np.float64)) >= 8388000 + spread = np.median(np.std(epochs[:, baseline, :], axis=1), axis=0) + rail_fraction = rail.mean(axis=(0, 1)) + useful = (spread > 1) & (rail_fraction < .1) + selected = np.flatnonzero(useful) + if not selected.size: + selected = np.arange(256) + channel = int(selected[np.argmax(spread[selected])]) + x = epochs[:, :, selected].astype(np.float64) + dx = np.diff(x, axis=1) + dt = time_ms[1:] + baseline_d = (dt >= -15) & (dt <= -3) + gate_d = (dt >= .5) & (dt <= 2) + baseline_level = np.median(np.abs(dx[:, baseline_d, :]), axis=(1, 2)) + baseline_level = np.maximum(baseline_level, 1) + normalized = np.median(np.abs(dx), axis=2) / baseline_level[:, None] + zero = np.mean(dx == 0, axis=2) + summary = dict(amplifier_details=meta.get('amplifier_details'), + complete=meta.get('complete', False), capture_errors=meta['errors'], + sample_count=len(packets), bytes=(folder/'packets.bin').stat().st_size, + requested_rate_hz=rate, blocks=rows, usable_epochs=len(epochs), + useful_channels=int(useful.sum()), plotted_channel=channel+1, + overall_epoch_rail_fraction=float(rail.mean()), modes={}) + for mode in (1, 2): + keep = modes == mode + gate_per_event = np.mean(normalized[keep][:, gate_d], axis=1) + info = dict(events=int(keep.sum()), + median_baseline_abs_increment_counts=float(np.median(baseline_level[keep])), + gate_0_5_to_2ms_normalized_increment_median=float(np.median(gate_per_event)), + gate_0_5_to_2ms_normalized_increment_q25_q75=np.percentile(gate_per_event,[25,75]).tolist(), + gate_exact_repeat_fraction=float(zero[keep][:,gate_d].mean()), + baseline_exact_repeat_fraction=float(zero[keep][:,baseline_d].mean())) + summary['modes'][str(mode)] = info + for row in rows: + keep = blocks == row['block'] + row['usable_epochs'] = int(keep.sum()) + if keep.any(): + row['gate_normalized_increment'] = float(np.median(np.mean(normalized[keep][:,gate_d],axis=1))) + start = next(b['start_sample'] for b in meta['blocks'] if b['number']==row['block']) + end = start + row['samples'] + counter_diff = np.diff(packets['counter'][start:end].astype(np.int64)) + timestamp_diff = np.diff(packets['timestamp'][start:end].astype(np.int64)) + row['counter_discontinuities'] = int((counter_diff != 1).sum()) + row['median_timestamp_step_us'] = float(np.median(timestamp_diff)) + row['timestamp_discontinuities'] = int((timestamp_diff != 1000000 // rate).sum()) + np.savez_compressed(folder/'event_epochs.npz', eeg_counts=epochs, mode=modes, + block=blocks, sample_index=positions, time_ms=time_ms, + useful_channels=useful) + (folder/'summary.json').write_text(json.dumps(summary, indent=2)) + fig, axes = plt.subplots(4, 1, figsize=(11, 12), constrained_layout=True) + scale = 750000 / 2**24 + colors = {1:'#3274a1',2:'#d65035'} + for mode in (1, 2): + keep = modes == mode + label=f'Mode {mode} (n={keep.sum()})' + centered = epochs[keep,:,channel].astype(float) + centered -= centered[:,baseline].mean(axis=1)[:,None] + axes[0].plot(time_ms, centered.mean(axis=0)*scale, label=label, color=colors[mode]) + axes[1].plot(dt,np.median(normalized[keep],axis=0),label=label,color=colors[mode]) + axes[2].plot(dt,zero[keep].mean(axis=0),label=label,color=colors[mode]) + axes[3].plot(time_ms,centered[0]*scale,label=f'Mode {mode}: first event',color=colors[mode]) + axes[0].set_ylabel(f'Ch {channel+1} mean EEG (µV)\nbaseline subtracted') + axes[1].set_ylabel('Median |sample increment|\nrelative to pre-pulse baseline') + axes[2].set_ylabel('Fraction of channels\nwith exact repeated samples') + axes[3].set_ylabel(f'Ch {channel+1} single event (µV)') + axes[3].set_xlabel('Time from BNC input event (ms)') + axes[0].set_title(f'NA500 BNC loopback: open-input EEG, {rate} Hz native, ' + f'{meta["blanking_width_us"]} µs blanking\n' + 'Mode sequence 1 → 2 → 2 → 1; nominal gate shown in grey') + for ax in axes: + ax.axvspan(0,meta['blanking_width_us']/1000,color='grey',alpha=.15) + ax.axvline(0,color='black',lw=.6) + ax.set_xlim(-8,15) + ax.grid(alpha=.2) + ax.legend(loc='upper right') + fig.savefig(folder/'comparison.png',dpi=160) + print(json.dumps(summary,indent=2)) + + +if __name__ == '__main__': + main() diff --git a/scripts/bnc_blanking_capture.py b/scripts/bnc_blanking_capture.py new file mode 100644 index 0000000..41f02cc --- /dev/null +++ b/scripts/bnc_blanking_capture.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Capture a real NA500 mode-1/mode-2 BNC loopback comparison. + +BNC OUT must be connected to BNC IN. Other AmpServer clients must be unlinked. +Uses one session, 4000 Hz native, 1000 us default blanking/output widths, and ABBA +blocks. Saves every 1264-byte PacketFormat2 (little endian, no frame headers), +command replies, notifications, and sample-index boundaries. No LSL required. +Leaves the BNC input in mode 2, then stops and powers down acquisition. +""" + +import argparse +import datetime +import json +import pathlib +import socket +import struct +import threading +import time + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--host', default='10.10.10.62') + ap.add_argument('--out', type=pathlib.Path, required=True) + ap.add_argument('--pulses', type=int, default=20) + ap.add_argument('--interval', type=float, default=0.5) + ap.add_argument('--width', type=int, default=1000) + args = ap.parse_args() + if not 100 <= args.width <= 1600 or args.pulses < 1 or args.interval < .1: + ap.error('width must be 100-1600 us; pulses >= 1; interval >= .1 s') + args.out.mkdir(parents=True, exist_ok=False) + meta = dict(host=args.host, started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), + rate=4000, native=True, blanking_width_us=args.width, + output_width_us=1000, sequence=[1, 2, 2, 1], + input_description='Open EEG inputs; BNC OUT cabled to BNC IN', + packet_size=1264, samples=0, commands=[], notifications=[], blocks=[], errors=[]) + stop = threading.Event() + power_on = threading.Event() + sockets, workers = [], [] + command_file = (args.out / 'commands.jsonl').open('w') + + def save(): + (args.out / 'capture.json').write_text(json.dumps(meta, indent=2)) + + def connect(port): + sock = socket.create_connection((args.host, port), timeout=5) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + sockets.append(sock) + return sock + + def exact(sock, count): + result = bytearray() + while len(result) < count: + if stop.is_set(): + raise EOFError + try: + chunk = sock.recv(count - len(result)) + except socket.timeout: + continue + if not chunk: + raise EOFError + result.extend(chunk) + return result + + def data_reader(sock): + try: + with (args.out / 'packets.bin').open('wb') as output: + while not stop.is_set(): + amp, length = struct.unpack('>qQ', exact(sock, 16)) + if amp != 0 or length % 1264 or not 0 < length <= 1264 * 65536: + raise ValueError(f'Invalid frame header: {amp}, {length}') + payload = exact(sock, length) + output.write(payload) + meta['samples'] += length // 1264 + except (EOFError, OSError, ValueError) as exc: + if not stop.is_set(): + meta['errors'].append(f'data reader: {exc!r}') + + def notifications(sock): + buffer = b'' + try: + while not stop.is_set(): + try: + chunk = sock.recv(4096) + except socket.timeout: + continue + if not chunk: + break + buffer += chunk + while b'\n' in buffer: + line, buffer = buffer.split(b'\n', 1) + text = line.decode(errors='replace') + meta['notifications'].append(dict(monotonic=time.monotonic(), text=text)) + if 'ntn_AmpPowerOn' in text: + power_on.set() + except OSError: + pass + + cmd = None + identified = False + try: + cmd = connect(9877) + cmd.settimeout(12) + cmd_file = cmd.makefile('rb') + notify, data = connect(9878), connect(9879) + for sock, target in ((notify, notifications), (data, data_reader)): + sock.settimeout(1) + worker = threading.Thread(target=target, args=(sock,), daemon=True) + workers.append(worker) + worker.start() + time.sleep(.2) + + def send(name, value=0, channel=0): + entry = dict(command=name, value=value, channel=channel, + monotonic_before=time.monotonic(), sample_before=meta['samples']) + cmd.sendall(f'(sendCommand {name} 0 {channel} {value})\n'.encode()) + reply = cmd_file.readline().decode(errors='replace').strip() + entry.update(reply=reply, monotonic_after=time.monotonic(), sample_after=meta['samples']) + meta['commands'].append(entry) + command_file.write(json.dumps(entry) + '\n') + command_file.flush() + if '(status complete)' not in reply: + raise RuntimeError(f'{name}: {reply!r}') + return reply + + details = send('cmd_GetAmpDetails') + meta['amplifier_details'] = details + print(details, flush=True) + if '(amp_type NA500)' not in details or '(packet_format 2)' not in details: + raise RuntimeError('This capture requires an NA500 with packet format 2') + identified = True + send('cmd_Stop') + send('cmd_SetPower', 0) + send('cmd_ReceiveNotifications') + send('cmd_SetAmpTime', time.time_ns() // 1000) + send('cmd_SetPower', 1) + print('Waiting for power-on notification...', flush=True) + if not power_on.wait(35): + raise RuntimeError('No amplifier power-on confirmation') + time.sleep(.3) + send('cmd_SetNativeRate', 4000) + send('cmd_DefaultAcquisitionState') + send('cmd_SetBufferedReference', 1) + send('cmd_SetDinEnable', 1) + send('cmd_SetBlankingPulseWidth', args.width) + send('cmd_SetBncInMode', 1) + send('cmd_SetBncOutMode', 1) + send('cmd_SetBncOutPulseWidth', 1000) + send('cmd_Start') + time.sleep(2) + if meta['samples'] < 1000: + raise RuntimeError('No usable stream after start') + for number, mode in enumerate(meta['sequence'], 1): + send('cmd_SetBlankingPulseWidth', args.width) + send('cmd_SetBncInMode', mode) + time.sleep(.75) + block = dict(number=number, mode=mode, start_sample=meta['samples'], pulses=[]) + meta['blocks'].append(block) + print(f'Block {number}/4: mode {mode}, {args.pulses} pulses', flush=True) + time.sleep(.5) + for pulse in range(args.pulses): + start = time.monotonic() + send('cmd_SetTriggerBncManualOut') + block['pulses'].append(len(meta['commands']) - 1) + time.sleep(max(0, args.interval - (time.monotonic() - start))) + if meta['errors']: + raise RuntimeError(meta['errors']) + time.sleep(.5) + block['end_sample'] = meta['samples'] + save() + meta['complete'] = True + except BaseException as exc: + meta['errors'].append(repr(exc)) + raise + finally: + if cmd is not None and identified: + for name, value in (('cmd_SetBlankingPulseWidth', args.width), ('cmd_SetBncInMode', 2), + ('cmd_Stop', 0), ('cmd_SetPower', 0)): + try: + send(name, value) + except Exception as exc: + meta['errors'].append(f'cleanup {name}: {exc!r}') + stop.set() + for sock in sockets: + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + sock.close() + for worker in workers: + worker.join(3) + save() + command_file.close() + print(f'Saved {meta["samples"]} raw packets to {args.out}', flush=True) + + +if __name__ == '__main__': + main() diff --git a/scripts/na500_dhcp.conf b/scripts/na500_dhcp.conf new file mode 100644 index 0000000..2c5ca2a --- /dev/null +++ b/scripts/na500_dhcp.conf @@ -0,0 +1,13 @@ +# Example DHCP for an isolated NA500 Ethernet link. +# Change en10 to your adapter, and configure it as 10.10.10.61/24 first. +# Run from the repository root; Ctrl+C stops the server: +# sudo /opt/homebrew/sbin/dnsmasq --no-daemon --conf-file="$PWD/scripts/na500_dhcp.conf" +interface=en10 +bind-interfaces +port=0 +dhcp-range=10.10.10.62,10.10.10.62,255.255.255.0,12h +# This isolated link provides neither a default gateway nor a DNS server. +dhcp-option=option:router +dhcp-option=option:dns-server +dhcp-leasefile=/private/tmp/egi-na500-dhcp.leases +log-dhcp diff --git a/src/core/include/egiamp/EGIAmpClient.h b/src/core/include/egiamp/EGIAmpClient.h index 8d98d88..fbfb199 100644 --- a/src/core/include/egiamp/EGIAmpClient.h +++ b/src/core/include/egiamp/EGIAmpClient.h @@ -99,6 +99,7 @@ class EGIAmpClient { bool initAmplifier(); void haltAmplifier(); void enableNA500FrontEnd(); // no-op on other models + void configureNA500BncInput(); // width before mode; throws on rejection void readPacketFormat1(); void readPacketFormat2(); diff --git a/src/core/src/EGIAmpClient.cpp b/src/core/src/EGIAmpClient.cpp index e3d197b..84d3b83 100644 --- a/src/core/src/EGIAmpClient.cpp +++ b/src/core/src/EGIAmpClient.cpp @@ -534,8 +534,7 @@ void EGIAmpClient::enableNA500FrontEnd() { connection_.sendCommand("cmd_SetBufferedReference", config_.amplifierId, 0, "1"); // Without this the DB9 inputs read 0, i.e. all 16 active (they are active-low). connection_.sendCommand("cmd_SetDinEnable", config_.amplifierId, 0, "1"); - // BNC in: report each rising edge (as DIN bit 16). - connection_.sendCommand("cmd_SetBncInMode", config_.amplifierId, 0, "1"); + configureNA500BncInput(); // Physio gains persist on the amp across sessions; pin them to 12, the // power-on default, which the physio scaling assumes (same as the EEG's). for (int ch = 0; ch < 16; ch++) { @@ -544,6 +543,25 @@ void EGIAmpClient::enableNA500FrontEnd() { } } +void EGIAmpClient::configureNA500BncInput() { + if (details_.amplifierType != AmplifierType::NA500) return; + + // The FPGA requires a width (100-1600 us) BEFORE mode 2 enables TMS + // blanking. It stays armed for subsequent pulses and still reports each + // rising edge as DIN bit 16. Apply on stream setup, including when joining + // an already-running amp, and again after reinitialization. + constexpr int blankingWidthUs = 1000; + if (!commandCompleted(connection_.sendCommand("cmd_SetBlankingPulseWidth", + config_.amplifierId, 0, std::to_string(blankingWidthUs)))) { + throw std::runtime_error("Failed to set BNC input blanking pulse width"); + } + if (!commandCompleted(connection_.sendCommand("cmd_SetBncInMode", + config_.amplifierId, 0, "2"))) { + throw std::runtime_error("Failed to enable BNC input TMS blanking"); + } + emitStatus("BNC input: TMS blanking enabled (1000 us), with input events.\n"); +} + void EGIAmpClient::haltAmplifier() { emitStatus("Stopping stream...\n"); @@ -681,6 +699,7 @@ bool EGIAmpClient::startStreaming() { } else { emitStatus("Amplifier is already running, skipping initialization.\n"); weInitializedAmp_ = false; + configureNA500BncInput(); // Use detected sample rate if available if (detectedRate > 0) {