From d22ff4ce50d0b8963786d905cad56172a4f38b3f Mon Sep 17 00:00:00 2001 From: Chadwick Boulay Date: Mon, 26 Oct 2026 01:54:16 -0400 Subject: [PATCH 1/8] Align the NA500 mock with the real GES 500; fix NA500 streaming bugs Measured against a real NA500 (fw 0.4.9) with a new wire-level conformance recorder, scripts/ampserver_conformance.py. Its recording of the device is mock/conformance/na500_fw0.4.9.json, and the observed protocol is written up in docs/NA500_AmpServer.md. Mock: --amp-type NA500 now runs a dedicated session-based server (NA500Server) that matches the device on every compared behavior: one client per port per session, session ends with the command connection, one command per TCP segment, unknown commands re-run the previous one, missing/double replies, unbalanced replies, notification timing, 8-sample blocks, counter restart and leftover packets after cmd_Start, the ~8000 samples/s ceiling at 16 kHz, and sample loss when a client stops reading. --net-code None emulates a unit with no net. NA400 and other models are unchanged. App (all NA500-gated; the NA400 path is untouched): - Discard the leftover packets the NA500 sends after cmd_Start; they carried stale samples into LSL and a false "Packet(s) Dropped". - Skip the Physio16 status wait: the NA500 never sends the notification, and leaving its data port unread for 5 s lost ~4 s of samples. - Set the amp clock with cmd_SetAmpTime at power-on, as Net Station does. - Stop offering 16000 Hz: the NA500 delivers only ~8000 samples/s there. Also bumps liblsl to v1.18.0.b6 and documents finding the NA500 by mDNS. --- README.md | 25 +- docs/NA500_AmpServer.md | 92 ++++ mock/CMakeLists.txt | 1 + mock/conformance/na500_fw0.4.9.json | 442 ++++++++++++++++++ mock/include/NA500Server.h | 78 ++++ mock/src/MockAmplifier.cpp | 6 +- mock/src/NA500Server.cpp | 378 +++++++++++++++ mock/src/main.cpp | 11 + resources/sampling_rates.json | 4 +- scripts/ampserver_conformance.py | 493 ++++++++++++++++++++ src/core/include/egiamp/AmpServerProtocol.h | 5 +- src/core/src/EGIAmpClient.cpp | 29 +- src/gui/EGIAmpWindow.cpp | 1 - 13 files changed, 1551 insertions(+), 14 deletions(-) create mode 100644 docs/NA500_AmpServer.md create mode 100644 mock/conformance/na500_fw0.4.9.json create mode 100644 mock/include/NA500Server.h create mode 100644 mock/src/NA500Server.cpp create mode 100644 scripts/ampserver_conformance.py diff --git a/README.md b/README.md index e304fcf..cc9ec37 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ Bypasses the FPGA filter and samples directly at the requested rate. This provid - Reduced bandwidth (~1/4 of sample rate, e.g., 250 Hz at 1000 Hz sample rate) - Optimized for EEG-TMS and real-time BCI applications -Available native rates: 500, 1000, 2000, 4000, 8000 Hz (NA400); 250, 500, 1000, 2000, 4000, 8000, 16000 Hz (NA500) +Available native rates: 500, 1000, 2000, 4000, 8000 Hz (NA400); 250, 500, 1000, 2000, 4000, 8000 Hz (NA500) Use `--fast-recovery` (or a "Low Latency" dropdown entry) to select native mode for rates where the model offers both. @@ -131,14 +131,21 @@ The NA500 rows are zero deliberately: Net Station 6 applies no anti-alias alignm ## Net Amps 500 (GES 500) Support -NA500 support was verified against real hardware (firmware 0.4.9). Differences from the NA400 that this app handles automatically: +NA500 support was verified against real hardware (firmware 0.4.9). The amplifier's protocol is documented, as observed on the wire, in [docs/NA500_AmpServer.md](docs/NA500_AmpServer.md). + +**Finding the amplifier**: the NA500 gets its address by DHCP and advertises itself over mDNS (service `_na500._tcp`), typically as `NA500-256ch-.local`. Pass that name instead of an IP, e.g. `--address NA500-256ch-0001.local`. This works out of the box on macOS and recent Windows 10/11; Linux needs Avahi with `nss-mdns`. To list amplifiers on the network, run `dns-sd -B _na500._tcp` (macOS/Windows with Bonjour) or `avahi-browse -r _na500._tcp` (Linux). With no DHCP server on the network the amplifier has no IPv4 address, and this app cannot reach it because its AmpServer is IPv4-only. + +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). -- **Rates**: decimated up to 2000 Hz; native from 250 Hz up to 16000 Hz. No duplicate packets are sent at low rates (the NA400 duplicates samples below 1000 Hz). +- **Rates**: decimated up to 2000 Hz; native from 250 Hz up to 8000 Hz. No duplicate packets are sent at low rates (the NA400 duplicates samples below 1000 Hz). 16000 Hz is not offered: the amplifier accepts it but delivers only about 8000 samples/s, and the missing samples leave no gap in its packet counter. - **Initialization**: the NA500 silently ignores commands sent while it is powering up (~10 s from cold), so the app waits for the power-on notification before configuring it. -- **Data connection handling**: the NA500's AmpServer stops serving data to new listeners once any listener disconnects (until the amp restarts), so the app maintains one persistent data connection per session and never issues `cmd_StopListeningToAmp`. +- **Data connection handling**: the NA500's AmpServer serves one data listener per session; once it disconnects, no new listener is served until the command connection closes and a new session starts. The app therefore maintains one persistent data connection per session and never issues `cmd_StopListeningToAmp` (which the NA500 never answers). +- **Continuous reading**: the NA500 drops samples if its data port goes unread for a few seconds, so the app does not wait for a Physio16 status notification (the NA500 sends none). +- **Stale packets**: after `cmd_Start` the NA500 first resends leftover packets from its previous stream before its counter restarts at 0; the app discards them. +- **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). -- **Recovery**: the NA500 emits no `ntn_AmpStarted` notification, so external-restart recovery uses data-port polling instead. +- **Recovery**: the NA500 sends `ntn_AmpStarted` only in reply to `cmd_GetStartTime`, not when streaming starts, so external-restart recovery uses data-port polling instead. - **Robustness**: the NA500's embedded AmpServer (fw 0.4.9) can crash or stop responding after abrupt client disconnects; commands now time out after 10 s instead of hanging, and the GUI performs linking on a background thread so the UI never freezes. A crashed AmpServer requires power-cycling the amplifier. ## Timestamp Compensation @@ -430,6 +437,14 @@ To use the mock server for development: The mock server generates synthetic sine waves (10-50 Hz) with noise for the EEG data, so you can also verify the LSL stream in downstream applications. +The C++ mock (`MockAmpServer`, built with the project) also emulates other models. `MockAmpServer --amp-type NA500` reproduces the NA500's session-based AmpServer, including its quirks (see [docs/NA500_AmpServer.md](docs/NA500_AmpServer.md)); add `--net-code None` to emulate a unit with no net attached. + +`scripts/ampserver_conformance.py` records how an AmpServer behaves on the wire and diffs two recordings. The recording of a real NA500 is in `mock/conformance/`; to check the mock against it: + +> MockAmpServer --amp-type NA500 --net-code None & +> python3 scripts/ampserver_conformance.py --host 127.0.0.1 --active -o mock.json +> python3 scripts/ampserver_conformance.py --compare mock/conformance/na500_fw0.4.9.json mock.json + # Known Issues ## Net Station Acquisition Compatibility diff --git a/docs/NA500_AmpServer.md b/docs/NA500_AmpServer.md new file mode 100644 index 0000000..c92d0f7 --- /dev/null +++ b/docs/NA500_AmpServer.md @@ -0,0 +1,92 @@ +# Net Amps 500 (GES 500) AmpServer: observed behavior + +There is no public documentation for the AmpServer embedded in the GES 500. This page records how it +behaves on the wire, as measured against a real unit (firmware 0.4.9, FPGA 0.6.1.f0, PCB 4.1.0.0). +`scripts/ampserver_conformance.py` reproduces every measurement here, and its recording of that unit is +in `mock/conformance/na500_fw0.4.9.json`. `MockAmpServer --amp-type NA500` emulates this behavior. + +The protocol is the AmpServer protocol used by the NA400 (commands on TCP 9877, notifications on 9878, +data on 9879). Only the differences that matter to a client are listed. + +## Network + +- The amplifier takes an IPv4 address by DHCP and advertises itself over mDNS as service `_na500._tcp`, + host `NA500-256ch-.local`, with TXT records `serial` and `hostname`. Some units also hold the + static address `169.254.3.10`. +- The AmpServer listens on IPv4 only. On a network without DHCP the unit has only an IPv6 link-local + address and cannot be reached. +- There is no ECI port (55513) and no UDP discovery port (9880). + +## Sessions + +- Each of the three ports accepts **one** client per session. A second client's connection succeeds at + the TCP level but is never served. If the data client disconnects, no new data client is served until + the session ends. +- Closing the command connection ends the session: streaming stops, the analog front end is powered + off, and the notification and data clients are disconnected. The next client to connect starts a new + session. A stream left running is not resumed: the next session must send `cmd_SetPower 1` and + `cmd_Start` again. +- `cmd_SetDinEnable` persists from one session to the next. + +## Commands + +- Each TCP segment is one command. A second command in the same segment is ignored, so send one + command per write and wait for its reply. A trailing extra newline or a doubled space is harmless. +- A command name the server does not recognize, or a segment that does not parse, **re-runs the + previous command**, with the new segment's arguments where they parse. For example, after + `cmd_NumberOfAmps`, sending `cmd_NoSuchCommand` returns the `number_of_amps` reply again. +- Replies that differ from the NA400: + + | Command | Reply | + |---|---| + | `cmd_ListenToAmp`, `cmd_StopListeningToAmp` sent on the **command** port | none (the client must time out) | + | `cmd_SetDecimatedRate` / `cmd_SetNativeRate` with an unsupported rate | none | + | `cmd_SetPower` with a value other than 0 or 1 | none | + | `cmd_TurnAllZeroOhms`, `cmd_TurnChannelZeroOhms`, `cmd_SetMRIPulseInfo`, `cmd_SetPhoticStimSequence` | **two** `(status complete)` lines | + | `cmd_NumberOfAmps` | `(sendCommand_return (status complete) (number_of_amps 1))` | + | `cmd_GetAmpDetails` | as on the NA400 plus `fpga_version`, `pcb_version`, `feature_flags`; **the final `)` is missing** | + | `cmd_GetBatteryData` | `(battery_details (time_remaining …) (master …) (slave1 …) … (slave4 …))`; one `)` short | + | `cmd_GetBoardStatus` | `(status_details (ambient_temp …) (lpd_temp …) (fpd_temp …) (pl_temp …))`; one `)` too many | + | `cmd_GetCurrentTime` | `(amp_status_info (current_time N))`, N = current packet counter | + | `cmd_SetRecordingState` | `(amp_status_info (start_time N))`, N = current packet counter | + | `cmd_GetAmpStatus`, `cmd_NumberOfActiveAmps`, `cmd_GetPhysioConnectionStatus`, `cmd_ReceiveNotifications` | bare `(status complete)`, no data | + | `cmd_Stop` | `(status complete)` after about 1 s | + | `cmd_SetAmpTime ` | `(status complete)`; sets the clock used for packet timestamps | + +- Valid rates are 250, 500, 1000, 2000, 4000, 8000 and 16000 Hz, accepted by both `cmd_SetDecimatedRate` + and `cmd_SetNativeRate`. +- The server does not shut down on `cmd_Exit`. GTEN commands and `cmd_SetFilterAndDecimate` are not + recognized (so they re-run the previous command). + +## Notifications + +Only four are sent, each after the reply to the command that causes it: + +| Notification | Sent after | +|---|---| +| `(notification ntn_AmpPowerOn 9 0 -1)` | `cmd_SetPower 1` | +| `(notification ntn_AmpPowerOff 8 0 -1)` | `cmd_SetPower 0` | +| `(notification ntn_AmpStarted 10 0 -1)` | `cmd_GetStartTime` (**not** `cmd_Start`) | +| `(notification ntn_AmpStopped 11 0 -1)` | `cmd_Stop` | + +There is no `ntn_PhysioConnectionStatus` and no client-connected notification. + +## Data stream + +- Data flows to the data client as soon as the amplifier is powered and started; `cmd_ListenToAmp` is + not needed and gets no reply. +- Each block is a 16-byte big-endian header (amp id 0, payload length) followed by **8** format-2 + packets (10112 bytes), at every rate. +- The packet counter restarts at 0 on every `cmd_Start`. Before that first packet the stream carries + **leftover packets from the previous stream** (usually 1–7, occasionally more), with their old counter + and timestamps. They can come from a previous session. Discard packets until the counter is 0. +- Timestamps are microseconds on the amplifier's clock, advancing by exactly `1e6 / rate` per packet + truncated to an integer (62 µs at 16 kHz). The clock is not synchronized: the unit we measured was a + month behind until a client sent `cmd_SetAmpTime`. +- At 16000 Hz only about 8000 packets/s are delivered while timestamps and counters advance as if all + 16000 were sent: about half the samples are lost without a trace. Rates up to 8000 Hz are delivered in + full. +- If the client stops reading for a few seconds, the amplifier drops samples once about 1 MB is + 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. diff --git a/mock/CMakeLists.txt b/mock/CMakeLists.txt index 789a820..c3b88de 100644 --- a/mock/CMakeLists.txt +++ b/mock/CMakeLists.txt @@ -24,6 +24,7 @@ add_executable(MockAmpServer src/NotificationHandler.cpp src/DataStreamGenerator.cpp src/ECIHandler.cpp + src/NA500Server.cpp ) target_include_directories(MockAmpServer PRIVATE diff --git a/mock/conformance/na500_fw0.4.9.json b/mock/conformance/na500_fw0.4.9.json new file mode 100644 index 0000000..382d355 --- /dev/null +++ b/mock/conformance/na500_fw0.4.9.json @@ -0,0 +1,442 @@ +{ + "queries": { + "cmd_NumberOfAmps": { + "replies": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "~latency_s": 0.0 + }, + "cmd_GetAmpDetails": { + "replies": [ + "(sendCommand_return (status complete) (amp_details (serial_number ) (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))" + ], + "~latency_s": 0.0 + }, + "cmd_GetAmpStatus": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "cmd_GetBatteryData": { + "replies": [ + "(sendCommand_return (status complete) (battery_details (time_remaining ) (master ) (slave1 ) (slave2 ) (slave3 ) (slave4 ))" + ], + "~latency_s": 0.0 + }, + "cmd_GetBoardStatus": { + "replies": [ + "(sendCommand_return (status complete) (status_details (ambient_temp ) (lpd_temp ) (fpd_temp ) (pl_temp ))))" + ], + "~latency_s": 0.0 + }, + "cmd_NumberOfActiveAmps": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "cmd_GetPhysioConnectionStatus": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "cmd_GetCurrentTime": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (current_time )))" + ], + "~latency_s": 0.0 + }, + "cmd_GetCurrentDrift": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "cmd_GetNetRecordingTime": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "cmd_ReceiveNotifications": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "cmd_StopReceivingNotifications": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "cmd_None": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "notifications": [] + }, + "framing": { + "two_in_one_segment": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "double_newline": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "extra_space": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "unknown_after_NumberOfAmps": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "split_across_segments": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "lowercase_setPIBChannelGain": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ] + }, + "odd_replies": { + "ListenToAmp_on_cmd_port": [], + "ListenToAmp_on_cmd_port_then_NumberOfAmps": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "StopListeningToAmp_on_cmd_port": [], + "StopListeningToAmp_on_cmd_port_then_NumberOfAmps": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "SetDecimatedRate_300": [], + "SetDecimatedRate_300_then_NumberOfAmps": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "SetNativeRate_300": [], + "SetNativeRate_300_then_NumberOfAmps": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "SetPower_2": [], + "SetPower_2_then_NumberOfAmps": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "TurnAllZeroOhms_0": [ + "(sendCommand_return (status complete))", + "(sendCommand_return (status complete))" + ], + "TurnAllZeroOhms_0_then_NumberOfAmps": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ], + "SetMRIPulseInfo_0": [ + "(sendCommand_return (status complete))", + "(sendCommand_return (status complete))" + ], + "SetMRIPulseInfo_0_then_NumberOfAmps": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ] + }, + "second_client": { + "second_client_reply": null, + "second_client_connects": true, + "first_client_still_served": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ] + }, + "recognized": { + "cmd_Reset": true, + "cmd_DefaultAcquisitionState": true, + "cmd_DefaultSignalGeneration": true, + "cmd_Exit": true, + "cmd_TurnAll10KOhms": true, + "cmd_TurnChannel10KOhms": true, + "cmd_SetCOM10KOhms": true, + "cmd_TurnAllDriveSignals": true, + "cmd_TurnChannelDriveSignals": true, + "cmd_SetSubjectGround": true, + "cmd_SetCurrentSource": true, + "cmd_SetCalibrationSignalFreq": true, + "cmd_SetBufferedReference": true, + "cmd_SetOscillatorGate": true, + "cmd_SetReference10KOhms": true, + "cmd_SetReferenceDriveSignal": true, + "cmd_SetWaveShape": true, + "cmd_SetDrivenCommon": true, + "cmd_SetCalibrationSignalAmplitude": true, + "cmd_SetAnalogOutput": true, + "cmd_SetDigitalOutputData": true, + "cmd_SetDigitalInOutDirection": true, + "cmd_GetStartTime": true, + "cmd_SetPIBChannelGain": true, + "cmd_TurnChannelZeroOhms": true, + "cmd_SetPhoticStimSequence": true, + "cmd_SetSpo2Enable": true, + "cmd_SetDinEnable": true, + "cmd_SetTestMode": true, + "cmd_SetOpticalClockMode": true, + "cmd_SetRecordingState": true, + "cmd_SetBncInMode": true, + "cmd_SetBncOutMode": true, + "cmd_SetBncOutPulseWidth": true, + "cmd_SetBlankingPulseWidth": true, + "cmd_SetTriggerBncManualOut": true, + "cmd_SetQuietMode": true, + "cmd_SetNetRecordingTime": false, + "cmd_SetFilterAndDecimate": false, + "cmd_GTENGetStatus": false + }, + "power": { + "SetPower_1": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "SetPower_1_notifications": [ + "(notification ntn_AmpPowerOn 9 0 -1)" + ], + "SetPower_0": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "SetPower_0_notifications": [ + "(notification ntn_AmpPowerOff 8 0 -1)" + ] + }, + "stream_decimated_250": { + "SetDecimatedRate": [ + "(sendCommand_return (status complete))" + ], + "Start": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "Start_notifications": [], + "stream_without_ListenToAmp": { + "header_amp_ids": [ + 0 + ], + "packets_per_block": [ + 8 + ], + "payload_multiple_of_1264": true, + "counter_starts_at_0": true, + "counter_step_set": [ + 1 + ], + "timestamp_step_us_top": [ + 4000 + ], + "net_codes": [ + 255 + ], + "din_most_common": "0xffff", + "reserved0_values": [ + 3 + ], + "~stale_packets_before_reset": 7, + "~packets": 616, + "~rate_by_host_clock": 236, + "~rate_by_timestamps": 250, + "~amp_clock_minus_host_s": 0.2 + }, + "GetStartTime": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (start_time )))" + ], + "~latency_s": 0.0 + }, + "GetCurrentTime": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (current_time )))" + ], + "~latency_s": 0.0 + }, + "SetRecordingState_0": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (start_time )))" + ], + "~latency_s": 0.0 + }, + "GetStartTime_notifications": [ + "(notification ntn_AmpStarted 10 0 -1)" + ], + "Stop": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 1.0 + }, + "Stop_notifications": [ + "(notification ntn_AmpStopped 11 0 -1)" + ], + "restart_counter_starts_at_0": true, + "~restart_stale_packets": 0 + }, + "stream_decimated_1000": { + "SetDecimatedRate": [ + "(sendCommand_return (status complete))" + ], + "Start": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "Start_notifications": [], + "stream_without_ListenToAmp": { + "header_amp_ids": [ + 0 + ], + "packets_per_block": [ + 8 + ], + "payload_multiple_of_1264": true, + "counter_starts_at_0": true, + "counter_step_set": [ + 1 + ], + "timestamp_step_us_top": [ + 1000 + ], + "net_codes": [ + 255 + ], + "din_most_common": "0xffff", + "reserved0_values": [ + 3 + ], + "~stale_packets_before_reset": 3, + "~packets": 2464, + "~rate_by_host_clock": 940, + "~rate_by_timestamps": 1000, + "~amp_clock_minus_host_s": 0.3 + }, + "GetStartTime": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (start_time )))" + ], + "~latency_s": 0.0 + }, + "GetCurrentTime": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (current_time )))" + ], + "~latency_s": 0.0 + }, + "SetRecordingState_0": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (start_time )))" + ], + "~latency_s": 0.0 + }, + "GetStartTime_notifications": [ + "(notification ntn_AmpStarted 10 0 -1)" + ], + "Stop": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 1.0 + }, + "Stop_notifications": [ + "(notification ntn_AmpStopped 11 0 -1)" + ], + "restart_counter_starts_at_0": true, + "~restart_stale_packets": 0 + }, + "stream_native_16000": { + "SetNativeRate": [ + "(sendCommand_return (status complete))" + ], + "Start": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 0.0 + }, + "Start_notifications": [], + "stream_without_ListenToAmp": { + "header_amp_ids": [ + 0 + ], + "packets_per_block": [ + 8 + ], + "payload_multiple_of_1264": true, + "counter_starts_at_0": true, + "counter_step_set": [ + 1 + ], + "timestamp_step_us_top": [ + 62 + ], + "net_codes": [ + 255 + ], + "din_most_common": "0xffff", + "reserved0_values": [ + 3 + ], + "~stale_packets_before_reset": 3, + "~packets": 19640, + "~rate_by_host_clock": 7533, + "~rate_by_timestamps": 16129, + "~amp_clock_minus_host_s": -1.0 + }, + "GetStartTime": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (start_time )))" + ], + "~latency_s": 0.0 + }, + "GetCurrentTime": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (current_time )))" + ], + "~latency_s": 0.0 + }, + "SetRecordingState_0": { + "replies": [ + "(sendCommand_return (status complete) (amp_status_info (start_time )))" + ], + "~latency_s": 0.0 + }, + "GetStartTime_notifications": [ + "(notification ntn_AmpStarted 10 0 -1)" + ], + "Stop": { + "replies": [ + "(sendCommand_return (status complete))" + ], + "~latency_s": 1.0 + }, + "Stop_notifications": [ + "(notification ntn_AmpStopped 11 0 -1)" + ], + "restart_counter_starts_at_0": true, + "~restart_stale_packets": 4 + }, + "data_reconnect": { + "packets_before_drop": true, + "packets_after_reconnect": false, + "cmd_still_served": [ + "(sendCommand_return (status complete) (number_of_amps 1))" + ] + }, + "stalled_reader": { + "samples_lost": true, + "~largest_counter_jump": 4481 + }, + "after_session_end": { + "data_flows_in_new_session_before_Start": false, + "stream_after_Start_without_SetPower": { + "packets": 0, + "blocks": 0 + } + } +} diff --git a/mock/include/NA500Server.h b/mock/include/NA500Server.h new file mode 100644 index 0000000..e224ad1 --- /dev/null +++ b/mock/include/NA500Server.h @@ -0,0 +1,78 @@ +#ifndef MOCK_NA500SERVER_H +#define MOCK_NA500SERVER_H + +#include "MockAmplifier.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mock { + +// Emulates the AmpServer embedded in a Net Amps 500 (GES 500), as observed on +// the wire with firmware 0.4.9 (scripts/ampserver_conformance.py records it). +// It is session based, unlike the NA400's AmpServer: +// - each port accepts one client per session; later connections are never served; +// - closing the command connection ends the session: streaming stops, the amp +// powers off, the notification and data clients are dropped; +// - each TCP segment on the command port is one command; an unparsable or +// unknown command re-runs the previous one; +// - data flows to the data client without cmd_ListenToAmp, 8 samples per block; +// - a client that stops reading loses samples once a few blocks are queued. +class NA500Server { +public: + NA500Server(std::shared_ptr amplifier, + uint16_t cmdPort, uint16_t notifyPort, uint16_t dataPort); + ~NA500Server(); + + // Serve sessions until `running` becomes false. + void run(const std::atomic& running); + +private: + using Socket = asio::ip::tcp::socket; + + void session(const std::atomic& running); + std::vector execute(const std::string& name, long long channel, long long value); + void notify(const std::string& line); + void streamLoop(); + void sendLoop(); + int64_t ampClockMicros() const; + + asio::io_context io_; + std::shared_ptr amp_; + uint16_t cmdPort_, notifyPort_, dataPort_; + + std::mutex socketMutex_; + std::shared_ptr notifySocket_, dataSocket_; + + std::atomic stopping_{false}; + std::atomic streaming_{false}; + std::atomic dinEnabled_{false}; + std::thread streamThread_; + // Full blocks waiting to be written to the data client. Bounded like the + // device's send ring: while the client is not reading, new blocks are lost. + std::mutex queueMutex_; + std::condition_variable queueCv_; + std::deque> queue_; + std::thread sendThread_; + + // The previous command, re-run when a segment does not parse. + std::string lastName_ = "cmd_None"; + long long lastValues_[3] = {0, 0, 0}; + std::vector pendingNotifications_; // sent after the command's replies + + // Both persist across sessions, as on the device. + std::atomic packetCounter_{0}; + std::atomic clockOffsetUs_; + std::atomic streamStartUs_{0}; +}; + +} // namespace mock + +#endif // MOCK_NA500SERVER_H diff --git a/mock/src/MockAmplifier.cpp b/mock/src/MockAmplifier.cpp index 94d9dc7..069978d 100644 --- a/mock/src/MockAmplifier.cpp +++ b/mock/src/MockAmplifier.cpp @@ -424,9 +424,11 @@ void MockAmplifier::generatePacketFormat2(PacketFormat2_SamplePacket& packet) { // continuous timestamp offset, so nearest-sample is the closest the mock's // sample grid can get). The physio lead floors, matching the device's own // whole-sample quantization (32 ms @ 250/500, 33 ms @ 1000). - const int eegDelaySamples = state_.decimated + // The NA500 has neither skew: its decimated and native rates stream identically. + const bool skewed = state_.decimated && state_.amplifierType != AmplifierType::NA500; + const int eegDelaySamples = skewed ? (filterDelayMs(sampleRate) * sampleRate + 500) / 1000 : 0; - const int physioLeadSamples = state_.decimated + const int physioLeadSamples = skewed ? PHYSIO_LEAD_MS * sampleRate / 1000 : 0; int physioDelaySamples = eegDelaySamples - physioLeadSamples; if (physioDelaySamples < 0) physioDelaySamples = 0; diff --git a/mock/src/NA500Server.cpp b/mock/src/NA500Server.cpp new file mode 100644 index 0000000..130bbad --- /dev/null +++ b/mock/src/NA500Server.cpp @@ -0,0 +1,378 @@ +#include "NA500Server.h" +#include "ByteSwap.h" + +#include +#include +#include +#include +#include + +namespace mock { + +namespace { + +constexpr int SAMPLES_PER_BLOCK = 8; +constexpr std::size_t SEND_QUEUE_BLOCKS = 8; +// Above this the device drops frames silently: at 16 kHz timestamps still step +// 62 us and the counter steps 1, but only ~8000 packets/s arrive. +constexpr int MAX_DELIVERED_RATE = 8000; +// The amp's clock is not synced until a client sends cmd_SetAmpTime; the unit +// we recorded was about a month behind. +constexpr int64_t STALE_CLOCK_US = -30LL * 24 * 3600 * 1000000; + +const std::string OK = "(sendCommand_return (status complete))"; + +const std::set RATES = {"250", "500", "1000", "2000", "4000", "8000", "16000"}; + +// Commands the device recognizes (scripts/ampserver_conformance.py checks them, +// except cmd_SetCOMDriveSignal, cmd_SetCOMAndRefForMeasurement and +// cmd_SetScreenOrientation, which it skips to leave the unit alone). +// Anything else re-runs the previous command. +const std::set KNOWN = { + "cmd_None", "cmd_Start", "cmd_Stop", "cmd_TurnAll10KOhms", "cmd_TurnChannel10KOhms", + "cmd_SetCOM10KOhms", "cmd_TurnAllDriveSignals", "cmd_SetCOMDriveSignal", + "cmd_TurnChannelDriveSignals", "cmd_SetSubjectGround", "cmd_SetCurrentSource", + "cmd_SetCalibrationSignalFreq", "cmd_SetBufferedReference", "cmd_SetOscillatorGate", + "cmd_SetReference10KOhms", "cmd_SetReferenceDriveSignal", "cmd_SetPower", "cmd_Reset", + "cmd_SetWaveShape", "cmd_SetDrivenCommon", "cmd_SetCalibrationSignalAmplitude", + "cmd_SetAnalogOutput", "cmd_SetDigitalOutputData", "cmd_SetDigitalInOutDirection", + "cmd_GetStartTime", "cmd_GetCurrentTime", "cmd_GetCurrentDrift", "cmd_SetNativeRate", + "cmd_SetDecimatedRate", "cmd_SetMRIPulseInfo", "cmd_SetPIBChannelGain", + "cmd_TurnChannelZeroOhms", "cmd_TurnAllZeroOhms", "cmd_SetPhoticStimSequence", + "cmd_GetPhysioConnectionStatus", "cmd_GetAmpDetails", "cmd_GetAmpStatus", + "cmd_DefaultAcquisitionState", "cmd_DefaultSignalGeneration", "cmd_NumberOfAmps", + "cmd_NumberOfActiveAmps", "cmd_ListenToAmp", "cmd_StopListeningToAmp", + "cmd_ReceiveNotifications", "cmd_StopReceivingNotifications", "cmd_Exit", + "cmd_GetBatteryData", "cmd_GetBoardStatus", "cmd_SetSpo2Enable", "cmd_SetDinEnable", + "cmd_SetTestMode", "cmd_SetCOMAndRefForMeasurement", "cmd_SetOpticalClockMode", + "cmd_SetRecordingState", "cmd_SetAmpTime", "cmd_SetBncInMode", "cmd_SetBncOutMode", + "cmd_SetBncOutPulseWidth", "cmd_SetBlankingPulseWidth", "cmd_SetTriggerBncManualOut", + "cmd_SetQuietMode", "cmd_SetScreenOrientation"}; + +int64_t hostMicros() { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); +} + +// Poll a non-blocking acceptor until a client arrives or `keepGoing` turns false. +template +std::shared_ptr acceptOne(asio::io_context& io, asio::ip::tcp::acceptor& acceptor, + Pred keepGoing) { + while (keepGoing()) { + auto socket = std::make_shared(io); + asio::error_code ec; + acceptor.accept(*socket, ec); + if (!ec) { + socket->set_option(asio::ip::tcp::no_delay(true), ec); + return socket; + } + // Poll quickly: the device accepts within microseconds, and clients + // send commands right after connecting all three ports. + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return nullptr; +} + +asio::ip::tcp::acceptor listen(asio::io_context& io, uint16_t port) { + asio::ip::tcp::acceptor acceptor(io); + const asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port); + acceptor.open(endpoint.protocol()); + acceptor.set_option(asio::ip::tcp::acceptor::reuse_address(true)); + acceptor.bind(endpoint); + acceptor.listen(5); + acceptor.non_blocking(true); + return acceptor; +} + +} // namespace + +NA500Server::NA500Server(std::shared_ptr amplifier, + uint16_t cmdPort, uint16_t notifyPort, uint16_t dataPort) + : amp_(std::move(amplifier)), cmdPort_(cmdPort), notifyPort_(notifyPort), dataPort_(dataPort), + clockOffsetUs_(STALE_CLOCK_US) { + streamThread_ = std::thread(&NA500Server::streamLoop, this); + sendThread_ = std::thread(&NA500Server::sendLoop, this); +} + +NA500Server::~NA500Server() { + stopping_ = true; + queueCv_.notify_all(); + if (streamThread_.joinable()) streamThread_.join(); + if (sendThread_.joinable()) sendThread_.join(); +} + +int64_t NA500Server::ampClockMicros() const { + return hostMicros() + clockOffsetUs_; +} + +void NA500Server::run(const std::atomic& running) { + std::cout << "[NA500] Serving one session at a time on ports " << cmdPort_ << "/" + << notifyPort_ << "/" << dataPort_ << std::endl; + while (running) { + session(running); + } + stopping_ = true; +} + +void NA500Server::session(const std::atomic& running) { + auto cmdAcceptor = listen(io_, cmdPort_); + auto notifyAcceptor = listen(io_, notifyPort_); + auto dataAcceptor = listen(io_, dataPort_); + + // All three ports accept concurrently, each exactly one client per session. + std::atomic open{true}; + auto acceptInto = [&](asio::ip::tcp::acceptor& acceptor, std::shared_ptr& slot) { + return std::thread([this, &open, acc = &acceptor, out = &slot] { + auto socket = acceptOne(io_, *acc, [&] { return open.load(); }); + std::lock_guard lock(socketMutex_); + *out = socket; + }); + }; + std::thread notifyAccept = acceptInto(notifyAcceptor, notifySocket_); + std::thread dataAccept = acceptInto(dataAcceptor, dataSocket_); + + auto cmd = acceptOne(io_, cmdAcceptor, [&] { return running.load(); }); + if (cmd) std::cout << "[NA500] Session started" << std::endl; + + char buffer[4096]; + if (cmd) cmd->non_blocking(true); + while (cmd && running) { + asio::error_code ec; + const std::size_t n = cmd->read_some(asio::buffer(buffer), ec); + if (ec == asio::error::would_block) { + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + continue; + } + if (ec || n == 0) break; + + // One read is one command. Fields that fail to parse keep the previous + // command's values; an unknown name re-runs the previous command. + char name[64] = {0}; + long long values[3] = {lastValues_[0], lastValues_[1], lastValues_[2]}; + const std::string segment(buffer, n); + const int parsed = std::sscanf(segment.c_str(), "(sendCommand %63s %lld %lld %lld)", + name, &values[0], &values[1], &values[2]); + // The parsed values are kept even when the name is not recognized. + if (parsed >= 1 && KNOWN.count(name)) lastName_ = name; + std::copy(values, values + 3, lastValues_); + for (const auto& reply : execute(lastName_, lastValues_[1], lastValues_[2])) { + asio::write(*cmd, asio::buffer(reply + "\n"), ec); + } + for (const auto& note : pendingNotifications_) notify(note); // replies go first + pendingNotifications_.clear(); + } + + // Session teardown: like the device, stop, power off and drop every client. + open = false; + notifyAccept.join(); + dataAccept.join(); + // The DIN enable survives into the next session, as on the device. + streaming_ = false; + amp_->setPower(false); + { + std::lock_guard lock(socketMutex_); + notifySocket_.reset(); + asio::error_code ec; + if (dataSocket_) dataSocket_->shutdown(Socket::shutdown_both, ec); // unblocks sendLoop + dataSocket_.reset(); + } + { + std::lock_guard lock(queueMutex_); + queue_.clear(); + } + std::cout << "[NA500] Session ended" << std::endl; +} + +void NA500Server::notify(const std::string& line) { + std::lock_guard lock(socketMutex_); + if (!notifySocket_) return; + asio::error_code ec; + asio::write(*notifySocket_, asio::buffer(line + "\n"), ec); +} + +std::vector NA500Server::execute(const std::string& name, long long channel, + long long value) { + const bool on = value == 1; + const std::string v = std::to_string(value); + + if (name == "cmd_SetPower") { + if (value != 0 && value != 1) return {}; + amp_->setPower(on); + if (!on) streaming_ = false; + pendingNotifications_.push_back(on ? "(notification ntn_AmpPowerOn 9 0 -1)" + : "(notification ntn_AmpPowerOff 8 0 -1)"); + return {OK}; + } + if (name == "cmd_Start") { + streamStartUs_ = ampClockMicros(); + streaming_ = true; + return {OK}; + } + if (name == "cmd_Stop") { + streaming_ = false; + std::this_thread::sleep_for(std::chrono::seconds(1)); + pendingNotifications_.push_back("(notification ntn_AmpStopped 11 0 -1)"); + return {OK}; + } + if (name == "cmd_SetDecimatedRate" || name == "cmd_SetNativeRate") { + if (!RATES.count(v)) return {}; + if (name == "cmd_SetDecimatedRate") amp_->setDecimatedRate(static_cast(value)); + else amp_->setNativeRate(static_cast(value)); + return {OK}; + } + if (name == "cmd_SetTestMode") { + return (value == 0 || value == 1 || (value >= 3 && value <= 5)) ? std::vector{OK} + : std::vector{}; + } + if (name == "cmd_ListenToAmp" || name == "cmd_StopListeningToAmp") return {}; + if (name == "cmd_TurnChannelZeroOhms" || name == "cmd_TurnAllZeroOhms" || + name == "cmd_SetMRIPulseInfo" || name == "cmd_SetPhoticStimSequence") { + return {OK, OK}; + } + + if (name == "cmd_NumberOfAmps") { + return {"(sendCommand_return (status complete) (number_of_amps 1))"}; + } + if (name == "cmd_GetAmpDetails") { + // The device omits the final closing parenthesis. + const auto& s = amp_->state(); + return {"(sendCommand_return (status complete) (amp_details (serial_number " + s.serialNumber + + ") (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))"}; + } + if (name == "cmd_GetBatteryData") { + // Unbalanced on the device too: one closing parenthesis short. + return {"(sendCommand_return (status complete) (battery_details (time_remaining 600)" + " (master 100) (slave1 100) (slave2 100) (slave3 100) (slave4 100))"}; + } + if (name == "cmd_GetBoardStatus") { + // One closing parenthesis too many, as on the device. + return {"(sendCommand_return (status complete) (status_details (ambient_temp 3200)" + " (lpd_temp 40000) (fpd_temp 40000) (pl_temp 40000))))"}; + } + if (name == "cmd_GetCurrentTime") { + return {"(sendCommand_return (status complete) (amp_status_info (current_time " + + std::to_string(packetCounter_.load()) + ")))"}; + } + if (name == "cmd_SetRecordingState") { + return {"(sendCommand_return (status complete) (amp_status_info (start_time " + + std::to_string(packetCounter_.load()) + ")))"}; + } + if (name == "cmd_GetStartTime") { + pendingNotifications_.push_back("(notification ntn_AmpStarted 10 0 -1)"); + return {"(sendCommand_return (status complete) (amp_status_info (start_time " + + std::to_string(streamStartUs_.load()) + ")))"}; + } + if (name == "cmd_SetAmpTime") { + clockOffsetUs_ = value - hostMicros(); + return {OK}; + } + if (name == "cmd_SetDinEnable") { + dinEnabled_ = true; // the device ignores the value + return {OK}; + } + + // Front-end state the mock's synthetic signals depend on (impedance mode). + const int ch = static_cast(channel); + if (name == "cmd_TurnAll10KOhms") amp_->setAll10KOhms(on); + else if (name == "cmd_TurnChannel10KOhms") amp_->setChannel10KOhms(ch, on); + else if (name == "cmd_TurnAllDriveSignals") amp_->setAllDriveSignals(on); + else if (name == "cmd_TurnChannelDriveSignals") amp_->setChannelDriveSignals(ch, on); + else if (name == "cmd_SetCOM10KOhms") amp_->setCom10KOhms(on); + else if (name == "cmd_SetReference10KOhms") amp_->setReference10KOhms(on); + else if (name == "cmd_SetReferenceDriveSignal") amp_->setReferenceDriveSignal(on); + else if (name == "cmd_SetCOMDriveSignal") amp_->setComDriveSignal(on); + else if (name == "cmd_SetSubjectGround") amp_->setSubjectGround(on); + else if (name == "cmd_SetDrivenCommon") amp_->setDrivenCommon(on); + else if (name == "cmd_SetBufferedReference") amp_->setBufferedReference(on); + else if (name == "cmd_SetOscillatorGate") amp_->setOscillatorGate(on); + else if (name == "cmd_SetWaveShape") amp_->setWaveShape(static_cast(value)); + else if (name == "cmd_SetCalibrationSignalFreq") amp_->setCalibrationSignalFreq(static_cast(value)); + else if (name == "cmd_SetCalibrationSignalAmplitude") amp_->setCalibrationSignalAmplitude(static_cast(value)); + else if (name == "cmd_SetPIBChannelGain") amp_->setPIBChannelGain(ch, static_cast(value)); + return {OK}; +} + +void NA500Server::streamLoop() { + // Blocks are filled one sample at a time and only sent when full. A block left + // partly filled by cmd_Stop is kept (even across sessions) and completed by the + // next stream, so each new stream opens with a few stale packets, as on the device. + std::vector payload(SAMPLES_PER_BLOCK * PACKET_FORMAT2_SIZE); + int fill = 0; + auto next = std::chrono::steady_clock::now(); + uint64_t framesSinceStart = 0; + bool wasStreaming = false; + + while (!stopping_) { + if (!(streaming_ && amp_->isPowered())) { + wasStreaming = false; + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + continue; + } + if (!wasStreaming) { + wasStreaming = true; + framesSinceStart = 0; + packetCounter_ = 0; // every cmd_Start restarts the counter + next = std::chrono::steady_clock::now(); + } + + const int rate = amp_->state().activeRate(); + const int64_t stepUs = 1000000 / rate; // integer step: 62 us at 16 kHz, as on the device + const int delivered = rate < MAX_DELIVERED_RATE ? rate : MAX_DELIVERED_RATE; + const auto period = std::chrono::nanoseconds(1000000000LL / delivered); + + while (streaming_ && std::chrono::steady_clock::now() >= next) { + next += period; + PacketFormat2_SamplePacket packet; + amp_->generatePacketFormat2(packet); + packet.tr = 0; + packet.packetCounter = packetCounter_++; + packet.timeStamp = static_cast(streamStartUs_ + framesSinceStart++ * stepUs); + packet.netCode = static_cast(amp_->state().netCode); + if (!dinEnabled_) packet.digitalInputs = 0; + packet.reserved[0] = 3; // idle level of the event inputs on the recorded unit + std::memcpy(payload.data() + fill * PACKET_FORMAT2_SIZE, &packet, PACKET_FORMAT2_SIZE); + if (++fill < SAMPLES_PER_BLOCK) continue; + fill = 0; + + const AmpDataPacketHeader header{0, bswap64(payload.size())}; + std::vector block(sizeof(header) + payload.size()); + std::memcpy(block.data(), &header, sizeof(header)); + std::memcpy(block.data() + sizeof(header), payload.data(), payload.size()); + std::lock_guard lock(queueMutex_); + if (queue_.size() < SEND_QUEUE_BLOCKS) queue_.push_back(std::move(block)); + queueCv_.notify_one(); + } + std::this_thread::sleep_until(next); + } +} + +void NA500Server::sendLoop() { + while (!stopping_) { + std::vector block; + { + std::unique_lock lock(queueMutex_); + queueCv_.wait_for(lock, std::chrono::milliseconds(50), + [this] { return !queue_.empty() || stopping_; }); + if (queue_.empty()) continue; + block = std::move(queue_.front()); + queue_.pop_front(); + } + std::shared_ptr socket; + { + std::lock_guard lock(socketMutex_); + socket = dataSocket_; + } + if (!socket) continue; // no data client: the block is lost + asio::error_code ec; + asio::write(*socket, asio::buffer(block), ec); + if (ec) { + // The device never serves this port again this session. + std::lock_guard lock(socketMutex_); + if (dataSocket_ == socket) dataSocket_.reset(); + } + } +} + +} // namespace mock diff --git a/mock/src/main.cpp b/mock/src/main.cpp index 530d4ab..e25550f 100644 --- a/mock/src/main.cpp +++ b/mock/src/main.cpp @@ -3,6 +3,7 @@ #include "DataStreamGenerator.h" #include "ECIHandler.h" #include "MockAmplifier.h" +#include "NA500Server.h" #include "NotificationHandler.h" #include @@ -36,6 +37,7 @@ void printUsage(const char* programName) { << " HGSN32, HGSN64, HGSN128, HGSN256 - HydroCel GSN nets\n" << " MGSN32, MGSN64, MGSN128, MGSN256 - MicroCel GSN nets\n" << " TestConnector - Test connector (256 channels)\n" + << " None - No net attached\n" << std::endl; } @@ -52,6 +54,7 @@ mock::NetCode parseNetCode(const std::string& str) { if (str == "MGSN128") return mock::NetCode::MCGSN128_1_0; if (str == "MGSN256") return mock::NetCode::MCGSN256_1_0; if (str == "TestConnector") return mock::NetCode::TestConnector; + if (str == "None") return mock::NetCode::Unknown; // what an NA500 reports with no net return mock::NetCode::GSN256_2_0; // default } @@ -124,6 +127,14 @@ int main(int argc, char* argv[]) { amplifier->setSerialNumber(serialNumber); amplifier->setPhysioConnectionStatus(physioStatus); + // The NA500's AmpServer is session based (one client per port, no ECI) + // and is emulated separately; see NA500Server.h. + if (ampType == mock::AmplifierType::NA500) { + mock::NA500Server server(amplifier, cmdPort, notifyPort, dataPort); + server.run(g_running); + return 0; + } + // Create handlers auto notificationHandler = std::make_shared( io_context, notifyPort, amplifier); diff --git a/resources/sampling_rates.json b/resources/sampling_rates.json index 60d9340..5b7b48b 100644 --- a/resources/sampling_rates.json +++ b/resources/sampling_rates.json @@ -58,10 +58,10 @@ } }, "NA500": { - "_note": "Rates verified against hardware on 2026-08-31 (serial 0007, system_version 0.4.9, fpga_version 0.6.1.f0). Unlike the NA400, the NA500 sends no duplicate packets at sub-1000 Hz decimated rates, and its native mode extends down to 250 Hz and up to 16000 Hz.", + "_note": "Rates verified against hardware on 2026-08-31 (serial 0007, system_version 0.4.9, fpga_version 0.6.1.f0). Unlike the NA400, the NA500 sends no duplicate packets at sub-1000 Hz decimated rates, and its native mode extends down to 250 Hz and up to 8000 Hz. It accepts 16000 Hz but delivers only ~8000 samples/s there (measured 2026-10-26), so 16000 is not offered.", "_delay_note": "All shifts 0 = no timestamp compensation in decimated mode. This matches Net Station 6.0.0.60960: libEgiDataSource.dll PhysicalAmp::calculateShift() applies anti-alias shifts only for NA400 (112/66/36 ms eeg, 80/28/3 ms pns) and NA410 (76/34/13, 64/24/3) and leaves the NA500 at zero (verified by decompilation 2026-08-31). If a real DIN->EEG delay is ever measured for NA500 decimated mode (scripts/delay_capture_sweep.py), update these values.", "available_rates": [250, 500, 1000, 2000], - "fast_recovery_rates": [250, 500, 1000, 2000, 4000, 8000, 16000], + "fast_recovery_rates": [250, 500, 1000, 2000, 4000, 8000], "source_rate": 1000, "eeg_shift_msec": { "250": 0, diff --git a/scripts/ampserver_conformance.py b/scripts/ampserver_conformance.py new file mode 100644 index 0000000..ee8b15e --- /dev/null +++ b/scripts/ampserver_conformance.py @@ -0,0 +1,493 @@ +#!/usr/bin/env python3 +""" +Record how an AmpServer behaves on the wire, and diff two recordings. + +Used to keep the mock (mock/MockAmpServer --amp-type NA500) aligned with a real +GES 500 / Net Amps 500: record the device once, then record the mock and diff. + + # record (Net Station and every other client must be disconnected: + # the NA500 serves one client per session) + python ampserver_conformance.py --host NA500-256ch-0001.local --active -o na500.json + python ampserver_conformance.py --host 127.0.0.1 --active -o mock.json + # compare; exits 1 on any difference + python ampserver_conformance.py --compare na500.json mock.json + +Every scenario opens a fresh session and closes it at the end. On the NA500 +closing the command connection ends the session, so scenarios do not leak state +into each other. Keys starting with "~" are informational (timings, clocks) and +are not compared. + +--active powers the amplifier on and streams; without it only commands that do +not touch the analog front end are sent. +""" + +import argparse +import json +import re +import socket +import struct +import sys +import threading +import time +from collections import Counter + +CMD_PORT, NTN_PORT, DATA_PORT = 9877, 9878, 9879 +HEADER = struct.Struct(">qQ") # amp id, payload length (big-endian) +PACKET2_SIZE = 1264 +# Packet format 2 fields we inspect (little-endian): din u16 @0, counter u64 @25, +# timestamp u64 @33, net code u8 @41, first reserved byte @42. +PKT = struct.Struct(")", line) + + +class Reader(threading.Thread): + """Collects newline-terminated lines from a socket with arrival times.""" + + def __init__(self, sock): + super().__init__(daemon=True) + self.sock, self.lines, self.closed = sock, [], False + self.start() + + def run(self): + buf = b"" + while True: + try: + chunk = self.sock.recv(65536) + except OSError: + chunk = b"" + if not chunk: + self.closed = True + return + buf += chunk + while b"\n" in buf: + line, buf = buf.split(b"\n", 1) + if line.strip(): + self.lines.append((time.monotonic(), line.decode(errors="replace"))) + + +class DataReader(threading.Thread): + """Parses data-port frames: header + payload of format-2 packets.""" + + def __init__(self, sock): + super().__init__(daemon=True) + self.sock, self.blocks, self.packets, self.closed = sock, [], [], False + self.start() + + def _read(self, n): + out = b"" + while len(out) < n: + chunk = self.sock.recv(n - len(out)) + if not chunk: + raise EOFError + out += chunk + return out + + def run(self): + try: + while True: + amp_id, length = HEADER.unpack(self._read(HEADER.size)) + payload = self._read(length) + self.blocks.append((time.monotonic(), amp_id, length)) + for off in range(0, length - PACKET2_SIZE + 1, PACKET2_SIZE): + self.packets.append(PKT.unpack_from(payload, off)) + except (EOFError, OSError): + self.closed = True + + +class Session: + def __init__(self, host, data=False, ntn=True): + self.host = host + self.cmd = self._connect(CMD_PORT) + self.cmd_reader = Reader(self.cmd) + self.ntn = Reader(self._connect(NTN_PORT)) if ntn else None + self.data = DataReader(self._connect(DATA_PORT)) if data else None + + def _connect(self, port): + sock = socket.create_connection((self.host, port), timeout=5) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + sock.settimeout(None) + return sock + + def raw(self, payload, quiet=0.6, first=3.0): + """Send bytes, return every reply line until `quiet` s pass with none.""" + start = len(self.cmd_reader.lines) + t0 = time.monotonic() + self.cmd.sendall(payload if isinstance(payload, bytes) else payload.encode()) + deadline = t0 + first + while time.monotonic() < deadline: + time.sleep(0.02) + if len(self.cmd_reader.lines) > start: + deadline = max(deadline, self.cmd_reader.lines[-1][0] + quiet) + if time.monotonic() > self.cmd_reader.lines[-1][0] + quiet: + break + got = self.cmd_reader.lines[start:] + return [normalize(l) for _, l in got], (round(got[0][0] - t0, 2) if got else None) + + def send(self, command, channel=0, value=0, **kw): + return self.raw(f"(sendCommand {command} 0 {channel} {value})\n", **kw) + + def notifications(self, since=0): + return [l for _, l in self.ntn.lines[since:]] if self.ntn else [] + + def close(self): + for s in (self.cmd, self.ntn and self.ntn.sock, self.data and self.data.sock): + if s: + try: + s.close() + except OSError: + pass + time.sleep(1.0) # let the server tear the session down before the next one + + +def reply_info(session, command, channel=0, value=0, **kw): + lines, latency = session.send(command, channel, value, **kw) + return {"replies": lines, "~latency_s": latency} + + +# ---------------------------------------------------------------- passive + +QUERIES = ["cmd_NumberOfAmps", "cmd_GetAmpDetails", "cmd_GetAmpStatus", "cmd_GetBatteryData", + "cmd_GetBoardStatus", "cmd_NumberOfActiveAmps", "cmd_GetPhysioConnectionStatus", + "cmd_GetCurrentTime", "cmd_GetCurrentDrift", "cmd_GetNetRecordingTime", + "cmd_ReceiveNotifications", "cmd_StopReceivingNotifications", "cmd_None"] + + +def scenario_queries(host): + s = Session(host) + try: + out = {c: reply_info(s, c, -1, -1) for c in QUERIES} + out["notifications"] = s.notifications() + return out + finally: + s.close() + + +def scenario_framing(host): + s = Session(host) + try: + s.send("cmd_NumberOfAmps", -1, -1) + two = (b"(sendCommand cmd_NumberOfAmps 0 -1 -1)\n" + b"(sendCommand cmd_GetAmpDetails 0 -1 -1)\n") + out = {"two_in_one_segment": s.raw(two)[0], + "double_newline": s.raw(b"(sendCommand cmd_NumberOfAmps 0 -1 -1)\n\n")[0], + "extra_space": s.raw(b"(sendCommand cmd_NumberOfAmps 0 -1 -1)\n")[0]} + s.send("cmd_NumberOfAmps", -1, -1) + out["unknown_after_NumberOfAmps"] = s.send("cmd_NoSuchCommand", -1, -1)[0] + s.send("cmd_NumberOfAmps", -1, -1) + s.cmd.sendall(b"(sendCommand cmd_GetAmp") + time.sleep(0.3) + out["split_across_segments"] = s.raw(b"Details 0 -1 -1)\n")[0] + s.send("cmd_NumberOfAmps", -1, -1) + out["lowercase_setPIBChannelGain"] = s.send("cmd_setPIBChannelGain", 0, 12)[0] + return out + finally: + s.close() + + +def scenario_odd_replies(host): + s = Session(host) + try: + out = {} + for name, (cmd, ch, val) in { + "ListenToAmp_on_cmd_port": ("cmd_ListenToAmp", 0, 0), + "StopListeningToAmp_on_cmd_port": ("cmd_StopListeningToAmp", 0, 0), + "SetDecimatedRate_300": ("cmd_SetDecimatedRate", 0, 300), + "SetNativeRate_300": ("cmd_SetNativeRate", 0, 300), + "SetPower_2": ("cmd_SetPower", 0, 2), + "TurnAllZeroOhms_0": ("cmd_TurnAllZeroOhms", 0, 0), + "SetMRIPulseInfo_0": ("cmd_SetMRIPulseInfo", 0, 0), + }.items(): + out[name] = s.send(cmd, ch, val, first=2.0)[0] + # A fresh, well-known reply shows whether the session is still usable. + out[name + "_then_NumberOfAmps"] = s.send("cmd_NumberOfAmps", -1, -1)[0] + return out + finally: + s.close() + + +def scenario_second_client(host): + s = Session(host) + try: + s.send("cmd_NumberOfAmps", -1, -1) + out = {} + try: + second = socket.create_connection((host, CMD_PORT), timeout=3) + second.settimeout(3) + second.sendall(b"(sendCommand cmd_NumberOfAmps 0 -1 -1)\n") + try: + out["second_client_reply"] = normalize(second.recv(4096).decode().strip()) + except socket.timeout: + out["second_client_reply"] = None + second.close() + out["second_client_connects"] = True + except OSError: + out["second_client_connects"] = False + out["first_client_still_served"] = s.send("cmd_NumberOfAmps", -1, -1)[0] + return out + finally: + s.close() + + +# Names to check for recognition. An unrecognized name re-runs the previous +# command on the NA500, so each is sent right after cmd_NumberOfAmps. All are +# sent with value 0, which leaves the amplifier in its idle state. +NAMES = ["cmd_Reset", "cmd_DefaultAcquisitionState", "cmd_DefaultSignalGeneration", "cmd_Exit", + "cmd_TurnAll10KOhms", "cmd_TurnChannel10KOhms", "cmd_SetCOM10KOhms", + "cmd_TurnAllDriveSignals", "cmd_TurnChannelDriveSignals", "cmd_SetSubjectGround", + "cmd_SetCurrentSource", "cmd_SetCalibrationSignalFreq", "cmd_SetBufferedReference", + "cmd_SetOscillatorGate", "cmd_SetReference10KOhms", "cmd_SetReferenceDriveSignal", + "cmd_SetWaveShape", "cmd_SetDrivenCommon", "cmd_SetCalibrationSignalAmplitude", + "cmd_SetAnalogOutput", "cmd_SetDigitalOutputData", "cmd_SetDigitalInOutDirection", + "cmd_GetStartTime", "cmd_SetPIBChannelGain", "cmd_TurnChannelZeroOhms", + "cmd_SetPhoticStimSequence", "cmd_SetSpo2Enable", "cmd_SetDinEnable", "cmd_SetTestMode", + "cmd_SetOpticalClockMode", "cmd_SetRecordingState", "cmd_SetBncInMode", + "cmd_SetBncOutMode", "cmd_SetBncOutPulseWidth", "cmd_SetBlankingPulseWidth", + "cmd_SetTriggerBncManualOut", "cmd_SetQuietMode", "cmd_SetNetRecordingTime", + "cmd_SetFilterAndDecimate", "cmd_GTENGetStatus"] + + +def scenario_recognized(host): + s = Session(host) + try: + baseline = s.send("cmd_NumberOfAmps", -1, -1)[0] + out = {} + for name in NAMES: + s.send("cmd_NumberOfAmps", -1, -1) + out[name] = s.send(name, 0, 0)[0] != baseline + return out + finally: + s.close() + + +# ---------------------------------------------------------------- active + +def summarize_stream(d, seconds_host): + pk = d.packets + if not pk: + return {"packets": 0, "blocks": len(d.blocks)} + # A new stream may open with leftovers of the previous one (old counter and + # clock) before its own counter starts at 0; measure the stream after them. + reset = next((i for i, p in enumerate(pk) if p[1] == 0), 0) + counters = [p[1] for p in pk[reset:]] + stamps = [p[2] for p in pk[reset:]] + diffs = Counter(b - a for a, b in zip(stamps, stamps[1:])) + return { + "header_amp_ids": sorted({b[1] for b in d.blocks}), + "packets_per_block": sorted({b[2] // PACKET2_SIZE for b in d.blocks}), + "payload_multiple_of_1264": all(b[2] % PACKET2_SIZE == 0 for b in d.blocks), + "counter_starts_at_0": counters[0] == 0, + "counter_step_set": sorted({b - a for a, b in zip(counters, counters[1:])}), + "timestamp_step_us_top": [k for k, _ in diffs.most_common(2)], + "net_codes": sorted({p[3] for p in pk}), + "din_most_common": hex(Counter(p[0] for p in pk[reset:]).most_common(1)[0][0]), + "reserved0_values": sorted({p[4] for p in pk}), + "~stale_packets_before_reset": reset, + "~packets": len(pk), + "~rate_by_host_clock": round(len(pk) / seconds_host), + "~rate_by_timestamps": round((len(stamps) - 1) * 1e6 / max(1, stamps[-1] - stamps[0])), + "~amp_clock_minus_host_s": round(stamps[-1] / 1e6 - time.time(), 1), + } + + +def stream_for(s, seconds): + """Collect everything the data port delivers for `seconds` from now.""" + t0 = time.monotonic() + s.data.packets.clear() + s.data.blocks.clear() + time.sleep(seconds) + return time.monotonic() - t0 + + +def scenario_power(host): + s = Session(host) + try: + out = {} + for v in (1, 0): + n = len(s.ntn.lines) + out[f"SetPower_{v}"] = reply_info(s, "cmd_SetPower", 0, v, quiet=1.0) + time.sleep(1.0) + out[f"SetPower_{v}_notifications"] = s.notifications(n) + return out + finally: + s.close() + + +def scenario_stream(host, rate, mode="Decimated"): + s = Session(host, data=True) + try: + out = {} + s.send("cmd_SetPower", 0, 1) + out[f"Set{mode}Rate"] = s.send(f"cmd_Set{mode}Rate", 0, rate)[0] + n = len(s.ntn.lines) + s.data.packets.clear() + s.data.blocks.clear() + t0 = time.monotonic() + out["Start"] = reply_info(s, "cmd_Start", -1, -1) + out["Start_notifications"] = s.notifications(n) + # No cmd_ListenToAmp on the data port: does data flow anyway? + time.sleep(2.0) + out["stream_without_ListenToAmp"] = summarize_stream(s.data, time.monotonic() - t0) + n = len(s.ntn.lines) + out["GetStartTime"] = reply_info(s, "cmd_GetStartTime", -1, -1) + out["GetCurrentTime"] = reply_info(s, "cmd_GetCurrentTime", -1, -1) + out["SetRecordingState_0"] = reply_info(s, "cmd_SetRecordingState", -1, 0) + out["GetStartTime_notifications"] = s.notifications(n) + n = len(s.ntn.lines) + out["Stop"] = reply_info(s, "cmd_Stop", -1, -1, quiet=1.0, first=5.0) + time.sleep(0.5) + out["Stop_notifications"] = s.notifications(n) + # A second Start in the same session. + s.data.packets.clear() + s.data.blocks.clear() + t0 = time.monotonic() + s.send("cmd_Start", -1, -1) + time.sleep(1.0) + restart = summarize_stream(s.data, time.monotonic() - t0) + out["restart_counter_starts_at_0"] = restart.get("counter_starts_at_0") + out["~restart_stale_packets"] = restart.get("~stale_packets_before_reset") + s.send("cmd_Stop", -1, -1, first=5.0) + s.send("cmd_SetPower", 0, 0) + return out + finally: + s.close() + + +def scenario_data_reconnect(host): + s = Session(host, data=True) + try: + out = {} + s.send("cmd_SetPower", 0, 1) + s.send("cmd_SetDecimatedRate", 0, 1000) + s.send("cmd_Start", -1, -1) + time.sleep(1.0) + out["packets_before_drop"] = len(s.data.packets) > 0 + s.data.sock.close() + time.sleep(0.5) + s.data = DataReader(s._connect(DATA_PORT)) + time.sleep(2.0) + out["packets_after_reconnect"] = len(s.data.packets) > 0 + out["cmd_still_served"] = s.send("cmd_NumberOfAmps", -1, -1)[0] + s.send("cmd_Stop", -1, -1, first=5.0) + return out + finally: + s.close() + + +def scenario_stalled_reader(host): + """Start streaming but leave the data port unread for 5 s, then read.""" + s = Session(host) + data = s._connect(DATA_PORT) + try: + s.send("cmd_SetPower", 0, 1) + s.send("cmd_SetDecimatedRate", 0, 1000) + s.send("cmd_Start", -1, -1) + time.sleep(5.0) + s.data = DataReader(data) + time.sleep(2.0) + pk = s.data.packets + reset = next((i for i, p in enumerate(pk) if p[1] == 0), 0) + steps = [b[1] - a[1] for a, b in zip(pk[reset:], pk[reset + 1:])] + s.send("cmd_Stop", -1, -1, first=5.0) + s.send("cmd_SetPower", 0, 0) + return {"samples_lost": any(step > 1 for step in steps), + "~largest_counter_jump": max(steps, default=0)} + finally: + s.close() + + +def scenario_after_session_end(host): + """Leave the amp powered and streaming, drop the session, then Start only.""" + s = Session(host, data=True) + s.send("cmd_SetPower", 0, 1) + s.send("cmd_SetDecimatedRate", 0, 1000) + s.send("cmd_Start", -1, -1) + time.sleep(1.0) + s.close() + s = Session(host, data=True) + try: + time.sleep(1.0) + out = {"data_flows_in_new_session_before_Start": len(s.data.packets) > 0} + s.send("cmd_Start", -1, -1) + out["stream_after_Start_without_SetPower"] = summarize_stream(s.data, stream_for(s, 1.5)) + s.send("cmd_Stop", -1, -1, first=5.0) + s.send("cmd_SetPower", 0, 0) + return out + finally: + s.close() + + +def record(host, active): + scenarios = { + "queries": scenario_queries, + "framing": scenario_framing, + "odd_replies": scenario_odd_replies, + "second_client": scenario_second_client, + "recognized": scenario_recognized, + } + if active: + scenarios.update({ + "power": scenario_power, + "stream_decimated_250": lambda h: scenario_stream(h, 250), + "stream_decimated_1000": lambda h: scenario_stream(h, 1000), + "stream_native_16000": lambda h: scenario_stream(h, 16000, "Native"), + "data_reconnect": scenario_data_reconnect, + "stalled_reader": scenario_stalled_reader, + "after_session_end": scenario_after_session_end, + }) + results = {} + for name, fn in scenarios.items(): + print(f"[{name}] ...", file=sys.stderr, flush=True) + try: + results[name] = fn(host) + except Exception as exc: # record and keep going: one wedge must not hide the rest + results[name] = {"error": f"{type(exc).__name__}: {exc}"} + return results + + +def flatten(d, prefix=""): + for k, v in d.items(): + key = f"{prefix}{k}" + if isinstance(v, dict): + yield from flatten(v, key + ".") + else: + yield key, v + + +def compare(path_a, path_b): + a, b = (dict(flatten(json.load(open(p)))) for p in (path_a, path_b)) + keys = sorted(k for k in a.keys() | b.keys() if not k.rsplit(".", 1)[-1].startswith("~")) + diffs = [k for k in keys if a.get(k) != b.get(k)] + for k in diffs: + print(f"{k}\n {path_a}: {a.get(k)!r}\n {path_b}: {b.get(k)!r}") + print(f"{len(diffs)} difference(s) in {len(keys)} compared keys") + return 1 if diffs else 0 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--host") + ap.add_argument("--active", action="store_true", help="power on and stream") + ap.add_argument("-o", "--output", help="write the recording here (default: stdout)") + ap.add_argument("--compare", nargs=2, metavar=("A", "B")) + args = ap.parse_args() + if args.compare: + sys.exit(compare(*args.compare)) + if not args.host: + ap.error("--host is required unless --compare is given") + text = json.dumps(record(args.host, args.active), indent=1) + if args.output: + open(args.output, "w").write(text + "\n") + else: + print(text) + + +if __name__ == "__main__": + main() diff --git a/src/core/include/egiamp/AmpServerProtocol.h b/src/core/include/egiamp/AmpServerProtocol.h index 2f3bdb1..e4da475 100644 --- a/src/core/include/egiamp/AmpServerProtocol.h +++ b/src/core/include/egiamp/AmpServerProtocol.h @@ -151,7 +151,8 @@ inline float getScalingFactor(AmplifierType type) { // Rate/mode capabilities per model, verified against hardware where possible. // NA400 (measured): decimated 250/500/1000; native 500/1000/2000/4000/8000. // NA500 (measured, fw 0.4.9): decimated 250/500/1000/2000; native -// 250/500/1000/2000/4000/8000/16000. Unlike the NA400, the NA500 never sends +// 250/500/1000/2000/4000/8000. It accepts 16000 but delivers only ~8000 +// samples/s there, so 16000 is not offered. Unlike the NA400, the NA500 never sends // duplicate packets at sub-1000 Hz decimated rates. inline int maxDecimatedRate(AmplifierType type) { return type == AmplifierType::NA500 ? 2000 : 1000; @@ -190,7 +191,7 @@ inline bool supportsSampleRate(AmplifierType type, int sampleRate, bool fastReco : contains({250, 500, 1000}); case AmplifierType::NA500: // Verified on hardware (fw 0.4.9) - return native ? contains({250, 500, 1000, 2000, 4000, 8000, 16000}) + return native ? contains({250, 500, 1000, 2000, 4000, 8000}) : contains({250, 500, 1000, 2000}); default: return true; diff --git a/src/core/src/EGIAmpClient.cpp b/src/core/src/EGIAmpClient.cpp index 3473650..7da2e10 100644 --- a/src/core/src/EGIAmpClient.cpp +++ b/src/core/src/EGIAmpClient.cpp @@ -456,6 +456,11 @@ bool EGIAmpClient::initAmplifier() { // would add an unverified dependency on its notification timing. if (details_.amplifierType == AmplifierType::NA500) { connection_.sendCommand("cmd_ReceiveNotifications", ampId, 0, "0"); + // The NA500 stamps packets with its own clock, which nothing else keeps + // in sync; set it to UTC epoch us at power-on, as Net Station does. + const auto nowUs = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + connection_.sendCommand("cmd_SetAmpTime", ampId, 0, std::to_string(nowUs)); connection_.sendCommand("cmd_SetPower", ampId, 0, "1"); emitStatus("Waiting for amplifier power-on...\n"); if (waitForAmpPowerOn(30)) { @@ -691,7 +696,10 @@ bool EGIAmpClient::startStreaming() { auto& notifStream = connection_.notificationStream(); const std::regex statusRegex(R"(ntn_PhysioConnectionStatus\s+\d+\s+\d+\s+\+(\d+))"); - for (int attempt = 0; attempt < 10; attempt++) { + // The NA500 never sends ntn_PhysioConnectionStatus, and leaving its data + // port unread for these 5 s makes it silently drop ~4 s of samples. + const int attempts = details_.amplifierType == AmplifierType::NA500 ? 0 : 10; + for (int attempt = 0; attempt < attempts; attempt++) { notifStream.clear(); // Reset stream state after any prior timeout connection_.setNotificationStreamTimeout(std::chrono::milliseconds(500)); char notifBuffer[4096]; @@ -1021,6 +1029,12 @@ void EGIAmpClient::readPacketFormat2() { uint64_t lastPacketCounter = 0; int nChannels = details_.channelCount; bool firstPacketReceived = false; + // After a cmd_Start the NA500 first sends leftover packets from its previous + // stream (old counter and clock, possibly from an earlier session); its own + // counter then restarts at 0. Bounded so a missed reset cannot stall the stream. + constexpr int MAX_STALE_PACKETS = 128; + int staleToSkip = details_.amplifierType == AmplifierType::NA500 && weInitializedAmp_ + ? MAX_STALE_PACKETS : 0; // Sample rate change detection bool measuringNewRate = false; @@ -1066,6 +1080,14 @@ void EGIAmpClient::readPacketFormat2() { PacketFormat2 packet{}; stream.read(reinterpret_cast(&packet), sizeof(PacketFormat2)); + if (staleToSkip > 0) { + if (packet.packetCounter != 0) { + --staleToSkip; + continue; + } + staleToSkip = 0; + } + if (!streamer_.hasOutlet()) { // Determine channel count and sensor from net code details_.netCode = static_cast(packet.netCode); @@ -1342,6 +1364,8 @@ void EGIAmpClient::readPacketFormat2() { emitStatus("Stream recovered. Resuming data reading.\n"); lastPacketCounter = 0; firstPacketReceived = false; + staleToSkip = details_.amplifierType == AmplifierType::NA500 && weInitializedAmp_ + ? MAX_STALE_PACKETS : 0; measuringNewRate = false; rateCheckSampleCount = 0; lastTimeStamp_ = 0; @@ -1519,7 +1543,8 @@ void EGIAmpClient::reQueryPhysioStatus() { auto& notifStream = connection_.notificationStream(); const std::regex statusRegex(R"(ntn_PhysioConnectionStatus\s+\d+\s+\d+\s+\+(\d+))"); - for (int attempt = 0; attempt < 10; attempt++) { + const int attempts = details_.amplifierType == AmplifierType::NA500 ? 0 : 10; // see startStreaming() + for (int attempt = 0; attempt < attempts; attempt++) { notifStream.clear(); connection_.setNotificationStreamTimeout(std::chrono::milliseconds(500)); char notifBuffer[4096]; diff --git a/src/gui/EGIAmpWindow.cpp b/src/gui/EGIAmpWindow.cpp index 5233278..f166271 100644 --- a/src/gui/EGIAmpWindow.cpp +++ b/src/gui/EGIAmpWindow.cpp @@ -369,7 +369,6 @@ void EGIAmpWindow::populateSampleRateCombo() { {"2000 Hz \xe2\x80\x94 Low Latency", 2000, true}, {"4000 Hz", 4000, true}, {"8000 Hz", 8000, true}, - {"16000 Hz (NA500 only)", 16000, true}, }; ui->sampleRateComboBox->clear(); From 4a5e0426e47bdd93078ea3ca5384a2f109c8dd93 Mon Sep 17 00:00:00 2001 From: Chadwick Boulay Date: Mon, 26 Oct 2026 02:24:30 -0400 Subject: [PATCH 2/8] NA500: enable the front end so the EEG leaves full scale On the NA500 the EEG reads negative full scale until cmd_SetBufferedReference 1, every cmd_Stop switches it off again, and switch commands sent within ~20 ms of the cmd_SetPower 1 reply are silently lost. The app sent neither, so its NA500 EEG was pinned at -375000 uV. It now waits 200 ms after power-on and enables the buffered reference before each cmd_Start (NA500 only; skipped in impedance mode). The mock and the conformance recorder model and check all three behaviors; the recorder also waits briefly after connecting so the NA500 has accepted the notification port before the first command. --- README.md | 1 + docs/NA500_AmpServer.md | 11 ++++++- mock/conformance/na500_fw0.4.9.json | 39 ++++++++++++++--------- mock/include/NA500Server.h | 2 ++ mock/src/NA500Server.cpp | 14 ++++++++- scripts/ampserver_conformance.py | 43 ++++++++++++++++++++++++-- src/core/include/egiamp/EGIAmpClient.h | 1 + src/core/src/EGIAmpClient.cpp | 15 +++++++++ 8 files changed, 107 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index cc9ec37..0ac3b3e 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ Differences from the NA400 that this app handles automatically: - **Data connection handling**: the NA500's AmpServer serves one data listener per session; once it disconnects, no new listener is served until the command connection closes and a new session starts. The app therefore maintains one persistent data connection per session and never issues `cmd_StopListeningToAmp` (which the NA500 never answers). - **Continuous reading**: the NA500 drops samples if its data port goes unread for a few seconds, so the app does not wait for a Physio16 status notification (the NA500 sends none). - **Stale packets**: after `cmd_Start` the NA500 first resends leftover packets from its previous stream before its counter restarts at 0; the app discards them. +- **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`. - **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). - **Recovery**: the NA500 sends `ntn_AmpStarted` only in reply to `cmd_GetStartTime`, not when streaming starts, so external-restart recovery uses data-port polling instead. diff --git a/docs/NA500_AmpServer.md b/docs/NA500_AmpServer.md index c92d0f7..0050731 100644 --- a/docs/NA500_AmpServer.md +++ b/docs/NA500_AmpServer.md @@ -58,6 +58,14 @@ data on 9879). Only the differences that matter to a client are listed. - The server does not shut down on `cmd_Exit`. GTEN commands and `cmd_SetFilterAndDecimate` are not recognized (so they re-run the previous command). +## Front end + +- After power-on the EEG channels read negative full scale (-8388608 counts) until + `cmd_SetBufferedReference 1` is sent. `cmd_Stop` switches the buffered reference off again, so send + it after every stop (before or after `cmd_Start`; either works). +- Front-end switch commands sent within about 20 ms of the `cmd_SetPower 1` reply are lost, although + they are acknowledged. Wait a moment after power-on before configuring. + ## Notifications Only four are sent, each after the reply to the command that causes it: @@ -69,7 +77,8 @@ Only four are sent, each after the reply to the command that causes it: | `(notification ntn_AmpStarted 10 0 -1)` | `cmd_GetStartTime` (**not** `cmd_Start`) | | `(notification ntn_AmpStopped 11 0 -1)` | `cmd_Stop` | -There is no `ntn_PhysioConnectionStatus` and no client-connected notification. +There is no `ntn_PhysioConnectionStatus` and no client-connected notification. A notification can be +lost if its command is sent the instant the notification port connects, before the server has accepted it. ## Data stream diff --git a/mock/conformance/na500_fw0.4.9.json b/mock/conformance/na500_fw0.4.9.json index 382d355..d3a377e 100644 --- a/mock/conformance/na500_fw0.4.9.json +++ b/mock/conformance/na500_fw0.4.9.json @@ -238,11 +238,12 @@ "reserved0_values": [ 3 ], - "~stale_packets_before_reset": 7, - "~packets": 616, - "~rate_by_host_clock": 236, + "eeg_railed": 1.0, + "~stale_packets_before_reset": 51, + "~packets": 664, + "~rate_by_host_clock": 254, "~rate_by_timestamps": 250, - "~amp_clock_minus_host_s": 0.2 + "~amp_clock_minus_host_s": 0.1 }, "GetStartTime": { "replies": [ @@ -275,7 +276,7 @@ "(notification ntn_AmpStopped 11 0 -1)" ], "restart_counter_starts_at_0": true, - "~restart_stale_packets": 0 + "~restart_stale_packets": 5 }, "stream_decimated_1000": { "SetDecimatedRate": [ @@ -310,11 +311,12 @@ "reserved0_values": [ 3 ], - "~stale_packets_before_reset": 3, - "~packets": 2464, - "~rate_by_host_clock": 940, + "eeg_railed": 1.0, + "~stale_packets_before_reset": 7, + "~packets": 2472, + "~rate_by_host_clock": 943, "~rate_by_timestamps": 1000, - "~amp_clock_minus_host_s": 0.3 + "~amp_clock_minus_host_s": 0.1 }, "GetStartTime": { "replies": [ @@ -347,7 +349,7 @@ "(notification ntn_AmpStopped 11 0 -1)" ], "restart_counter_starts_at_0": true, - "~restart_stale_packets": 0 + "~restart_stale_packets": 1 }, "stream_native_16000": { "SetNativeRate": [ @@ -382,11 +384,12 @@ "reserved0_values": [ 3 ], - "~stale_packets_before_reset": 3, - "~packets": 19640, - "~rate_by_host_clock": 7533, + "eeg_railed": 1.0, + "~stale_packets_before_reset": 2, + "~packets": 19704, + "~rate_by_host_clock": 7529, "~rate_by_timestamps": 16129, - "~amp_clock_minus_host_s": -1.0 + "~amp_clock_minus_host_s": -1.1 }, "GetStartTime": { "replies": [ @@ -419,7 +422,7 @@ "(notification ntn_AmpStopped 11 0 -1)" ], "restart_counter_starts_at_0": true, - "~restart_stale_packets": 4 + "~restart_stale_packets": 0 }, "data_reconnect": { "packets_before_drop": true, @@ -432,6 +435,12 @@ "samples_lost": true, "~largest_counter_jump": 4481 }, + "front_end": { + "railed_when_set_right_after_power_on": 1.0, + "railed_after_Start": 1.0, + "railed_after_SetBufferedReference_1": 0.0, + "railed_after_Stop_Start": 1.0 + }, "after_session_end": { "data_flows_in_new_session_before_Start": false, "stream_after_Start_without_SetPower": { diff --git a/mock/include/NA500Server.h b/mock/include/NA500Server.h index e224ad1..5a2d936 100644 --- a/mock/include/NA500Server.h +++ b/mock/include/NA500Server.h @@ -54,6 +54,8 @@ class NA500Server { std::atomic stopping_{false}; std::atomic streaming_{false}; std::atomic dinEnabled_{false}; + std::atomic bufferedReference_{false}; // EEG sits at the rail while off + std::chrono::steady_clock::time_point poweredOnAt_{}; // front end ignores commands just after std::thread streamThread_; // Full blocks waiting to be written to the data client. Bounded like the // device's send ring: while the client is not reading, new blocks are lost. diff --git a/mock/src/NA500Server.cpp b/mock/src/NA500Server.cpp index 130bbad..141c411 100644 --- a/mock/src/NA500Server.cpp +++ b/mock/src/NA500Server.cpp @@ -4,7 +4,9 @@ #include #include #include +#include #include +#include #include namespace mock { @@ -168,6 +170,7 @@ void NA500Server::session(const std::atomic& running) { dataAccept.join(); // The DIN enable survives into the next session, as on the device. streaming_ = false; + bufferedReference_ = false; amp_->setPower(false); { std::lock_guard lock(socketMutex_); @@ -198,6 +201,7 @@ std::vector NA500Server::execute(const std::string& name, long long if (name == "cmd_SetPower") { if (value != 0 && value != 1) return {}; amp_->setPower(on); + if (on) poweredOnAt_ = std::chrono::steady_clock::now(); if (!on) streaming_ = false; pendingNotifications_.push_back(on ? "(notification ntn_AmpPowerOn 9 0 -1)" : "(notification ntn_AmpPowerOff 8 0 -1)"); @@ -210,6 +214,7 @@ std::vector NA500Server::execute(const std::string& name, long long } if (name == "cmd_Stop") { streaming_ = false; + bufferedReference_ = false; // cmd_Stop switches the front end off std::this_thread::sleep_for(std::chrono::seconds(1)); pendingNotifications_.push_back("(notification ntn_AmpStopped 11 0 -1)"); return {OK}; @@ -285,7 +290,13 @@ std::vector NA500Server::execute(const std::string& name, long long else if (name == "cmd_SetCOMDriveSignal") amp_->setComDriveSignal(on); else if (name == "cmd_SetSubjectGround") amp_->setSubjectGround(on); else if (name == "cmd_SetDrivenCommon") amp_->setDrivenCommon(on); - else if (name == "cmd_SetBufferedReference") amp_->setBufferedReference(on); + else if (name == "cmd_SetBufferedReference") { + // The front end is still powering up for ~20 ms after cmd_SetPower 1 + // and silently drops switch commands (the reply is still OK). + if (std::chrono::steady_clock::now() - poweredOnAt_ >= std::chrono::milliseconds(20)) { + bufferedReference_ = on; + } + } else if (name == "cmd_SetOscillatorGate") amp_->setOscillatorGate(on); else if (name == "cmd_SetWaveShape") amp_->setWaveShape(static_cast(value)); else if (name == "cmd_SetCalibrationSignalFreq") amp_->setCalibrationSignalFreq(static_cast(value)); @@ -331,6 +342,7 @@ void NA500Server::streamLoop() { packet.timeStamp = static_cast(streamStartUs_ + framesSinceStart++ * stepUs); packet.netCode = static_cast(amp_->state().netCode); if (!dinEnabled_) packet.digitalInputs = 0; + if (!bufferedReference_) std::fill(std::begin(packet.eegData), std::end(packet.eegData), -8388608); packet.reserved[0] = 3; // idle level of the event inputs on the recorded unit std::memcpy(payload.data() + fill * PACKET_FORMAT2_SIZE, &packet, PACKET_FORMAT2_SIZE); if (++fill < SAMPLES_PER_BLOCK) continue; diff --git a/scripts/ampserver_conformance.py b/scripts/ampserver_conformance.py index ee8b15e..0bf6d06 100644 --- a/scripts/ampserver_conformance.py +++ b/scripts/ampserver_conformance.py @@ -35,8 +35,9 @@ HEADER = struct.Struct(">qQ") # amp id, payload length (big-endian) PACKET2_SIZE = 1264 # Packet format 2 fields we inspect (little-endian): din u16 @0, counter u64 @25, -# timestamp u64 @33, net code u8 @41, first reserved byte @42. -PKT = struct.Struct("= RAIL for p in pk[reset:]) / max(1, len(pk) - reset), 1), "~stale_packets_before_reset": reset, "~packets": len(pk), "~rate_by_host_clock": round(len(pk) / seconds_host), @@ -403,6 +408,39 @@ def scenario_stalled_reader(host): s.close() +def scenario_front_end(host): + """Is the EEG usable before and after cmd_SetBufferedReference, and after a Stop?""" + s = Session(host, data=True) + try: + def railed(): + s.data.packets.clear() + time.sleep(1.5) + pk = s.data.packets[-500:] + return round(sum(abs(p[5]) >= RAIL for p in pk) / max(1, len(pk)), 1) + # A switch command sent the moment cmd_SetPower 1 is answered. + n = len(s.cmd_reader.lines) + s.cmd.sendall(b"(sendCommand cmd_SetPower 0 0 1)\n") + while len(s.cmd_reader.lines) == n: + time.sleep(0.0005) + s.send("cmd_SetBufferedReference", 0, 1, quiet=0.05) + s.send("cmd_SetDecimatedRate", 0, 1000) + s.send("cmd_Start", -1, -1) + out = {"railed_when_set_right_after_power_on": railed()} + s.send("cmd_Stop", -1, -1, first=5.0) + s.send("cmd_Start", -1, -1) + out["railed_after_Start"] = railed() + s.send("cmd_SetBufferedReference", 0, 1) + out["railed_after_SetBufferedReference_1"] = railed() + s.send("cmd_Stop", -1, -1, first=5.0) + s.send("cmd_Start", -1, -1) + out["railed_after_Stop_Start"] = railed() + s.send("cmd_Stop", -1, -1, first=5.0) + s.send("cmd_SetPower", 0, 0) + return out + finally: + s.close() + + def scenario_after_session_end(host): """Leave the amp powered and streaming, drop the session, then Start only.""" s = Session(host, data=True) @@ -440,6 +478,7 @@ def record(host, active): "stream_native_16000": lambda h: scenario_stream(h, 16000, "Native"), "data_reconnect": scenario_data_reconnect, "stalled_reader": scenario_stalled_reader, + "front_end": scenario_front_end, "after_session_end": scenario_after_session_end, }) results = {} diff --git a/src/core/include/egiamp/EGIAmpClient.h b/src/core/include/egiamp/EGIAmpClient.h index 400bbfb..53e2175 100644 --- a/src/core/include/egiamp/EGIAmpClient.h +++ b/src/core/include/egiamp/EGIAmpClient.h @@ -91,6 +91,7 @@ class EGIAmpClient { int detectSampleRate(); // Returns detected sample rate, or 0 if detection failed bool initAmplifier(); void haltAmplifier(); + void enableNA500FrontEnd(); // no-op on other models void readPacketFormat1(); void readPacketFormat2(); diff --git a/src/core/src/EGIAmpClient.cpp b/src/core/src/EGIAmpClient.cpp index 7da2e10..29e6d77 100644 --- a/src/core/src/EGIAmpClient.cpp +++ b/src/core/src/EGIAmpClient.cpp @@ -468,6 +468,9 @@ bool EGIAmpClient::initAmplifier() { } else { emitStatus("Warning: no power-on confirmation within 30 s, continuing.\n"); } + // Front-end switch commands sent within ~20 ms of power-on are silently + // lost (measured), which leaves the EEG at full scale. Let it settle. + std::this_thread::sleep_for(std::chrono::milliseconds(200)); } // Set sample rate. Native rates have no FPGA anti-alias filter (lower @@ -505,6 +508,7 @@ bool EGIAmpClient::initAmplifier() { } else { // Set default acquisition state when not in impedance mode connection_.sendCommand("cmd_DefaultAcquisitionState", ampId, 0, "0"); + enableNA500FrontEnd(); } // Start @@ -513,6 +517,14 @@ bool EGIAmpClient::initAmplifier() { return true; } +void EGIAmpClient::enableNA500FrontEnd() { + // The NA500's EEG sits at negative full scale until its buffered reference + // is switched on, and every cmd_Stop switches it off again. + if (details_.amplifierType == AmplifierType::NA500) { + connection_.sendCommand("cmd_SetBufferedReference", config_.amplifierId, 0, "1"); + } +} + void EGIAmpClient::haltAmplifier() { emitStatus("Stopping stream...\n"); @@ -642,6 +654,9 @@ bool EGIAmpClient::startStreaming() { } } + if (!config_.impedance) { + enableNA500FrontEnd(); + } connection_.sendCommand("cmd_Start", config_.amplifierId, 0, "0"); weInitializedAmp_ = true; } else { From ab27af9a44d633701313d19f0a4fbbe8fb268c7c Mon Sep 17 00:00:00 2001 From: Chadwick Boulay Date: Mon, 26 Oct 2026 11:40:19 -0400 Subject: [PATCH 3/8] NA500: rate-dependent system-delay default; document the 8 kHz frame loss Measured with scripts/audio_latency_test against DAC-stamped tone markers, the NA500's digitization-to-client latency is ~1.0 ms + 1.1 sample periods (5.4 ms at 250 Hz, 2.1 ms at 1 kHz, 1.3 ms at 4 kHz), well under the NA400's ~5 ms, so the 4.5 ms system delay back-dated NA500 samples by 1-3 ms. systemdelayms is now optional. Unset, it defaults to 0.8 ms + one sample period on the NA500 (a little under the measured latency at every rate; verified +0.33 ms at 1 kHz) and to 4.5 ms on every other model, so NA400 behavior is unchanged. The shipped config no longer pins it. The NA500 also delivers at most ~7995 packets/s: 8 kHz silently loses ~4 samples/s (not only 16 kHz), so its timeline drifts. Documented, and the mock's delivery ceiling now matches. --- README.md | 8 ++++---- ampserver_config.cfg | 9 +++++---- docs/NA500_AmpServer.md | 7 ++++--- mock/src/NA500Server.cpp | 6 +++--- src/core/include/egiamp/AmpServerConfig.h | 6 ++++-- src/core/include/egiamp/AmpServerProtocol.h | 12 ++++++++++++ src/core/src/AmpServerConfig.cpp | 6 ++++-- src/core/src/EGIAmpClient.cpp | 4 +++- 8 files changed, 39 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 0ac3b3e..c72ecd6 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ NA500 support was verified against real hardware (firmware 0.4.9). The amplifier 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). -- **Rates**: decimated up to 2000 Hz; native from 250 Hz up to 8000 Hz. No duplicate packets are sent at low rates (the NA400 duplicates samples below 1000 Hz). 16000 Hz is not offered: the amplifier accepts it but delivers only about 8000 samples/s, and the missing samples leave no gap in its packet counter. +- **Rates**: decimated up to 2000 Hz; native from 250 Hz up to 8000 Hz. No duplicate packets are sent at low rates (the NA400 duplicates samples below 1000 Hz). 16000 Hz is not offered: the amplifier accepts it but delivers only about 8000 samples/s, and the missing samples leave no gap in its packet counter. 8000 Hz loses about 4 samples/s the same way, so its timing drifts; use 4000 Hz or below where timing matters. - **Initialization**: the NA500 silently ignores commands sent while it is powering up (~10 s from cold), so the app waits for the power-on notification before configuring it. - **Data connection handling**: the NA500's AmpServer serves one data listener per session; once it disconnects, no new listener is served until the command connection closes and a new session starts. The app therefore maintains one persistent data connection per session and never issues `cmd_StopListeningToAmp` (which the NA500 never answers). - **Continuous reading**: the NA500 drops samples if its data port goes unread for a few seconds, so the app does not wait for a Physio16 status notification (the NA500 sends none). @@ -157,9 +157,9 @@ There is **no flag to toggle this** — it follows the configured mode automatic ### 1. System (pipeline) delay — always applied -Every pushed timestamp (EEG, Physio16, **and** DIN) is moved earlier by `systemdelayms` to account for the time between digitization and the sample becoming available here: device firmware + network transmission + our read path. Measured at ~5 ms in native mode using `scripts/audio_latency_test`. +Every pushed timestamp (EEG, Physio16, **and** DIN) is moved earlier by `systemdelayms` to account for the time between digitization and the sample becoming available here: device firmware + network transmission + our read path. Measured using `scripts/audio_latency_test` at ~5 ms on the NA400, and on the NA500 at ~1.0 ms plus 1.1 sample periods (5.4 ms at 250 Hz, 2.1 ms at 1000 Hz, 1.3 ms at 4000 Hz). -The default is **4.5 ms** — deliberately a little *under* the measured value. Under-compensating is the safe direction: it guarantees a sample is never back-dated to *before* the event that produced it (a response must not precede its stimulus). It is user-configurable; raise it toward the measured latency if you prefer tighter alignment and can accept that risk. +The default is **4.5 ms** (NA400 and other models) and **0.8 ms + one sample period** on the NA500 (4.8 ms at 250 Hz, 1.8 ms at 1000 Hz) — deliberately a little *under* the measured value. Under-compensating is the safe direction: it guarantees a sample is never back-dated to *before* the event that produced it (a response must not precede its stimulus). It is user-configurable; raise it toward the measured latency if you prefer tighter alignment and can accept that risk. ### 2. FPGA filter offset — decimated mode only @@ -177,7 +177,7 @@ Both values live in the config file (and persist via File → Save Configuration ... 33 - 4.5 + 4.5 ``` diff --git a/ampserver_config.cfg b/ampserver_config.cfg index da425c9..e422771 100644 --- a/ampserver_config.cfg +++ b/ampserver_config.cfg @@ -17,8 +17,9 @@ 33 - 4.5 + network + read path), measured via scripts/audio_latency_test: ~5 ms on + the NA400, ~1 ms + 1.1 sample periods on the NA500. When unset the app uses + a little less (4.5 ms; NA500: 0.8 ms + one sample period) so a sample is + never back-dated before its event. Setting it overrides every model. --> + \ No newline at end of file diff --git a/docs/NA500_AmpServer.md b/docs/NA500_AmpServer.md index 0050731..7d13ad0 100644 --- a/docs/NA500_AmpServer.md +++ b/docs/NA500_AmpServer.md @@ -92,9 +92,10 @@ lost if its command is sent the instant the notification port connects, before t - Timestamps are microseconds on the amplifier's clock, advancing by exactly `1e6 / rate` per packet truncated to an integer (62 µs at 16 kHz). The clock is not synchronized: the unit we measured was a month behind until a client sent `cmd_SetAmpTime`. -- At 16000 Hz only about 8000 packets/s are delivered while timestamps and counters advance as if all - 16000 were sent: about half the samples are lost without a trace. Rates up to 8000 Hz are delivered in - full. +- The amplifier delivers at most about 7995 packets/s, while timestamps and counters advance as if + every sample were sent. At 16000 Hz about half the samples are lost without a trace; at 8000 Hz about + 4 per second are, enough to make the sample timeline drift by milliseconds over a minute. Rates up to + 4000 Hz are delivered in full. - If the client stops reading for a few seconds, the amplifier drops samples once about 1 MB is 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 diff --git a/mock/src/NA500Server.cpp b/mock/src/NA500Server.cpp index 141c411..1a396c5 100644 --- a/mock/src/NA500Server.cpp +++ b/mock/src/NA500Server.cpp @@ -15,9 +15,9 @@ namespace { constexpr int SAMPLES_PER_BLOCK = 8; constexpr std::size_t SEND_QUEUE_BLOCKS = 8; -// Above this the device drops frames silently: at 16 kHz timestamps still step -// 62 us and the counter steps 1, but only ~8000 packets/s arrive. -constexpr int MAX_DELIVERED_RATE = 8000; +// Above this the device drops frames silently (timestamps and counter advance as +// if all were sent): measured ~7995 packets/s at both 8 kHz and 16 kHz. +constexpr int MAX_DELIVERED_RATE = 7995; // The amp's clock is not synced until a client sends cmd_SetAmpTime; the unit // we recorded was about a month behind. constexpr int64_t STALE_CLOCK_US = -30LL * 24 * 3600 * 1000000; diff --git a/src/core/include/egiamp/AmpServerConfig.h b/src/core/include/egiamp/AmpServerConfig.h index b32ed01..60aa403 100644 --- a/src/core/include/egiamp/AmpServerConfig.h +++ b/src/core/include/egiamp/AmpServerConfig.h @@ -2,6 +2,7 @@ #define EGIAMP_AMPSERVERCONFIG_H #include +#include #include #include @@ -31,8 +32,9 @@ struct AmpServerConfig { // scripts/audio_latency_test (native modes). Applied unconditionally, on top // of the decimated-only FPGA filter offset. Default intentionally slightly // under the measured value so we never back-date a sample *before* its event - // (a response cannot precede its stimulus); user-tunable. - double systemDelayMs = 4.5; + // (a response cannot precede its stimulus); user-tunable. Unset means the + // per-model default, defaultSystemDelayMs() in AmpServerProtocol.h. + std::optional systemDelayMs; bool impedance = false; bool nativeFormat = false; // When true, transmit raw int32 ADC counts instead of float microvolts diff --git a/src/core/include/egiamp/AmpServerProtocol.h b/src/core/include/egiamp/AmpServerProtocol.h index e4da475..7b1e4d4 100644 --- a/src/core/include/egiamp/AmpServerProtocol.h +++ b/src/core/include/egiamp/AmpServerProtocol.h @@ -154,6 +154,18 @@ inline float getScalingFactor(AmplifierType type) { // 250/500/1000/2000/4000/8000. It accepts 16000 but delivers only ~8000 // samples/s there, so 16000 is not offered. Unlike the NA400, the NA500 never sends // duplicate packets at sub-1000 Hz decimated rates. +// Digitization-to-client latency (ms) subtracted from every timestamp when the +// config does not set one, a little under the value measured with +// scripts/audio_latency_test so a sample is never back-dated before its event. +// NA400: ~5 ms. NA500: ~1.0 ms + 1.1 sample periods (5.4 ms at 250 Hz down to +// 1.0 ms at 8 kHz), so its default follows the rate. +inline double defaultSystemDelayMs(AmplifierType type, int sampleRate) { + if (type == AmplifierType::NA500 && sampleRate > 0) { + return 0.8 + 1000.0 / sampleRate; + } + return 4.5; +} + inline int maxDecimatedRate(AmplifierType type) { return type == AmplifierType::NA500 ? 2000 : 1000; } diff --git a/src/core/src/AmpServerConfig.cpp b/src/core/src/AmpServerConfig.cpp index 3fa30e4..df6ca4a 100644 --- a/src/core/src/AmpServerConfig.cpp +++ b/src/core/src/AmpServerConfig.cpp @@ -68,7 +68,7 @@ AmpServerConfig AmpServerConfig::loadFromFile(const std::string& filename) { config.physioAlignDelayMs = node.text().as_int(config.physioAlignDelayMs); } if (auto node = settings.child("systemdelayms")) { - config.systemDelayMs = node.text().as_double(config.systemDelayMs); + config.systemDelayMs = node.text().as_double(); } } @@ -93,7 +93,9 @@ void AmpServerConfig::saveToFile(const std::string& filename) const { settings.append_child("nativeformat").text().set(nativeFormat); settings.append_child("fastrecovery").text().set(fastRecovery); settings.append_child("physioaligndelayms").text().set(physioAlignDelayMs); - settings.append_child("systemdelayms").text().set(systemDelayMs); + if (systemDelayMs) { + settings.append_child("systemdelayms").text().set(*systemDelayMs); + } if (!doc.save_file(filename.c_str())) { throw ConfigError("Could not write to config file: " + filename); diff --git a/src/core/src/EGIAmpClient.cpp b/src/core/src/EGIAmpClient.cpp index 29e6d77..ade9c73 100644 --- a/src/core/src/EGIAmpClient.cpp +++ b/src/core/src/EGIAmpClient.cpp @@ -1075,7 +1075,9 @@ void EGIAmpClient::readPacketFormat2() { // timestamp reflects digitization time, not arrival. This flows to // both the EEG/physio chunk and the DIN events (derived below), and // is on top of the decimated-only filter offset applied in pushChunk. - double batchTimestamp = lsl::local_clock() - config_.systemDelayMs / 1000.0; + double batchTimestamp = lsl::local_clock() - + config_.systemDelayMs.value_or( + defaultSystemDelayMs(details_.amplifierType, config_.sampleRate)) / 1000.0; header.ampID = big_to_native(header.ampID); header.length = big_to_native(header.length); From 4f6a3d02b06a577e57c0fab46d00103bf0ae3832 Mon Sep 17 00:00:00 2001 From: Chadwick Boulay Date: Mon, 26 Oct 2026 11:55:31 -0400 Subject: [PATCH 4/8] NA500: stop offering 8000 Hz The NA500 delivers at most ~7995 samples/s and silently drops the rest, so at 8000 Hz it loses ~4 samples/s and the sample timeline drifts by milliseconds over a run (measured with the audio latency test). 4000 Hz is now the NA500's highest rate; the NA400's rates are unchanged. --- README.md | 4 ++-- resources/sampling_rates.json | 4 ++-- src/core/include/egiamp/AmpServerProtocol.h | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c72ecd6..eda73ba 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ Bypasses the FPGA filter and samples directly at the requested rate. This provid - Reduced bandwidth (~1/4 of sample rate, e.g., 250 Hz at 1000 Hz sample rate) - Optimized for EEG-TMS and real-time BCI applications -Available native rates: 500, 1000, 2000, 4000, 8000 Hz (NA400); 250, 500, 1000, 2000, 4000, 8000 Hz (NA500) +Available native rates: 500, 1000, 2000, 4000, 8000 Hz (NA400); 250, 500, 1000, 2000, 4000 Hz (NA500) Use `--fast-recovery` (or a "Low Latency" dropdown entry) to select native mode for rates where the model offers both. @@ -138,7 +138,7 @@ NA500 support was verified against real hardware (firmware 0.4.9). The amplifier 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). -- **Rates**: decimated up to 2000 Hz; native from 250 Hz up to 8000 Hz. No duplicate packets are sent at low rates (the NA400 duplicates samples below 1000 Hz). 16000 Hz is not offered: the amplifier accepts it but delivers only about 8000 samples/s, and the missing samples leave no gap in its packet counter. 8000 Hz loses about 4 samples/s the same way, so its timing drifts; use 4000 Hz or below where timing matters. +- **Rates**: decimated up to 2000 Hz; native from 250 Hz up to 4000 Hz. No duplicate packets are sent at low rates (the NA400 duplicates samples below 1000 Hz). 8000 and 16000 Hz are not offered: the amplifier accepts them but delivers at most about 7995 samples/s, and the missing samples leave no gap in its packet counter (about 4 samples/s lost at 8000 Hz, half at 16000 Hz). - **Initialization**: the NA500 silently ignores commands sent while it is powering up (~10 s from cold), so the app waits for the power-on notification before configuring it. - **Data connection handling**: the NA500's AmpServer serves one data listener per session; once it disconnects, no new listener is served until the command connection closes and a new session starts. The app therefore maintains one persistent data connection per session and never issues `cmd_StopListeningToAmp` (which the NA500 never answers). - **Continuous reading**: the NA500 drops samples if its data port goes unread for a few seconds, so the app does not wait for a Physio16 status notification (the NA500 sends none). diff --git a/resources/sampling_rates.json b/resources/sampling_rates.json index 5b7b48b..64dc87f 100644 --- a/resources/sampling_rates.json +++ b/resources/sampling_rates.json @@ -58,10 +58,10 @@ } }, "NA500": { - "_note": "Rates verified against hardware on 2026-08-31 (serial 0007, system_version 0.4.9, fpga_version 0.6.1.f0). Unlike the NA400, the NA500 sends no duplicate packets at sub-1000 Hz decimated rates, and its native mode extends down to 250 Hz and up to 8000 Hz. It accepts 16000 Hz but delivers only ~8000 samples/s there (measured 2026-10-26), so 16000 is not offered.", + "_note": "Rates verified against hardware on 2026-08-31 (serial 0007, system_version 0.4.9, fpga_version 0.6.1.f0). Unlike the NA400, the NA500 sends no duplicate packets at sub-1000 Hz decimated rates, and its native mode extends down to 250 Hz and up to 4000 Hz. It accepts 8000 and 16000 Hz but delivers at most ~7995 samples/s, silently dropping the rest (measured 2026-10-26), so neither is offered.", "_delay_note": "All shifts 0 = no timestamp compensation in decimated mode. This matches Net Station 6.0.0.60960: libEgiDataSource.dll PhysicalAmp::calculateShift() applies anti-alias shifts only for NA400 (112/66/36 ms eeg, 80/28/3 ms pns) and NA410 (76/34/13, 64/24/3) and leaves the NA500 at zero (verified by decompilation 2026-08-31). If a real DIN->EEG delay is ever measured for NA500 decimated mode (scripts/delay_capture_sweep.py), update these values.", "available_rates": [250, 500, 1000, 2000], - "fast_recovery_rates": [250, 500, 1000, 2000, 4000, 8000], + "fast_recovery_rates": [250, 500, 1000, 2000, 4000], "source_rate": 1000, "eeg_shift_msec": { "250": 0, diff --git a/src/core/include/egiamp/AmpServerProtocol.h b/src/core/include/egiamp/AmpServerProtocol.h index 7b1e4d4..261e8b2 100644 --- a/src/core/include/egiamp/AmpServerProtocol.h +++ b/src/core/include/egiamp/AmpServerProtocol.h @@ -151,8 +151,8 @@ inline float getScalingFactor(AmplifierType type) { // Rate/mode capabilities per model, verified against hardware where possible. // NA400 (measured): decimated 250/500/1000; native 500/1000/2000/4000/8000. // NA500 (measured, fw 0.4.9): decimated 250/500/1000/2000; native -// 250/500/1000/2000/4000/8000. It accepts 16000 but delivers only ~8000 -// samples/s there, so 16000 is not offered. Unlike the NA400, the NA500 never sends +// 250/500/1000/2000/4000. It accepts 8000 and 16000 but delivers at most ~7995 +// samples/s, silently dropping the rest, so neither is offered. Unlike the NA400, the NA500 never sends // duplicate packets at sub-1000 Hz decimated rates. // Digitization-to-client latency (ms) subtracted from every timestamp when the // config does not set one, a little under the value measured with @@ -203,7 +203,7 @@ inline bool supportsSampleRate(AmplifierType type, int sampleRate, bool fastReco : contains({250, 500, 1000}); case AmplifierType::NA500: // Verified on hardware (fw 0.4.9) - return native ? contains({250, 500, 1000, 2000, 4000, 8000}) + return native ? contains({250, 500, 1000, 2000, 4000}) : contains({250, 500, 1000, 2000}); default: return true; From e90933570289fda89970e7c402b913e0cc185efc Mon Sep 17 00:00:00 2001 From: Chadwick Boulay Date: Wed, 28 Oct 2026 17:27:17 -0400 Subject: [PATCH 5/8] NA500: stream the 16 physio channels The NA500 sends no Physio16 status notification, so the app streamed no physio at all. Its 16 physio inputs are always in the data stream (pib1_Data[0-7], pib2_Data[0-7]), so the app now always streams them as PIB1-16 on the NA500. Physio gains persist on the amplifier across sessions (a gain set by another client stays), so before each cmd_Start the app pins all 16 to 12, the power-on default, and scales them like the EEG. Measured with the audio latency test: PIB1 timing matches EEG within 0.1 ms at 250-4000 Hz, so no physio realignment is needed (filter delays are 0 on the NA500). The NA500 mock zeroes the unused physio slots, as the device does. All changes are NA500-only; the NA400 physio path is unchanged. --- README.md | 1 + docs/NA500_AmpServer.md | 9 +++++++++ mock/src/NA500Server.cpp | 3 +++ src/core/src/EGIAmpClient.cpp | 27 ++++++++++++++++++++++----- src/core/src/LSLStreamer.cpp | 3 ++- 5 files changed, 37 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index eda73ba..2c4b5a2 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ Differences from the NA400 that this app handles automatically: - **Continuous reading**: the NA500 drops samples if its data port goes unread for a few seconds, so the app does not wait for a Physio16 status notification (the NA500 sends none). - **Stale packets**: after `cmd_Start` the NA500 first resends leftover packets from its previous stream before its counter restarts at 0; the app discards them. - **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. - **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). - **Recovery**: the NA500 sends `ntn_AmpStarted` only in reply to `cmd_GetStartTime`, not when streaming starts, so external-restart recovery uses data-port polling instead. diff --git a/docs/NA500_AmpServer.md b/docs/NA500_AmpServer.md index 7d13ad0..d1a9af0 100644 --- a/docs/NA500_AmpServer.md +++ b/docs/NA500_AmpServer.md @@ -66,6 +66,15 @@ data on 9879). Only the differences that matter to a client are listed. - Front-end switch commands sent within about 20 ms of the `cmd_SetPower 1` reply are lost, although they are acknowledged. Wait a moment after power-on before configuring. +## Physio + +- The 16 physio inputs arrive in the first 8 entries of each of the packet's two physio arrays (physio + 1-8, then 9-16); the other entries are 0. They are sampled with the EEG: no relative delay at any rate + or mode. There is no notification or reply that reports whether a Physio16 is attached. +- `cmd_SetPIBChannelGain ` sets one input's gain (1, 2, 4, 6, 8, 12 or 24). At the + power-on default of 12 the physio scale equals the EEG's (0.0447 µV per count); at gain 1 it is 12 + times coarser. Gains **persist across sessions**, so a client should set them rather than assume them. + ## Notifications Only four are sent, each after the reply to the command that causes it: diff --git a/mock/src/NA500Server.cpp b/mock/src/NA500Server.cpp index 1a396c5..2f847ed 100644 --- a/mock/src/NA500Server.cpp +++ b/mock/src/NA500Server.cpp @@ -344,6 +344,9 @@ void NA500Server::streamLoop() { if (!dinEnabled_) packet.digitalInputs = 0; if (!bufferedReference_) std::fill(std::begin(packet.eegData), std::end(packet.eegData), -8388608); packet.reserved[0] = 3; // idle level of the event inputs on the recorded unit + // Only the first 8 slots of each physio array carry data on the NA500. + std::fill(std::begin(packet.pib1_Data) + 8, std::end(packet.pib1_Data), 0); + std::fill(std::begin(packet.pib2_Data) + 8, std::end(packet.pib2_Data), 0); std::memcpy(payload.data() + fill * PACKET_FORMAT2_SIZE, &packet, PACKET_FORMAT2_SIZE); if (++fill < SAMPLES_PER_BLOCK) continue; fill = 0; diff --git a/src/core/src/EGIAmpClient.cpp b/src/core/src/EGIAmpClient.cpp index ade9c73..6f59853 100644 --- a/src/core/src/EGIAmpClient.cpp +++ b/src/core/src/EGIAmpClient.cpp @@ -522,6 +522,11 @@ void EGIAmpClient::enableNA500FrontEnd() { // is switched on, and every cmd_Stop switches it off again. if (details_.amplifierType == AmplifierType::NA500) { connection_.sendCommand("cmd_SetBufferedReference", config_.amplifierId, 0, "1"); + // 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++) { + connection_.sendCommand("cmd_SetPIBChannelGain", config_.amplifierId, ch, "12"); + } } } @@ -737,7 +742,12 @@ bool EGIAmpClient::startStreaming() { // Not the physio notification, try again } - if (physioConnectionStatus_ == 0) { + if (details_.amplifierType == AmplifierType::NA500) { + // The NA500 never reports a Physio16; its 16 physio inputs are always + // in the data stream, so always stream them. + physioConnectionStatus_ = 1; + emitStatus("Physio16: streaming the NA500's 16 physio channels\n"); + } else if (physioConnectionStatus_ == 0) { emitStatus("Physio16: no device detected\n"); } } catch (...) { @@ -1278,10 +1288,14 @@ void EGIAmpClient::readPacketFormat2() { // counts so the same delay serves both the native and float paths. int32_t physioRaw[32]; int physioN = 0; - if (physioConnectionStatus_ & 0x01) { + if (details_.amplifierType == AmplifierType::NA500) { + // NA500: physio 1-8 in pib1_Data[0-7], 9-16 in pib2_Data[0-7]. + for (int ch = 0; ch < 8; ch++) physioRaw[physioN++] = packet.pib1_Data[ch]; + for (int ch = 0; ch < 8; ch++) physioRaw[physioN++] = packet.pib2_Data[ch]; + } else if (physioConnectionStatus_ & 0x01) { for (int ch = 0; ch < 16; ch++) physioRaw[physioN++] = packet.pib1_Data[ch]; } - if (physioConnectionStatus_ & 0x02) { + if (details_.amplifierType != AmplifierType::NA500 && (physioConnectionStatus_ & 0x02)) { for (int ch = 0; ch < 16; ch++) physioRaw[physioN++] = packet.pib2_Data[ch]; } physioDelay_.process(physioRaw, physioN); @@ -1315,8 +1329,11 @@ void EGIAmpClient::readPacketFormat2() { // PIB channels 1-8 use negative scaling, 9-16 use positive // scaling; the pattern repeats for each 16-channel port. for (int i = 0; i < physioN; i++) { - const float scale = (i % 16 < 8) ? PHYSIO_SCALING_1_8 - : PHYSIO_SCALING_9_16; + // NA500 physio runs at the EEG's gain by default (12). + const float scale = details_.amplifierType == AmplifierType::NA500 + ? details_.scalingFactor + : (i % 16 < 8) ? PHYSIO_SCALING_1_8 + : PHYSIO_SCALING_9_16; eegSamples.push_back(static_cast(physioRaw[i]) * scale); } diff --git a/src/core/src/LSLStreamer.cpp b/src/core/src/LSLStreamer.cpp index 13338fb..a75ab71 100644 --- a/src/core/src/LSLStreamer.cpp +++ b/src/core/src/LSLStreamer.cpp @@ -222,7 +222,8 @@ void LSLStreamer::createOutlet(const std::string& streamName, int eegChannelCoun // PIB channels 1-8 use negative scaling, 9-16 use positive scaling // Channel index within each PIB port: 0-7 negative, 8-15 positive int portChannel = i % 16; - float conversion = (portChannel < 8) ? PHYSIO_SCALING_1_8 : PHYSIO_SCALING_9_16; + float conversion = details.amplifierType == AmplifierType::NA500 ? details.scalingFactor + : (portChannel < 8) ? PHYSIO_SCALING_1_8 : PHYSIO_SCALING_9_16; ch.append_child_value("conversion", std::to_string(conversion)); } else { From cff2e95d03c95b78afbbc38be788c07446647319 Mon Sep 17 00:00:00 2001 From: Chadwick Boulay Date: Sun, 1 Nov 2026 14:50:54 -0500 Subject: [PATCH 6/8] Document serving the NA500 an address with dnsmasq on a network without DHCP --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2c4b5a2..96dccd2 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,14 @@ The NA500 rows are zero deliberately: Net Station 6 applies no anti-alias alignm NA500 support was verified against real hardware (firmware 0.4.9). The amplifier's protocol is documented, as observed on the wire, in [docs/NA500_AmpServer.md](docs/NA500_AmpServer.md). -**Finding the amplifier**: the NA500 gets its address by DHCP and advertises itself over mDNS (service `_na500._tcp`), typically as `NA500-256ch-.local`. Pass that name instead of an IP, e.g. `--address NA500-256ch-0001.local`. This works out of the box on macOS and recent Windows 10/11; Linux needs Avahi with `nss-mdns`. To list amplifiers on the network, run `dns-sd -B _na500._tcp` (macOS/Windows with Bonjour) or `avahi-browse -r _na500._tcp` (Linux). With no DHCP server on the network the amplifier has no IPv4 address, and this app cannot reach it because its AmpServer is IPv4-only. +**Finding the amplifier**: the NA500 gets its address by DHCP and advertises itself over mDNS (service `_na500._tcp`), typically as `NA500-256ch-.local`. Pass that name instead of an IP, e.g. `--address NA500-256ch-0001.local`. This works out of the box on macOS and recent Windows 10/11; Linux needs Avahi with `nss-mdns`. To list amplifiers on the network, run `dns-sd -B _na500._tcp` (macOS/Windows with Bonjour) or `avahi-browse -r _na500._tcp` (Linux). With no DHCP server on the network the amplifier has no IPv4 address, and this app cannot reach it because its AmpServer is IPv4-only. When the amplifier is cabled directly to this computer (or to a switch with no DHCP server), give the computer's adapter a static address and serve the amplifier a lease with [dnsmasq](https://thekelleys.org.uk/dnsmasq/doc.html) (`brew install dnsmasq` / `apt install dnsmasq`). For example, with the adapter `en10` set to 10.10.10.61/24: + +```bash +sudo dnsmasq -d --port=0 --interface=en10 --bind-interfaces \ + --dhcp-range=10.10.10.62,10.10.10.62,255.255.255.0,12h +``` + +`--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. Differences from the NA400 that this app handles automatically: From 8c0b567cf3a667d900abd6477a0b9018e74019ce Mon Sep 17 00:00:00 2001 From: Chadwick Boulay Date: Sun, 1 Nov 2026 15:08:38 -0500 Subject: [PATCH 7/8] NA500: enable the DB9 digital inputs and stream the BNC input The NA500's DB9 inputs read 0 until cmd_SetDinEnable, and the app never sent it, so its _DIN stream reported all 16 (active-low) inputs as active. The app now enables them, and puts the BNC input in event mode, before each start. Each rising edge on BNC in arrives as a 1 ms event in bit 2 of the packet's first reserved byte (verified with a BNC out -> BNC in loopback at 1 and 4 kHz); the app reports it in the _DIN stream as bit 16 (0x10000). On the NA400 that bit is never set, so its DIN events are unchanged. The NA500 mock emulates the BNC input from its test-jig pulse, and resets the BNC mode at the end of a session as the device does. --- README.md | 1 + docs/NA500_AmpServer.md | 13 +++++++++++++ mock/include/NA500Server.h | 1 + mock/src/NA500Server.cpp | 21 ++++++++++++++++++++- src/core/include/egiamp/EGIAmpClient.h | 1 + src/core/src/EGIAmpClient.cpp | 21 +++++++++++++++++---- 6 files changed, 53 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 96dccd2..d20f2bb 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,7 @@ Differences from the NA400 that this app handles automatically: - **Stale packets**: after `cmd_Start` the NA500 first resends leftover packets from its previous stream before its counter restarts at 0; the app discards them. - **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. - **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). - **Recovery**: the NA500 sends `ntn_AmpStarted` only in reply to `cmd_GetStartTime`, not when streaming starts, so external-restart recovery uses data-port polling instead. diff --git a/docs/NA500_AmpServer.md b/docs/NA500_AmpServer.md index d1a9af0..f76f802 100644 --- a/docs/NA500_AmpServer.md +++ b/docs/NA500_AmpServer.md @@ -75,6 +75,19 @@ data on 9879). Only the differences that matter to a client are listed. power-on default of 12 the physio scale equals the EEG's (0.0447 µV per count); at gain 1 it is 12 times coarser. Gains **persist across sessions**, so a client should set them rather than assume them. +## Triggers + +- **DB9 digital inputs** (16, active low) read 0 until `cmd_SetDinEnable` is sent (its value is + ignored), then idle at `0xFFFF`. The enable persists across sessions. +- **BNC in**: `cmd_SetBncInMode 1` (event mode) reports each rising edge as a 1 ms event in bit 2 of + the first reserved byte: one sample at 1000 Hz, four at 4000 Hz, whatever the pulse length. Mode 0 is + off. The mode is reset when the session ends. +- **BNC out**: `cmd_SetBncOutMode 1` (manual) makes `cmd_SetTriggerBncManualOut` fire one pulse of the + width set by `cmd_SetBncOutPulseWidth <µs>`. +- Bits 0 and 1 of the same byte (photocell and audio inputs) read 1 with nothing connected. +- A BNC pulse fed to the EEG inputs starts moving the EEG on the same sample as the BNC-in event and + reaches half amplitude about 1.5 samples later (the ADC filter's delay), at 1000 and 4000 Hz. + ## Notifications Only four are sent, each after the reply to the command that causes it: diff --git a/mock/include/NA500Server.h b/mock/include/NA500Server.h index 5a2d936..14bc6e3 100644 --- a/mock/include/NA500Server.h +++ b/mock/include/NA500Server.h @@ -54,6 +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 bufferedReference_{false}; // EEG sits at the rail while off std::chrono::steady_clock::time_point poweredOnAt_{}; // front end ignores commands just after std::thread streamThread_; diff --git a/mock/src/NA500Server.cpp b/mock/src/NA500Server.cpp index 2f847ed..5d63747 100644 --- a/mock/src/NA500Server.cpp +++ b/mock/src/NA500Server.cpp @@ -168,8 +168,10 @@ void NA500Server::session(const std::atomic& running) { open = false; notifyAccept.join(); dataAccept.join(); - // The DIN enable survives into the next session, as on the device. + // The DIN enable survives into the next session, as on the device; the BNC + // input configuration does not. streaming_ = false; + bncInEvents_ = false; bufferedReference_ = false; amp_->setPower(false); { @@ -273,6 +275,10 @@ std::vector NA500Server::execute(const std::string& name, long long clockOffsetUs_ = value - hostMicros(); return {OK}; } + if (name == "cmd_SetBncInMode") { + bncInEvents_ = value == 1; + return {OK}; + } if (name == "cmd_SetDinEnable") { dinEnabled_ = true; // the device ignores the value return {OK}; @@ -314,6 +320,8 @@ void NA500Server::streamLoop() { auto next = std::chrono::steady_clock::now(); uint64_t framesSinceStart = 0; bool wasStreaming = false; + uint16_t prevDin = 0xFFFF; + int bncSamplesLeft = 0; while (!stopping_) { if (!(streaming_ && amp_->isPowered())) { @@ -343,7 +351,18 @@ void NA500Server::streamLoop() { packet.netCode = static_cast(amp_->state().netCode); if (!dinEnabled_) packet.digitalInputs = 0; if (!bufferedReference_) 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. + const uint16_t din = packet.digitalInputs; + if (bncInEvents_ && (prevDin & 1) && !(din & 1)) { + bncSamplesLeft = rate >= 1000 ? rate / 1000 : 1; + } + prevDin = din; packet.reserved[0] = 3; // idle level of the event inputs on the recorded unit + if (bncSamplesLeft > 0) { + packet.reserved[0] |= 0x04; + --bncSamplesLeft; + } // Only the first 8 slots of each physio array carry data on the NA500. std::fill(std::begin(packet.pib1_Data) + 8, std::end(packet.pib1_Data), 0); std::fill(std::begin(packet.pib2_Data) + 8, std::end(packet.pib2_Data), 0); diff --git a/src/core/include/egiamp/EGIAmpClient.h b/src/core/include/egiamp/EGIAmpClient.h index 53e2175..19a023f 100644 --- a/src/core/include/egiamp/EGIAmpClient.h +++ b/src/core/include/egiamp/EGIAmpClient.h @@ -146,6 +146,7 @@ class EGIAmpClient { uint64_t lastTimeStamp_ = 0; uint64_t lastPacketCounterWithTimeStamp_ = 0; uint16_t lastDINValue_ = 0xFFFF; // DINs are active-low; 0xFFFF = idle + bool lastBncIn_ = false; // NA500 BNC input, reported as DIN bit 16 StatusCallback statusCallback_; ErrorCallback errorCallback_; diff --git a/src/core/src/EGIAmpClient.cpp b/src/core/src/EGIAmpClient.cpp index 6f59853..5e8f82d 100644 --- a/src/core/src/EGIAmpClient.cpp +++ b/src/core/src/EGIAmpClient.cpp @@ -522,6 +522,10 @@ void EGIAmpClient::enableNA500FrontEnd() { // is switched on, and every cmd_Stop switches it off again. if (details_.amplifierType == AmplifierType::NA500) { 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"); // 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++) { @@ -566,6 +570,7 @@ void EGIAmpClient::haltAmplifier() { dinStreamer_.closeOutlet(); impedanceStreamer_.closeOutlet(); lastDINValue_ = 0xFFFF; // DINs are active-low; 0xFFFF = idle (no inputs) + lastBncIn_ = false; streamLost_ = false; ampRestarted_ = false; recoveryAttempts_ = 0; @@ -1340,11 +1345,19 @@ void EGIAmpClient::readPacketFormat2() { chunkFloat.push_back(std::move(eegSamples)); } - // Track DIN changes (pushed after the loop with per-sample timestamps) - if (packet.digitalInputs != lastDINValue_) { - dinEvents.push_back({static_cast(static_cast(~packet.digitalInputs)), - uniquePackets - 1}); // 0-based index among unique samples + // Track DIN changes (pushed after the loop with per-sample timestamps). + // The NA500's BNC input (a 1 ms event at each rising edge, in bit 2 of + // the first reserved byte) is reported as DIN bit 16. + const bool bncIn = details_.amplifierType == AmplifierType::NA500 && + (packet.reserved[0] & 0x04) != 0; + if (packet.digitalInputs != lastDINValue_ || bncIn != lastBncIn_) { + int32_t active = static_cast(~packet.digitalInputs); + if (bncIn) { + active |= 0x10000; + } + dinEvents.push_back({active, uniquePackets - 1}); // 0-based index among unique samples lastDINValue_ = packet.digitalInputs; + lastBncIn_ = bncIn; } // Feed samples to impedance measurement if impedance mode is active From a37067fb7c7c1078c1224b3e08a126a2b75828a0 Mon Sep 17 00:00:00 2001 From: Chadwick Boulay Date: Sun, 1 Nov 2026 16:01:02 -0500 Subject: [PATCH 8/8] NA500: impedance mode The NA400 impedance sequence did not work on the NA500. Changes, all NA500-only unless noted: - Drive amplitude 1023 (its DAC is 10-bit), which gives ~5000 uV p-p on every channel; use Net Station's fixed 5000 uV ideal signal, since the app's self-calibration caught a switching transient (5300-5900 uV). - Switch the oscillator on after setting amplitude and frequency: the NA500 latches them at switch-on, so an app run that followed a reset drove nothing. - Measure the reference in the NA500's COM/REF measurement mode (cmd_SetCOMAndRefForMeasurement, ~1.2 s settles, then re-enable the DINs), as Net Station does. - Restore the acquisition state explicitly when impedance mode ends: cmd_DefaultAcquisitionState does nothing on the NA500. - Apply the NA500 front-end/trigger/physio setup in impedance mode too. Verified on a GES 500 with a test jig that shorts all inputs: 256/256 channels ~0 kOhm, reference ~0.5 kOhm, and normal acquisition afterwards. Mock: the NA500 mock models the 5000 uV drive, the oscillator latch and the COM/REF mode. A long-standing mock bug ignored per-channel drive/10K switches while "all" was set, so per-channel impedance never registered (this also affects the NA400 mock, which now measures per channel). --- README.md | 10 +++ docs/NA500_AmpServer.md | 15 +++++ mock/include/NA500Server.h | 4 ++ mock/src/MockAmplifier.cpp | 9 ++- mock/src/NA500Server.cpp | 23 +++++-- .../include/egiamp/ImpedanceMeasurement.h | 2 + src/core/src/EGIAmpClient.cpp | 22 +++++-- src/core/src/ImpedanceMeasurement.cpp | 64 ++++++++++++++++--- 8 files changed, 130 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index d20f2bb..c27e803 100644 --- a/README.md +++ b/README.md @@ -310,6 +310,16 @@ cmd_TurnChannelDriveSignals(N, 1) - Turn ON drive signal (reset) cmd_TurnChannel10KOhms(N, 0) - Turn OFF 10K resistor (reset) ``` +### Net Amps 500 + +The NA500 runs the same algorithm with these differences, handled automatically: +- **Drive level**: calibration amplitude 1023 (its DAC is 10-bit), which gives ~5000 µV p-p on every channel. The app uses Net Station's fixed 5000 µV ideal signal rather than self-calibrating, which catches a switching transient on this amplifier. +- **Oscillator last**: the NA500 latches amplitude and frequency when the oscillator turns on, so the app switches it on after setting them. +- **Reference**: measured in the NA500's COM/REF measurement mode (`cmd_SetCOMAndRefForMeasurement`), with ~1.2 s settling on each side; the EEG reads 0 during that step. +- **Leaving impedance mode**: `cmd_DefaultAcquisitionState` does nothing on the NA500, so the app restores the acquisition state explicitly. + +Verified on a GES 500 with a test jig that ties all inputs together (all channels ~0 kΩ, reference ~0.5 kΩ); absolute accuracy against real electrodes has not been checked. + ### Limitations and Notes - **Tiling-based scanning**: When a tiling layout is available for the detected net (32/64/128/256 HydroCel GSN nets), channels are measured in groups (~5-6 collections per full scan) rather than one at a time — no flag required, it engages automatically. A full 256-channel scan drops from ~5 minutes to roughly a minute. Nets without a tiling layout fall back to single-channel scanning. diff --git a/docs/NA500_AmpServer.md b/docs/NA500_AmpServer.md index f76f802..2d215c4 100644 --- a/docs/NA500_AmpServer.md +++ b/docs/NA500_AmpServer.md @@ -88,6 +88,21 @@ data on 9879). Only the differences that matter to a client are listed. - A BNC pulse fed to the EEG inputs starts moving the EEG on the same sample as the BNC-in event and reaches half amplitude about 1.5 samples later (the ADC filter's delay), at 1000 and 4000 Hz. +## Impedance + +- With all channels driving (`cmd_TurnAllDriveSignals 1`, `cmd_SetOscillatorGate 1`, 20 Hz sine, + `cmd_SetCalibrationSignalAmplitude 1023` (the maximum; a 10-bit DAC), buffered reference off) every + channel reads ~5000 µV p-p. Switching a channel to measuring (`cmd_TurnChannelDriveSignals 0`, + `cmd_TurnChannel10KOhms 1`) puts it behind the 10 kΩ resistor; on the measured unit about + 2 kΩ of the result is internal. +- The signal generator **latches its amplitude and frequency when the oscillator is switched on**: + set them first, then `cmd_SetOscillatorGate 1`. Changes made while it is on do not take effect. +- The reference and common electrodes are measured in a separate ADC configuration, + `cmd_SetCOMAndRefForMeasurement 1`: the EEG reads 0 and the reference and common signals arrive in the + packet's REF and COM monitor fields. Each switch needs about 1.2 s to settle, and switching back + (`… 0`) disables the DB9 inputs until `cmd_SetDinEnable` is sent again. +- `cmd_DefaultAcquisitionState` changes nothing; a client must restore the acquisition state itself. + ## Notifications Only four are sent, each after the reply to the command that causes it: diff --git a/mock/include/NA500Server.h b/mock/include/NA500Server.h index 14bc6e3..ae46647 100644 --- a/mock/include/NA500Server.h +++ b/mock/include/NA500Server.h @@ -55,6 +55,10 @@ class NA500Server { std::atomic streaming_{false}; std::atomic dinEnabled_{false}; std::atomic bncInEvents_{false}; // cmd_SetBncInMode 1; reset when the session ends + std::atomic comRefMode_{false}; // cmd_SetCOMAndRefForMeasurement 1: EEG reads 0 + // The signal generator latches amplitude and frequency when switched on. + bool oscillatorOn_ = false; + int pendingCalAmplitude_ = 0, pendingCalFreq_ = 0; std::atomic bufferedReference_{false}; // EEG sits at the rail while off std::chrono::steady_clock::time_point poweredOnAt_{}; // front end ignores commands just after std::thread streamThread_; diff --git a/mock/src/MockAmplifier.cpp b/mock/src/MockAmplifier.cpp index 069978d..604e11a 100644 --- a/mock/src/MockAmplifier.cpp +++ b/mock/src/MockAmplifier.cpp @@ -463,7 +463,8 @@ void MockAmplifier::generatePacketFormat2(PacketFormat2_SamplePacket& packet) { // Ideal signal amplitude in microvolts for impedance mode // This matches what a 0-ohm electrode would produce - constexpr double IDEAL_SIGNAL_UV = 100.0; + // The NA500 drives ~5000 uV p-p (its DAC at full scale); 100 uV elsewhere. + const double IDEAL_SIGNAL_UV = state_.amplifierType == AmplifierType::NA500 ? 2500.0 : 100.0; constexpr double REFERENCE_RESISTOR_KOHMS = 10.0; for (int ch = 0; ch < 256; ++ch) { @@ -472,8 +473,10 @@ void MockAmplifier::generatePacketFormat2(PacketFormat2_SamplePacket& packet) { double noise = (rand() % 1000 - 500) / 500.0 * 2.0; // ~2 uV noise // Check channel state for impedance measurement - bool channelDriving = state_.channelDriveSignals[ch] || state_.allDriveSignals; - bool channel10K = state_.channel10KOhms[ch] || state_.all10KOhms; + // The setAll* calls set every per-channel flag, so the per-channel flags + // alone are current (OR-ing in the "all" flag would ignore per-channel changes). + bool channelDriving = state_.channelDriveSignals[ch]; + bool channel10K = state_.channel10KOhms[ch]; if (impedanceMode) { // Use calibration signal frequency diff --git a/mock/src/NA500Server.cpp b/mock/src/NA500Server.cpp index 5d63747..2dc1086 100644 --- a/mock/src/NA500Server.cpp +++ b/mock/src/NA500Server.cpp @@ -172,6 +172,7 @@ void NA500Server::session(const std::atomic& running) { // input configuration does not. streaming_ = false; bncInEvents_ = false; + comRefMode_ = false; bufferedReference_ = false; amp_->setPower(false); { @@ -303,10 +304,18 @@ std::vector NA500Server::execute(const std::string& name, long long bufferedReference_ = on; } } - else if (name == "cmd_SetOscillatorGate") amp_->setOscillatorGate(on); + else if (name == "cmd_SetOscillatorGate") { + if (on && !oscillatorOn_) { + amp_->setCalibrationSignalAmplitude(pendingCalAmplitude_); + amp_->setCalibrationSignalFreq(pendingCalFreq_); + } + oscillatorOn_ = on; + amp_->setOscillatorGate(on); + } else if (name == "cmd_SetWaveShape") amp_->setWaveShape(static_cast(value)); - else if (name == "cmd_SetCalibrationSignalFreq") amp_->setCalibrationSignalFreq(static_cast(value)); - else if (name == "cmd_SetCalibrationSignalAmplitude") amp_->setCalibrationSignalAmplitude(static_cast(value)); + else if (name == "cmd_SetCalibrationSignalFreq") pendingCalFreq_ = static_cast(value); + else if (name == "cmd_SetCalibrationSignalAmplitude") pendingCalAmplitude_ = static_cast(value); + else if (name == "cmd_SetCOMAndRefForMeasurement") comRefMode_ = on; else if (name == "cmd_SetPIBChannelGain") amp_->setPIBChannelGain(ch, static_cast(value)); return {OK}; } @@ -350,7 +359,13 @@ void NA500Server::streamLoop() { packet.timeStamp = static_cast(streamStartUs_ + framesSinceStart++ * stepUs); packet.netCode = static_cast(amp_->state().netCode); if (!dinEnabled_) packet.digitalInputs = 0; - if (!bufferedReference_) std::fill(std::begin(packet.eegData), std::end(packet.eegData), -8388608); + if (comRefMode_) { + std::fill(std::begin(packet.eegData), std::end(packet.eegData), 0); + } else if (!bufferedReference_ && !amp_->state().oscillatorGate) { + // Railed without the buffered reference, unless the impedance + // 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. const uint16_t din = packet.digitalInputs; diff --git a/src/core/include/egiamp/ImpedanceMeasurement.h b/src/core/include/egiamp/ImpedanceMeasurement.h index 9ca87fc..d7223d9 100644 --- a/src/core/include/egiamp/ImpedanceMeasurement.h +++ b/src/core/include/egiamp/ImpedanceMeasurement.h @@ -51,6 +51,7 @@ class ImpedanceMeasurement { void setSampleRate(int rate); void setChannelCount(int count) { channelCount_ = count; } void setScalingFactor(float factor) { scalingFactor_ = factor; } + void setNA500(bool na500) { na500_ = na500; } // NA500 drive level and REF/COM sequence void setNetSize(int netSize); // Override the ideal signal for all channels (disables per-channel calibration) @@ -130,6 +131,7 @@ class ImpedanceMeasurement { int sampleRate_ = 1000; int channelCount_ = 256; float scalingFactor_ = 0.0f; + bool na500_ = false; float idealSignal_ = 0.0f; // 0 = use calibrated or DEFAULT_IDEAL_SIGNAL float meanIdealSignal_ = 0.0f; // Mean across all normal channels from calibration diff --git a/src/core/src/EGIAmpClient.cpp b/src/core/src/EGIAmpClient.cpp index 5e8f82d..b23cde3 100644 --- a/src/core/src/EGIAmpClient.cpp +++ b/src/core/src/EGIAmpClient.cpp @@ -109,6 +109,12 @@ bool EGIAmpClient::cmd_ImpedanceAcquisitionState() { impedanceMeasurement_->setSampleRate(config_.sampleRate); impedanceMeasurement_->setScalingFactor(details_.scalingFactor); + impedanceMeasurement_->setNA500(details_.amplifierType == AmplifierType::NA500); + if (details_.amplifierType == AmplifierType::NA500) { + // Net Station's ideal signal; the NA500's drive measures 5036 uV p-p on + // every channel, while self-calibration catches a switching transient. + impedanceMeasurement_->setIdealSignal(5000.0f); + } impedanceMeasurement_->setNetSize(getChannelCountFromNetCode(details_.netCode)); // Set up the amplifier in impedance measurement state @@ -497,6 +503,10 @@ bool EGIAmpClient::initAmplifier() { connection_.sendCommand("cmd_SetPower", ampId, 0, "1"); } + // NA500 front end, physio gains and triggers (impedance mode then overrides + // the front end); no-op on other models. + enableNA500FrontEnd(); + // Configure acquisition state (impedance or default) if (config_.impedance) { try { @@ -508,7 +518,6 @@ bool EGIAmpClient::initAmplifier() { } else { // Set default acquisition state when not in impedance mode connection_.sendCommand("cmd_DefaultAcquisitionState", ampId, 0, "0"); - enableNA500FrontEnd(); } // Start @@ -654,6 +663,8 @@ bool EGIAmpClient::startStreaming() { emitStatus("Using decimated rate (FPGA anti-alias filter enabled).\n"); } + enableNA500FrontEnd(); // no-op on other models + // Configure impedance state if requested if (config_.impedance) { try { @@ -664,9 +675,6 @@ bool EGIAmpClient::startStreaming() { } } - if (!config_.impedance) { - enableNA500FrontEnd(); - } connection_.sendCommand("cmd_Start", config_.amplifierId, 0, "0"); weInitializedAmp_ = true; } else { @@ -827,6 +835,12 @@ bool EGIAmpClient::startImpedanceMode() { }); impedanceMeasurement_->setSampleRate(config_.sampleRate); impedanceMeasurement_->setScalingFactor(details_.scalingFactor); + impedanceMeasurement_->setNA500(details_.amplifierType == AmplifierType::NA500); + if (details_.amplifierType == AmplifierType::NA500) { + // Net Station's ideal signal; the NA500's drive measures 5036 uV p-p on + // every channel, while self-calibration catches a switching transient. + impedanceMeasurement_->setIdealSignal(5000.0f); + } impedanceMeasurement_->setNetSize(getChannelCountFromNetCode(details_.netCode)); // Set up the amplifier in impedance measurement state diff --git a/src/core/src/ImpedanceMeasurement.cpp b/src/core/src/ImpedanceMeasurement.cpp index 333cba9..2bd6250 100644 --- a/src/core/src/ImpedanceMeasurement.cpp +++ b/src/core/src/ImpedanceMeasurement.cpp @@ -124,16 +124,26 @@ bool ImpedanceMeasurement::setupImpedanceState() { // Driven leg (common) OFF {"cmd_SetDrivenCommon", "0"}, - // Calibration amplitude: maximum (4095 = 12 bits all set) - {"cmd_SetCalibrationSignalAmplitude", "4095"}, + // Calibration amplitude: maximum (4095 = 12 bits all set; the NA500's + // DAC is 10-bit, so 1023, which gives ~5000 uV p-p on every channel) + {"cmd_SetCalibrationSignalAmplitude", na500_ ? "1023" : "4095"}, }; for (const auto& [cmd, value] : commands) { + // The NA500's signal generator latches amplitude and frequency when the + // oscillator is switched on, so it is switched on last (below). + if (na500_ && cmd == "cmd_SetOscillatorGate") { + continue; + } if (!sendCommand(cmd, 0, value)) { emitStatus("Failed to send command: " + cmd + "\n"); return false; } } + if (na500_ && !sendCommand("cmd_SetOscillatorGate", 0, "1")) { + emitStatus("Failed to send command: cmd_SetOscillatorGate\n"); + return false; + } emitStatus("Impedance state configured.\n"); return true; @@ -191,6 +201,23 @@ bool ImpedanceMeasurement::calibrate() { bool ImpedanceMeasurement::resetToDefaultState() { emitStatus("Resetting to default acquisition state...\n"); + if (na500_) { + // cmd_DefaultAcquisitionState does nothing on the NA500, so restore its + // acquisition state explicitly: drive signal off, buffered reference on. + const std::pair commands[] = { + {"cmd_TurnAll10KOhms", "0"}, {"cmd_TurnAllDriveSignals", "0"}, + {"cmd_SetSubjectGround", "1"}, {"cmd_SetCurrentSource", "0"}, + {"cmd_SetBufferedReference", "1"}, {"cmd_SetDrivenCommon", "0"}, + {"cmd_SetReference10KOhms", "0"}, {"cmd_SetReferenceDriveSignal", "0"}, + {"cmd_SetCalibrationSignalAmplitude", "0"}, {"cmd_SetWaveShape", "0"}, + {"cmd_SetCalibrationSignalFreq", "0"}, {"cmd_SetOscillatorGate", "0"}, + }; + bool ok = true; + for (const auto& [cmd, value] : commands) { + ok = sendCommand(cmd, 0, value) && ok; + } + return ok; + } return sendCommand("cmd_DefaultAcquisitionState", 0, "0"); } @@ -441,14 +468,35 @@ ChannelImpedance ImpedanceMeasurement::measureReference() { result.impedanceKOhms = MAX_IMPEDANCE_KOHMS; result.amplitude = 0.0f; - // Put reference in measurement mode - setReferenceDriving(false); + std::deque packets; + if (na500_) { + // The NA500 measures REF (and COM) in a separate ADC configuration: the + // EEG reads 0 and REF arrives in refMonitor. Each switch needs ~1.2 s to + // settle, and switching back disables the DB9 inputs. + const auto settle = std::chrono::milliseconds(1200); + sendCommand("cmd_SetCOMAndRefForMeasurement", 0, "1"); + std::this_thread::sleep_for(settle); + setupImpedanceState(); + sendCommand("cmd_SetReferenceDriveSignal", 0, "1"); + std::this_thread::sleep_for(settle); + sendCommand("cmd_SetReferenceDriveSignal", 0, "0"); + sendCommand("cmd_SetReference10KOhms", 0, "1"); + sendCommand("cmd_SetCOM10KOhms", 0, "1"); + packets = collectSampleBuffer(); + sendCommand("cmd_SetCOMAndRefForMeasurement", 0, "0"); + std::this_thread::sleep_for(settle); + sendCommand("cmd_SetDinEnable", 0, "1"); + setupImpedanceState(); // back to all channels driving + } else { + // Put reference in measurement mode + setReferenceDriving(false); - // Collect sample buffer and extract from the dedicated refMonitor field - std::deque packets = collectSampleBuffer(); + // Collect sample buffer and extract from the dedicated refMonitor field + packets = collectSampleBuffer(); - // Reset reference to driving mode - setReferenceDriving(true); + // Reset reference to driving mode + setReferenceDriving(true); + } std::vector samples; samples.reserve(packets.size());