Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ The CLI provides a lightweight alternative to the GUI:
- `--fast-recovery` - Use native rate mode (no FPGA anti-alias filter) for lower latency. See [Sample Rate Modes](#sample-rate-modes).
- `--impedance` - Enable impedance testing mode
- `--native-format` - Transmit raw int32 ADC counts instead of float microvolts
- `--remote-port <port>` - Serve [remote control](#remote-control) commands on 127.0.0.1:`<port>`; the CLI then keeps running until Ctrl+C, even when unlinked or if the initial link fails
- `--shutdown` - Shutdown the Amp Server (terminates all connections)
- `--help` - Show help message

Expand Down Expand Up @@ -153,7 +154,7 @@ Differences from the NA400 that this app handles automatically:
- **Front end**: the NA500's EEG reads full scale until its buffered reference is switched on, every `cmd_Stop` switches it off, and switch commands sent within ~20 ms of power-on are lost; the app waits briefly after power-on and enables the buffered reference before each `cmd_Start`.
- **Physio16**: the NA500 never reports whether a Physio16 is attached, so the app always streams its 16 physio channels (PIB1-16) after the EEG. Physio gains persist on the amplifier, so the app sets them to 12, the power-on default, before each start; the physio is then scaled like the EEG (±375 mV range) and needs no realignment delay.
- **Triggers**: the app enables the NA500's DB9 digital inputs (without that they read as all 16 active) and its BNC input. Each rising edge on BNC in appears in the `_DIN` stream as bit 16 (value `0x10000`) for 1 ms, alongside the 16 DB9 bits. The EEG trails a BNC-in event by about 1.5 samples (the ADC filter's delay); no correction is applied, as in Net Station.
- **BNC output trigger**: the GUI's *BNC Trigger* button (enabled while linked to an NA500) sends a 1 ms TTL pulse (0 to 5 V) on the BNC output; `EGIAmpClient::triggerBncOut()` takes widths of 100-1600 µs. The amplifier makes each pulse about 6.7% longer than set (a 1 ms setting measures 1.07 ms); the app sends the width as is, as Net Station does. Cable BNC out to BNC in to see each pulse in the `_DIN` stream. The mock (`--amp-type NA500`) loops its BNC output back to its BNC input.
- **BNC output trigger**: the GUI's *BNC Trigger* button (enabled while linked to an NA500) and the remote control `trigger` command send a TTL pulse (0 to 5 V) on the BNC output: 1 ms by default, or 100-1600 µs via `trigger <width_us>`. The amplifier makes each pulse about 6.7% longer than set (a 1 ms setting measures 1.07 ms); the app sends the width as is, as Net Station does. Cable BNC out to BNC in to see each pulse in the `_DIN` stream. The mock (`--amp-type NA500`) loops its BNC output back to its BNC input.
- **Clock**: the NA500 stamps packets with its own clock, which is not synchronized; the app sets it with `cmd_SetAmpTime` at power-on, as Net Station does.
- **Single client**: while Net Station (or any other client) is linked to the NA500, this app's connections are accepted but not serviced — and vice versa. Unlink Net Station before using this app; concurrent monitoring is not possible on the NA500 (unlike the NA400).
- **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.
Expand Down Expand Up @@ -366,6 +367,30 @@ if imp_sample:
eeg_sample, timestamp = eeg_inlet.pull_sample()
```

## Remote Control

Both the CLI and the GUI can serve a remote control service that does everything the GUI does: change settings, load/save a configuration, link/unlink, toggle impedance mode, shut down the AmpServer, and fire the NA500's BNC output trigger. It is off by default. Enable it with `--remote-port <port>` (CLI) or `<remoteport>` in the `<settings>` section of the configuration file (CLI and GUI; read at startup). It listens on 127.0.0.1 only and has no authentication, so only programs on the same computer can use it. One client is served at a time.

The protocol is line based: send one command per line, read one reply line, `OK[ ...]` or `ERROR <message>`. Commands block until done (`link` can take 15+ s on a cold NA500). In the GUI, remote commands drive the window, so it always shows the current state.

| Command | Effect |
|---------|--------|
| `status` | `OK linked=0/1 impedance=0/1 address=... command_port=... notification_port=... data_port=... sample_rate=... fast_recovery=0/1`, plus `amplifier=... serial=... net=...` while linked |
| `set <key> <value>` | Change a setting while unlinked: `address`, `command_port`, `notification_port`, `data_port`, `sample_rate`, `fast_recovery` (0/1). In the CLI, a rate set this way is forced as with `--sample-rate`; the GUI attaches to a running amplifier as is. |
| `load <file>` / `save <file>` | Load (while unlinked) or save a configuration file |
| `link` / `unlink` | Start / stop streaming |
| `impedance on` / `impedance off` | Impedance mode, while linked |
| `trigger [width_us]` | NA500 only, while linked: one TTL pulse on the BNC output, 100-1600 µs (default 1000) |
| `shutdown_ampserver` | Terminate the AmpServer process, while unlinked (no confirmation) |
| `help` | List the commands |

```bash
./EGIAmpServerCLI --address NA500-256ch-0001.local --remote-port 9890 &
printf 'status\ntrigger\n' | nc 127.0.0.1 9890
```

`scripts/remote_control_test.py` exercises the service end to end (with `MockAmpServer --amp-type NA500`, which loops BNC out back to BNC in).

## Digital Inputs (DIN)

The DIN values are published on a **separate LSL stream** (not as a channel in the EEG stream). The stream is event-driven: a sample is only pushed when the DIN value changes.
Expand Down
81 changes: 81 additions & 0 deletions scripts/remote_control_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""End-to-end check of the remote control service and the NA500 BNC output trigger.

Start the CLI (or GUI with <remoteport> in its config) with remote control, e.g.
EGIAmpServerCLI --address 127.0.0.1 --remote-port 9890
against `MockAmpServer --amp-type NA500` or a real Net Amps 500, then run
python scripts/remote_control_test.py --port 9890
The trigger check needs BNC out cabled to BNC in on a real amplifier (the mock
loops it back internally); skip it with --no-loopback.
"""

import argparse
import socket
import time

import pylsl


class Remote:
def __init__(self, port):
self.sock = socket.create_connection(("127.0.0.1", port), timeout=60)
self.file = self.sock.makefile("r")

def __call__(self, line):
self.sock.sendall((line + "\n").encode())
reply = self.file.readline().strip()
print(f"> {line}\n< {reply}")
return reply


def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--port", type=int, default=9890)
ap.add_argument("--no-loopback", action="store_true", help="skip the BNC out -> BNC in check")
args = ap.parse_args()
r = Remote(args.port)

assert r("help").startswith("OK")
assert r("bogus").startswith("ERROR")
if "linked=1" in r("status"):
assert r("unlink") == "OK"
assert r("set sample_rate 1000") == "OK"
assert r("set data_port 0").startswith("ERROR")
assert "sample_rate=1000" in r("status")
assert r("trigger").startswith("ERROR") # not linked
assert r("link") == "OK"
assert r("link").startswith("ERROR")
status = r("status")
assert "linked=1" in status
assert r("set sample_rate 500").startswith("ERROR") # linked

if "Net_Amps_500" in status and not args.no_loopback:
assert r("trigger 50").startswith("ERROR") # out of range
din = pylsl.resolve_bypred("type='Markers' and contains(name,'_DIN')", 1, 10.0)
assert din, "no DIN stream"
inlet = pylsl.StreamInlet(din[0])
inlet.open_stream(5.0)
time.sleep(0.5)
inlet.pull_chunk() # drop anything before the triggers
sent = 0
hits = 0
for _ in range(5):
assert r("trigger 500") == "OK"
sent += 1
deadline = time.time() + 0.2 # well inside the mock's periodic DIN pulses
while time.time() < deadline:
values, _ = inlet.pull_chunk(timeout=0.1)
if any(v[0] & 0x10000 for v in values): # BNC-in is DIN bit 16
hits += 1
break
time.sleep(0.2)
print(f"BNC events seen for {hits}/{sent} triggers")
assert hits == sent

assert r("unlink") == "OK"
assert "linked=0" in r("status")
print("PASS")


if __name__ == "__main__":
main()
78 changes: 66 additions & 12 deletions src/cli/main.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
#include <egiamp/AmpServerConfig.h>
#include <egiamp/EGIAmpClient.h>
#include <egiamp/RemoteControl.h>

#include <atomic>
#include <csignal>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>

namespace {
Expand All @@ -22,6 +24,41 @@ void signalHandler(int signal) {
}
}

// Remote control for the CLI: drives the client directly.
class CliRemoteTarget : public egiamp::RemoteControlTarget {
public:
explicit CliRemoteTarget(egiamp::EGIAmpClient& client) : client_(client) {}
egiamp::EGIAmpClient& client() override { return client_; }
egiamp::AmpServerConfig config() override { return client_.config(); }
void setConfig(const egiamp::AmpServerConfig& config) override { client_.setConfig(config); }
std::string link() override {
if (!client_.connect()) {
return "Failed to connect to AmpServer at " + client_.config().serverAddress;
}
std::cout << "Connected to AmpServer.\n";
if (!client_.startStreaming()) {
client_.disconnect();
return "Failed to start streaming";
}
return "";
}
std::string unlink() override {
client_.stopStreaming();
client_.disconnect();
return "";
}
std::string setImpedance(bool on) override {
if (!on) {
client_.stopImpedanceMode();
return "";
}
return client_.startImpedanceMode() ? "" : "Failed to start impedance mode";
}

private:
egiamp::EGIAmpClient& client_;
};

void printUsage(const char* programName) {
std::cerr << "Usage: " << programName << " [options]\n"
<< "Options:\n"
Expand All @@ -34,6 +71,8 @@ void printUsage(const char* programName) {
<< " --fast-recovery Use native rate for lower latency (no FPGA anti-alias filter)\n"
<< " --impedance Enable impedance testing mode (default: disabled)\n"
<< " --native-format Transmit raw int32 ADC counts instead of float microvolts\n"
<< " --remote-port <p> Serve remote control commands on 127.0.0.1:<p> and keep\n"
<< " running until Ctrl+C, even when unlinked\n"
<< " --shutdown Shutdown the Amp Server (terminates all connections)\n"
<< " --help Show this help message\n";
}
Expand All @@ -42,6 +81,7 @@ int main(int argc, char* argv[]) {
egiamp::AmpServerConfig config;
std::string configFile;
bool shutdownMode = false;
int remotePort = 0;

// Parse command-line arguments
for (int i = 1; i < argc; i++) {
Expand Down Expand Up @@ -70,6 +110,12 @@ int main(int argc, char* argv[]) {
config.impedance = true;
} else if (arg == "--native-format") {
config.nativeFormat = true;
} else if (arg == "--remote-port" && i + 1 < argc) {
remotePort = std::stoi(argv[++i]);
if (remotePort < 1 || remotePort > 65535) {
std::cerr << "Invalid --remote-port: " << remotePort << std::endl;
return 1;
}
} else if (arg == "--shutdown") {
shutdownMode = true;
} else {
Expand Down Expand Up @@ -152,26 +198,34 @@ int main(int argc, char* argv[]) {
<< " Data Format: " << (config.nativeFormat ? "native (int32 counts)" : "microvolts (float32)") << "\n"
<< "Press Ctrl+C to stop.\n\n";

// Connect and stream
if (!client.connect()) {
std::cerr << "Failed to connect to AmpServer at "
<< config.serverAddress << std::endl;
return 1;
if (remotePort == 0) remotePort = config.remotePort;
CliRemoteTarget target(client);
std::unique_ptr<egiamp::RemoteControlServer> remote;
if (remotePort) {
try {
remote = std::make_unique<egiamp::RemoteControlServer>(
target, static_cast<uint16_t>(remotePort));
} catch (const std::exception& e) {
std::cerr << "Cannot serve remote control on port " << remotePort << ": "
<< e.what() << std::endl;
return 1;
}
std::cout << "Remote control on 127.0.0.1:" << remotePort << "\n";
}

std::cout << "Connected to AmpServer.\n";

if (!client.startStreaming()) {
std::cerr << "Failed to start streaming" << std::endl;
client.disconnect();
return 1;
// Connect and stream. With remote control, a failed link is not fatal:
// the remote side can fix the settings and link again.
if (const std::string err = target.link(); !err.empty()) {
std::cerr << err << std::endl;
if (!remote) return 1;
}

// Wait for shutdown signal
while (g_running && client.isStreaming()) {
while (g_running && (remote || client.isStreaming())) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

remote.reset();
client.stopStreaming();
client.disconnect();

Expand Down
1 change: 1 addition & 0 deletions src/core/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ add_library(egiamp_core STATIC
src/ImpedanceMeasurement.cpp
src/LSLStreamer.cpp
src/EGIAmpClient.cpp
src/RemoteControl.cpp
src/SensorLayout.cpp
"${GENERATED_DIR}/EmbeddedResources.cpp"
"${GENERATED_DIR}/egiamp/FilterDelays.h"
Expand Down
1 change: 1 addition & 0 deletions src/core/include/egiamp/AmpServerConfig.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ struct AmpServerConfig {
std::optional<double> systemDelayMs;
bool impedance = false;
bool nativeFormat = false; // When true, transmit raw int32 ADC counts instead of float microvolts
uint16_t remotePort = 0; // Remote control service on 127.0.0.1:<port>; 0 = off. Read at startup.

/// Derive LSL stream name from the server address.
/// .51 → "EGINetAmp_51", .52 → "EGINetAmp_52", localhost/127.* → "EGINetAmp_mock".
Expand Down
2 changes: 1 addition & 1 deletion src/core/include/egiamp/AmpServerConnection.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class AmpServerConnection {
socket_stream commandStream_;
socket_stream notificationStream_;
socket_stream dataStream_;
std::mutex commandMutex_; // commands come from several threads (UI, impedance scan)
std::mutex commandMutex_; // commands come from several threads (UI, impedance scan, remote control)
std::atomic<bool> connected_{false};
std::string serverAddress_;
uint16_t dataPort_{0};
Expand Down
63 changes: 63 additions & 0 deletions src/core/include/egiamp/RemoteControl.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#ifndef EGIAMP_REMOTECONTROL_H
#define EGIAMP_REMOTECONTROL_H

#include "AmpServerConfig.h"
#include "EGIAmpClient.h"

#include <asio.hpp>
#include <atomic>
#include <memory>
#include <mutex>
#include <string>
#include <thread>

namespace egiamp {

/// What the remote control service drives. The CLI and GUI each implement it;
/// methods are called on the service's thread. Methods returning a string
/// return an empty string on success, otherwise the error message.
class RemoteControlTarget {
public:
virtual ~RemoteControlTarget() = default;
virtual EGIAmpClient& client() = 0;
/// The configuration the next link would use.
virtual AmpServerConfig config() = 0;
virtual void setConfig(const AmpServerConfig& config) = 0;
/// Connect and start streaming; blocks until done.
virtual std::string link() = 0;
virtual std::string unlink() = 0;
virtual std::string setImpedance(bool on) = 0;
};

/// Executes one remote control command line and returns the reply line
/// ("OK[ ...]" or "ERROR <message>"). See README "Remote Control".
std::string handleRemoteCommand(RemoteControlTarget& target, const std::string& line);

/// Serves newline-delimited remote control commands on 127.0.0.1:<port>, one
/// client at a time, on its own thread. Throws std::system_error if the port
/// cannot be bound.
// ponytail: localhost only, no authentication; add a bind address (and auth)
// if control from another machine is ever needed.
class RemoteControlServer {
public:
RemoteControlServer(RemoteControlTarget& target, uint16_t port);
~RemoteControlServer();

RemoteControlServer(const RemoteControlServer&) = delete;
RemoteControlServer& operator=(const RemoteControlServer&) = delete;

private:
void serve();

RemoteControlTarget& target_;
asio::io_context io_;
asio::ip::tcp::acceptor acceptor_;
std::atomic<bool> stopping_{false};
std::mutex clientMutex_;
std::shared_ptr<asio::ip::tcp::socket> client_;
std::thread thread_;
};

} // namespace egiamp

#endif // EGIAMP_REMOTECONTROL_H
6 changes: 6 additions & 0 deletions src/core/src/AmpServerConfig.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ AmpServerConfig AmpServerConfig::loadFromFile(const std::string& filename) {
if (auto node = settings.child("physioaligndelayms")) {
config.physioAlignDelayMs = node.text().as_int(config.physioAlignDelayMs);
}
if (auto node = settings.child("remoteport")) {
config.remotePort = static_cast<uint16_t>(node.text().as_uint(config.remotePort));
}
if (auto node = settings.child("systemdelayms")) {
config.systemDelayMs = node.text().as_double();
}
Expand All @@ -93,6 +96,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);
if (remotePort) {
settings.append_child("remoteport").text().set(remotePort);
}
if (systemDelayMs) {
settings.append_child("systemdelayms").text().set(*systemDelayMs);
}
Expand Down
Loading
Loading