diff --git a/README.md b/README.md index dccfa59..ea7b91a 100644 --- a/README.md +++ b/README.md @@ -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 ` - Serve [remote control](#remote-control) commands on 127.0.0.1:``; 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 @@ -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 `. 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. @@ -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 ` (CLI) or `` in the `` 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 `. 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 ` | 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 ` / `save ` | 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. diff --git a/scripts/remote_control_test.py b/scripts/remote_control_test.py new file mode 100644 index 0000000..45bb650 --- /dev/null +++ b/scripts/remote_control_test.py @@ -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 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() diff --git a/src/cli/main.cpp b/src/cli/main.cpp index f64e141..8b0a4b6 100644 --- a/src/cli/main.cpp +++ b/src/cli/main.cpp @@ -1,10 +1,12 @@ #include #include +#include #include #include #include #include +#include #include namespace { @@ -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" @@ -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

Serve remote control commands on 127.0.0.1:

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"; } @@ -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++) { @@ -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 { @@ -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 remote; + if (remotePort) { + try { + remote = std::make_unique( + target, static_cast(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(); diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 4a71a75..af2125c 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -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" diff --git a/src/core/include/egiamp/AmpServerConfig.h b/src/core/include/egiamp/AmpServerConfig.h index 60aa403..efea87c 100644 --- a/src/core/include/egiamp/AmpServerConfig.h +++ b/src/core/include/egiamp/AmpServerConfig.h @@ -37,6 +37,7 @@ struct AmpServerConfig { std::optional 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:; 0 = off. Read at startup. /// Derive LSL stream name from the server address. /// .51 → "EGINetAmp_51", .52 → "EGINetAmp_52", localhost/127.* → "EGINetAmp_mock". diff --git a/src/core/include/egiamp/AmpServerConnection.h b/src/core/include/egiamp/AmpServerConnection.h index f215468..3a5264d 100644 --- a/src/core/include/egiamp/AmpServerConnection.h +++ b/src/core/include/egiamp/AmpServerConnection.h @@ -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 connected_{false}; std::string serverAddress_; uint16_t dataPort_{0}; diff --git a/src/core/include/egiamp/RemoteControl.h b/src/core/include/egiamp/RemoteControl.h new file mode 100644 index 0000000..c463559 --- /dev/null +++ b/src/core/include/egiamp/RemoteControl.h @@ -0,0 +1,63 @@ +#ifndef EGIAMP_REMOTECONTROL_H +#define EGIAMP_REMOTECONTROL_H + +#include "AmpServerConfig.h" +#include "EGIAmpClient.h" + +#include +#include +#include +#include +#include +#include + +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 "). See README "Remote Control". +std::string handleRemoteCommand(RemoteControlTarget& target, const std::string& line); + +/// Serves newline-delimited remote control commands on 127.0.0.1:, 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 stopping_{false}; + std::mutex clientMutex_; + std::shared_ptr client_; + std::thread thread_; +}; + +} // namespace egiamp + +#endif // EGIAMP_REMOTECONTROL_H diff --git a/src/core/src/AmpServerConfig.cpp b/src/core/src/AmpServerConfig.cpp index df6ca4a..56da171 100644 --- a/src/core/src/AmpServerConfig.cpp +++ b/src/core/src/AmpServerConfig.cpp @@ -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(node.text().as_uint(config.remotePort)); + } if (auto node = settings.child("systemdelayms")) { config.systemDelayMs = node.text().as_double(); } @@ -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); } diff --git a/src/core/src/RemoteControl.cpp b/src/core/src/RemoteControl.cpp new file mode 100644 index 0000000..3619668 --- /dev/null +++ b/src/core/src/RemoteControl.cpp @@ -0,0 +1,180 @@ +#include "egiamp/RemoteControl.h" + +#include +#include +#include + +namespace egiamp { + +namespace { + +const char* HELP = + "OK commands: status | set | load | save | link | unlink | impedance | " + "trigger [width_us] | shutdown_ampserver | help"; + +std::string result(const std::string& error) { + return error.empty() ? "OK" : "ERROR " + error; +} + +int parseInt(const std::string& s, int lo, int hi) { + size_t used = 0; + const int v = std::stoi(s, &used); + if (used != s.size() || v < lo || v > hi) throw std::invalid_argument(s); + return v; +} + +} // namespace + +std::string handleRemoteCommand(RemoteControlTarget& target, const std::string& line) { + std::istringstream in(line); + std::string cmd; + in >> cmd; + std::string rest; + std::getline(in >> std::ws, rest); + while (!rest.empty() && std::isspace(static_cast(rest.back()))) rest.pop_back(); + EGIAmpClient& client = target.client(); + const bool linked = client.isStreaming(); + + try { + if (cmd == "help") return HELP; + + if (cmd == "status") { + const AmpServerConfig c = target.config(); + std::ostringstream out; + out << "OK linked=" << linked << " impedance=" << client.isImpedanceModeActive() + << " address=" << c.serverAddress << " command_port=" << c.commandPort + << " notification_port=" << c.notificationPort << " data_port=" << c.dataPort + << " sample_rate=" << c.sampleRate << " fast_recovery=" << c.fastRecovery; + if (linked) { + const auto& d = client.amplifierDetails(); + std::string model = amplifierTypeName(d.amplifierType); + std::replace(model.begin(), model.end(), ' ', '_'); + out << " amplifier=" << model << " serial=" << d.serialNumber + << " net=" << netCodeName(d.netCode); + } + return out.str(); + } + + if (cmd == "set" || cmd == "load") { + if (linked) return "ERROR unlink first"; + AmpServerConfig c = target.config(); + if (cmd == "load") { + if (rest.empty()) return "ERROR usage: load "; + c = AmpServerConfig::loadFromFile(rest); + } else { + std::istringstream args(rest); + std::string key, value; + if (!(args >> key >> value)) return "ERROR usage: set "; + if (key == "address") c.serverAddress = value; + else if (key == "command_port") c.commandPort = static_cast(parseInt(value, 1, 65535)); + else if (key == "notification_port") c.notificationPort = static_cast(parseInt(value, 1, 65535)); + else if (key == "data_port") c.dataPort = static_cast(parseInt(value, 1, 65535)); + else if (key == "sample_rate") { + c.sampleRate = parseInt(value, 1, 1000000); + c.forceSampleRate = true; // an explicit request, as with the CLI's --sample-rate + } else if (key == "fast_recovery") { + c.fastRecovery = parseInt(value, 0, 1) == 1; + c.forceSampleRate = true; + } else return "ERROR unknown setting: " + key; + } + target.setConfig(c); + return "OK"; + } + + if (cmd == "save") { + if (rest.empty()) return "ERROR usage: save "; + target.config().saveToFile(rest); + return "OK"; + } + + if (cmd == "link") return linked ? "ERROR already linked" : result(target.link()); + if (cmd == "unlink") return linked ? result(target.unlink()) : "ERROR not linked"; + + if (cmd == "impedance") { + if (rest != "on" && rest != "off") return "ERROR usage: impedance "; + if (!linked) return "ERROR not linked"; + return result(target.setImpedance(rest == "on")); + } + + if (cmd == "trigger") { + const int width = rest.empty() ? EGIAmpClient::BNC_OUT_DEFAULT_PULSE_US + : parseInt(rest, EGIAmpClient::BNC_OUT_MIN_PULSE_US, + EGIAmpClient::BNC_OUT_MAX_PULSE_US); + if (!linked) return "ERROR not linked"; + if (client.amplifierDetails().amplifierType != AmplifierType::NA500) + return "ERROR the BNC output trigger needs a Net Amps 500"; + return client.triggerBncOut(width) ? "OK" : "ERROR trigger command failed"; + } + + if (cmd == "shutdown_ampserver") { + if (linked) return "ERROR unlink first"; + client.setConfig(target.config()); + if (!client.connect()) return "ERROR could not connect to AmpServer"; + const bool ok = client.shutdownAmpServer(); + client.disconnect(); + return ok ? "OK" : "ERROR shutdown command failed"; + } + } catch (const std::invalid_argument&) { + return "ERROR invalid value: " + rest; + } catch (const std::out_of_range&) { + return "ERROR invalid value: " + rest; + } catch (const std::exception& e) { + return std::string("ERROR ") + e.what(); + } + return "ERROR unknown command: " + cmd + " (try help)"; +} + +RemoteControlServer::RemoteControlServer(RemoteControlTarget& target, uint16_t port) + : target_(target) + , acceptor_(io_, asio::ip::tcp::endpoint(asio::ip::address_v4::loopback(), port)) + , thread_([this] { serve(); }) {} + +RemoteControlServer::~RemoteControlServer() { + stopping_ = true; + asio::error_code ec; + { + // Closing the acceptor does not wake a blocked accept() on macOS; a connection does. + asio::ip::tcp::socket wake(io_); + wake.connect(acceptor_.local_endpoint(ec), ec); + } + { + std::lock_guard lock(clientMutex_); + if (client_) client_->shutdown(asio::ip::tcp::socket::shutdown_both, ec); // unblocks read + } + thread_.join(); + acceptor_.close(ec); +} + +void RemoteControlServer::serve() { + while (!stopping_) { + auto socket = std::make_shared(io_); + asio::error_code ec; + acceptor_.accept(*socket, ec); + if (ec) { + if (stopping_) return; + continue; + } + { + std::lock_guard lock(clientMutex_); + if (stopping_) return; + client_ = socket; + } + asio::streambuf buffer; + while (!stopping_) { + asio::read_until(*socket, buffer, '\n', ec); + if (ec) break; + std::istream stream(&buffer); + std::string line; + std::getline(stream, line); + if (line.find_first_not_of(" \t\r") == std::string::npos) continue; + const std::string reply = handleRemoteCommand(target_, line) + "\n"; + asio::write(*socket, asio::buffer(reply), ec); + if (ec) break; + } + std::lock_guard lock(clientMutex_); + client_.reset(); + } +} + +} // namespace egiamp diff --git a/src/gui/EGIAmpWindow.cpp b/src/gui/EGIAmpWindow.cpp index fa24436..318cefe 100644 --- a/src/gui/EGIAmpWindow.cpp +++ b/src/gui/EGIAmpWindow.cpp @@ -9,6 +9,9 @@ #include #include +#include +#include + namespace { /// Derive amplifier ID from the server address: .52 → 1, everything else → 0. int amplifierIdFromAddress(const std::string& address) { @@ -89,9 +92,23 @@ EGIAmpWindow::EGIAmpWindow(QWidget* parent, const std::string& configFile) client_->setSensorCallback([this](egiamp::NetCode code) { emit sensorLayoutUpdated(QString::fromUtf8(egiamp::netCodeName(code))); }); + + if (baseConfig_.remotePort) { + try { + remote_ = std::make_unique(*this, baseConfig_.remotePort); + ui->statusBox->appendPlainText( + QString("Remote control on 127.0.0.1:%1").arg(baseConfig_.remotePort)); + } catch (const std::exception& e) { + ui->statusBox->appendPlainText( + QString("Cannot serve remote control on port %1: %2") + .arg(baseConfig_.remotePort).arg(e.what())); + } + } } EGIAmpWindow::~EGIAmpWindow() { + closing_ = true; // lets a remote command waiting on the UI thread give up + remote_.reset(); joinLinkThread(); if (client_->isStreaming()) { client_->stopStreaming(); @@ -120,19 +137,23 @@ void EGIAmpWindow::saveConfigDialog() { void EGIAmpWindow::loadConfig(const std::string& filename) { try { - auto config = egiamp::AmpServerConfig::loadFromFile(filename); - ui->serverAddress->setText(QString::fromStdString(config.serverAddress)); - ui->commandPort->setValue(config.commandPort); - ui->notificationPort->setValue(config.notificationPort); - ui->dataPort->setValue(config.dataPort); - ui->sampleRateComboBox->setCurrentIndex( - findSampleRateIndex(config.sampleRate, config.fastRecovery)); + applyConfig(egiamp::AmpServerConfig::loadFromFile(filename)); } catch (const egiamp::ConfigError& e) { QMessageBox::information(this, "Error", QString("Cannot read config file: %1").arg(e.what()), QMessageBox::Ok); } } +void EGIAmpWindow::applyConfig(const egiamp::AmpServerConfig& config) { + baseConfig_ = config; + ui->serverAddress->setText(QString::fromStdString(config.serverAddress)); + ui->commandPort->setValue(config.commandPort); + ui->notificationPort->setValue(config.notificationPort); + ui->dataPort->setValue(config.dataPort); + ui->sampleRateComboBox->setCurrentIndex( + findSampleRateIndex(config.sampleRate, config.fastRecovery)); +} + void EGIAmpWindow::saveConfig(const std::string& filename) { try { auto config = getConfigFromUI(); @@ -144,7 +165,10 @@ void EGIAmpWindow::saveConfig(const std::string& filename) { } egiamp::AmpServerConfig EGIAmpWindow::getConfigFromUI() const { - egiamp::AmpServerConfig config; + egiamp::AmpServerConfig config = baseConfig_; + // The GUI attaches to a running amp as-is and measures impedance on demand. + config.forceSampleRate = false; + config.impedance = false; config.serverAddress = ui->serverAddress->text().toStdString(); config.commandPort = static_cast(ui->commandPort->value()); config.notificationPort = static_cast(ui->notificationPort->value()); @@ -194,43 +218,44 @@ void EGIAmpWindow::linkAmpserver() { // unresponsive. All UI updates flow back through queued signals. joinLinkThread(); linkThread_ = std::make_unique([this]() { - emit appendStatusMessage("Connecting to AmpServer..."); - if (!client_->connect()) { - emit linkFinished(false, - "Could not connect to AmpServer. Please check network settings " - "and ensure AmpServer is running."); - return; - } - - // Query amplifier state to detect if it's already running - emit appendStatusMessage("Querying amplifier state..."); - client_->queryAmpState(); - if (client_->ampWasRunning()) { - int detectedRate = client_->detectedSampleRate(); - if (detectedRate > 0) { - emit appendStatusMessage( - QString("Amplifier already running at %1 Hz").arg(detectedRate)); - } else { - emit appendStatusMessage( - "Amplifier already running (sample rate detection failed, " - "using configured rate)"); - } - emit ampDetectedRunning(detectedRate); - emit sensorLayoutUpdated( - QString::fromUtf8(egiamp::netCodeName(client_->detectedNetCode()))); - } - - if (!client_->startStreaming()) { - client_->disconnect(); - emit linkFinished(false, "Failed to start streaming"); - return; - } - - emit linkFinished(true, QString()); + const QString err = runLink(); + emit linkFinished(err.isEmpty(), err); }); } } +QString EGIAmpWindow::runLink() { + emit appendStatusMessage("Connecting to AmpServer..."); + if (!client_->connect()) { + return "Could not connect to AmpServer. Please check network settings " + "and ensure AmpServer is running."; + } + + // Query amplifier state to detect if it's already running + emit appendStatusMessage("Querying amplifier state..."); + client_->queryAmpState(); + if (client_->ampWasRunning()) { + int detectedRate = client_->detectedSampleRate(); + if (detectedRate > 0) { + emit appendStatusMessage( + QString("Amplifier already running at %1 Hz").arg(detectedRate)); + } else { + emit appendStatusMessage( + "Amplifier already running (sample rate detection failed, " + "using configured rate)"); + } + emit ampDetectedRunning(detectedRate); + emit sensorLayoutUpdated( + QString::fromUtf8(egiamp::netCodeName(client_->detectedNetCode()))); + } + + if (!client_->startStreaming()) { + client_->disconnect(); + return "Failed to start streaming"; + } + return QString(); +} + void EGIAmpWindow::onLinkFinished(bool ok, QString errorMessage) { joinLinkThread(); if (ok) { @@ -416,3 +441,57 @@ void EGIAmpWindow::triggerBncOut() { emit appendStatusMessage("BNC trigger sent."); } } + +// Runs f on the UI thread and returns its result; called from the remote +// control thread. Gives up (throws) once the window starts closing, so the +// destructor can join the remote control thread without deadlocking. +template +auto EGIAmpWindow::onUiThread(F f) { + auto done = std::make_shared>(); + auto result = done->get_future(); + // `this` as context: Qt drops the call if the window is destroyed first. + QMetaObject::invokeMethod(this, [done, f]() mutable { done->set_value(f()); }, + Qt::QueuedConnection); + while (result.wait_for(std::chrono::milliseconds(50)) != std::future_status::ready) { + if (closing_) throw std::runtime_error("the application is closing"); + } + return result.get(); +} + +egiamp::AmpServerConfig EGIAmpWindow::config() { + return onUiThread([this] { return getConfigFromUI(); }); +} + +void EGIAmpWindow::setConfig(const egiamp::AmpServerConfig& config) { + onUiThread([this, &config] { applyConfig(config); return true; }); +} + +std::string EGIAmpWindow::link() { + const bool started = onUiThread([this] { + if (!ui->linkButton->isEnabled() || client_->isStreaming()) return false; + ui->linkButton->setEnabled(false); + client_->setConfig(getConfigFromUI()); + return true; + }); + if (!started) return "busy (already linking)"; + const QString err = runLink(); + emit linkFinished(err.isEmpty(), err); // updates the window, like a button-started link + return err.toStdString(); +} + +std::string EGIAmpWindow::unlink() { + return onUiThread([this]() -> std::string { + if (!ui->linkButton->isEnabled()) return "busy (linking)"; + if (!client_->isStreaming()) return "not linked"; + linkAmpserver(); + return ""; + }); +} + +std::string EGIAmpWindow::setImpedance(bool on) { + return onUiThread([this, on]() -> std::string { + if (!ui->impedanceCheckBox->isEnabled()) return "not linked"; + ui->impedanceCheckBox->setChecked(on); // runs toggleImpedanceMode (unchecks on failure) + return client_->isImpedanceModeActive() == on ? "" : "impedance mode change failed"; + }); +} diff --git a/src/gui/EGIAmpWindow.h b/src/gui/EGIAmpWindow.h index a7efe3c..1309197 100644 --- a/src/gui/EGIAmpWindow.h +++ b/src/gui/EGIAmpWindow.h @@ -2,9 +2,11 @@ #define EGIAMPWINDOW_H #include +#include #include #include +#include #include #include #include @@ -13,7 +15,7 @@ namespace Ui { class EGIAmpWindow; } -class EGIAmpWindow : public QMainWindow { +class EGIAmpWindow : public QMainWindow, public egiamp::RemoteControlTarget { Q_OBJECT public: @@ -21,6 +23,15 @@ class EGIAmpWindow : public QMainWindow { EGIAmpWindow(const EGIAmpWindow&) = delete; ~EGIAmpWindow() override; + // Remote control (called on the remote control thread; they run their UI + // work on the UI thread so the window always shows the current state). + egiamp::EGIAmpClient& client() override { return *client_; } + egiamp::AmpServerConfig config() override; + void setConfig(const egiamp::AmpServerConfig& config) override; + std::string link() override; + std::string unlink() override; + std::string setImpedance(bool on) override; + private slots: void loadConfigDialog(); void saveConfigDialog(); @@ -52,6 +63,9 @@ private slots: private: void loadConfig(const std::string& filename); + void applyConfig(const egiamp::AmpServerConfig& config); + QString runLink(); // connect/query/start; returns the error, empty on success + template auto onUiThread(F f); void saveConfig(const std::string& filename); void updateUIFromConfig(); egiamp::AmpServerConfig getConfigFromUI() const; @@ -67,6 +81,10 @@ private slots: // start legitimately takes 15+ s (power-on wait), and a hung AmpServer // must never freeze the UI. Progress arrives via queued signals. std::unique_ptr linkThread_; + // Settings the window has no field for, kept from the loaded config. + egiamp::AmpServerConfig baseConfig_; + std::atomic closing_{false}; + std::unique_ptr remote_; }; #endif // EGIAMPWINDOW_H