diff --git a/backend/crates/station/examples/ws_test.rs b/backend/crates/station/examples/ws_test.rs new file mode 100644 index 000000000..c2a798bd4 --- /dev/null +++ b/backend/crates/station/examples/ws_test.rs @@ -0,0 +1,382 @@ +//! Throwaway test runner: serves station's HTTP catalogs and WebSocket from an +//! ADJ and publishes fake updates on every frontend topic. +//! +//! ```sh +//! cargo run -p station --example ws_test -- [--adj-dir PATH] [--bind 127.0.0.1:4000] [--heartbeat-ms N] [--interval-ms N] +//! ``` +//! +//! Without `--adj-dir` it loads the test ADJ in `crates/core/src/adj/test/adj`. +//! Telemetry, connections and protections use that ADJ's ids, so a frontend +//! that loads the catalogs can show them. +//! +//! `--heartbeat-ms` defaults to a day so manual clients that send no heartbeats +//! stay connected; pass `100` to test the production timeout. Orders and logger +//! commands have no destination here: they are only traced. + +use std::{ + collections::HashMap, + error::Error, + net::SocketAddr, + path::PathBuf, + sync::Arc, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; + +use software_core::{ + adj::{Adj, load_from_dir}, + model::{ + AdjId, Measurement, MeasurementKind, MessageLevel, NumericKind, PacketType, ProtectionKind, + Value, + }, +}; +use station::{ + payload::{ + BackendMessage, Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate, + MeasurementUpdate, MessageTimestamp, MessageUpdate, ProtectionUpdate, + }, + websocket::{ + self, Commands, + broker::{self, Broker, BrokerClient}, + }, +}; +use tokio::{net::TcpListener, sync::mpsc, time::interval}; +use tracing_subscriber::EnvFilter; + +const TEST_ADJ: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../core/src/adj/test/adj"); +const EVENT_PERIOD: Duration = Duration::from_secs(3); +/// How long the flapping board stays connected, then disconnected. +const FLAP_SECONDS: u64 = 10; + +#[derive(Debug)] +struct Options { + adj_dir: PathBuf, + bind: SocketAddr, + heartbeat: Duration, + interval: Duration, +} + +impl Options { + fn parse() -> Result> { + let mut options = Self { + adj_dir: PathBuf::from(TEST_ADJ), + bind: SocketAddr::from(([127, 0, 0, 1], 4000)), + heartbeat: Duration::from_secs(24 * 60 * 60), + interval: Duration::from_millis(500), + }; + let mut args = std::env::args().skip(1); + while let Some(flag) = args.next() { + let value = args.next().ok_or_else(|| format!("{flag} needs a value"))?; + match flag.as_str() { + "--adj-dir" => options.adj_dir = PathBuf::from(value), + "--bind" => options.bind = value.parse()?, + "--heartbeat-ms" => options.heartbeat = Duration::from_millis(value.parse()?), + "--interval-ms" => options.interval = Duration::from_millis(value.parse()?), + _ => return Err(format!("unknown argument {flag}").into()), + } + } + if options.interval.is_zero() { + return Err("--interval-ms must be greater than 0".into()); + } + Ok(options) + } +} + +/// What the fake publisher needs from the ADJ, extracted once. +#[derive(Debug)] +struct FakePod { + /// Board names, sorted. The first one flaps. + boards: Vec, + /// Data packets with the measurements each one carries. + packets: Vec<(AdjId, Vec)>, + /// One trigger per protection packet, sorted by id. + triggers: Vec, + orders: usize, +} + +/// A protection packet and a reading that violates it. +#[derive(Debug)] +struct Trigger { + id: AdjId, + value: Value, +} + +impl FakePod { + fn new(adj: &Adj) -> Self { + let mut pod = Self { + boards: Vec::new(), + packets: Vec::new(), + triggers: Vec::new(), + orders: 0, + }; + for board in adj.pod_data.boards.values() { + pod.boards.push(board.name.clone()); + for packet in board.packets.values() { + match &packet.packet_type { + PacketType::Data(measurements) => { + pod.packets.push((packet.id, measurements.clone())); + } + PacketType::Order(_) => pod.orders += 1, + PacketType::Protection(measurement) => { + let position = usize::from(packet.id.protection_position()); + let Some(protection) = position + .checked_sub(1) + .and_then(|index| measurement.protections.get(index)) + else { + continue; + }; + pod.triggers.push(Trigger { + id: packet.id, + value: violation(measurement, protection.kind), + }); + } + PacketType::Message(_) => {} + } + } + } + pod.boards.sort(); + pod.packets.sort_by_key(|(id, _)| id.0); + pod.triggers.sort_by_key(|trigger| trigger.id.0); + pod + } +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); + tracing_subscriber::fmt().with_env_filter(filter).init(); + let options = Options::parse()?; + + let adj = + Arc::new(load_from_dir(&options.adj_dir).map_err(|error| { + format!("loading the ADJ in {}: {error}", options.adj_dir.display()) + })?); + let pod = FakePod::new(&adj); + tracing::info!( + adj = %options.adj_dir.display(), + boards = pod.boards.len(), + data_packets = pod.packets.len(), + orders = pod.orders, + protections = pod.triggers.len(), + "ADJ loaded" + ); + + let listener = TcpListener::bind(options.bind).await?; + let address = listener.local_addr()?; + let (sockets, connections) = mpsc::channel(16); + let mut http = + tokio::spawn(async move { station::http::serve(listener, &adj, Some(sockets)).await }); + + let (broker, client) = Broker::new(); + let broker = tokio::spawn(broker.run()); + let mut frontends = tokio::spawn(websocket::run( + connections, + client.subscriber(), + Commands::default(), + options.heartbeat, + )); + // The publisher owns the only BrokerClient: stopping it stops the broker. + let publisher = tokio::spawn(publish_fake_updates(client, pod, options.interval)); + + println!("HTTP http://{address}/backend/adj/DataPackets"); + println!(" http://{address}/backend/adj/OrderPackets"); + println!(" http://{address}/backend/adj/ProtectionPackets"); + println!("WS ws://{address}/backend/ws"); + println!(r#" {{"topic":"podData/update","payload":{{"subscribe":true}}}}"#); + println!("Ctrl+C to stop"); + + tokio::select! { + signal = tokio::signal::ctrl_c() => signal?, + // Only with a short heartbeat: run has already traced FrontendDisconnected. + result = &mut frontends => return Ok(result??), + result = &mut http => { + result??; + return Err("HTTP server stopped".into()); + } + } + + tracing::info!("stopping"); + publisher.abort(); + let _ = publisher.await; + broker.await?; + frontends.await??; + http.abort(); + Ok(()) +} + +async fn publish_fake_updates( + client: BrokerClient, + pod: FakePod, + period: Duration, +) -> Result<(), broker::Error> { + let start = Instant::now(); + let cycle_time = u64::try_from(period.as_nanos()).unwrap_or(u64::MAX); + let mut data_ticker = interval(period); + let mut event_ticker = interval(EVENT_PERIOD); + let mut count = 0; + let mut event = 0_usize; + let mut flapping_connected = None; + + loop { + tokio::select! { + _ = data_ticker.tick() => { + count += 1; + let elapsed = start.elapsed(); + let connected = (elapsed.as_secs() / FLAP_SECONDS).is_multiple_of(2); + // Connections are state: publish them only when they change. + if flapping_connected != Some(connected) { + flapping_connected = Some(connected); + client.publish_connections(connections(&pod.boards, connected)).await?; + } + client + .publish_data(data(&pod.packets, elapsed.as_secs_f64(), count, cycle_time)) + .await?; + } + _ = event_ticker.tick() => { + let round = event / 3; + let trigger = pod.triggers.get(round % pod.triggers.len().max(1)); + let board = pod.boards.get(round % pod.boards.len().max(1)).cloned(); + match (event % 3, trigger) { + (0, _) => client.publish_message(MessageUpdate { + kind: MessageLevel::Info, + payload: "Text message from ws_test".into(), + board: board.unwrap_or_default(), + origin: "ws_test.rs".into(), + name: "Fake info".into(), + timestamp: now(), + }).await?, + // The frontend completes it from the protections catalog. + (1, Some(trigger)) => client.publish_protection(ProtectionUpdate { + id: trigger.id, + value: trigger.value.clone(), + timestamp: now(), + }).await?, + _ => client.publish_backend_message(BackendMessage::new( + MessageLevel::Warning, + board, + "Backend message from ws_test", + now(), + )).await?, + } + event += 1; + } + } + } +} + +/// Every board connected except the first, which follows `flapping_connected`. +fn connections(boards: &[String], flapping_connected: bool) -> ConnectionUpdate { + let connections = boards + .iter() + .enumerate() + .map(|(index, name)| { + let connection = Connection { + name: name.clone(), + is_connected: index != 0 || flapping_connected, + }; + (name.clone(), connection) + }) + .collect(); + ConnectionUpdate(connections) +} + +fn data( + packets: &[(AdjId, Vec)], + elapsed: f64, + count: u64, + cycle_time: u64, +) -> DataUpdate { + let packets = packets + .iter() + .map(|(id, measurements)| { + let measurement_updates = measurements + .iter() + .map(|measurement| (measurement.id, reading(measurement, elapsed))) + .collect(); + let packet = DataPacketUpdate { + id: *id, + count, + cycle_time, + measurement_updates, + }; + (*id, packet) + }) + .collect::>(); + DataUpdate(packets) +} + +/// A slow wave between 10 and 90, offset by the measurement id so charts +/// don't move in lockstep. Booleans follow its sign; enums step through their +/// options. +fn reading(measurement: &Measurement, elapsed: f64) -> MeasurementUpdate { + let id = measurement.id.0; + let wave = (elapsed / 2.0 + f64::from(id)).sin(); + match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + let last = 50.0 + 40.0 * wave; + let last = match wire_type { + NumericKind::F32 | NumericKind::F64 => last, + _ => last.round(), + }; + MeasurementUpdate::Numeric { + last, + average: 50.0, + } + } + MeasurementKind::Boolean => MeasurementUpdate::Boolean(wave > 0.0), + MeasurementKind::Enum { options } => { + let step = (elapsed / 3.0) as usize + usize::from(id); + let option = options.get(step % options.len().max(1)); + MeasurementUpdate::Enum(option.cloned().unwrap_or_default()) + } + } +} + +/// A reading that breaks `kind`, typed like `measurement`. +fn violation(measurement: &Measurement, kind: ProtectionKind) -> Value { + let margin = |reference: f64| reference.abs().max(1.0) * 0.1; + let reading = match kind { + ProtectionKind::Above { limit } => limit + margin(limit), + ProtectionKind::Below { limit } => limit - margin(limit), + ProtectionKind::Range { min, max } => max + margin(max - min), + ProtectionKind::Equal { target } => target, + ProtectionKind::NotEqual { target } => target + 1.0, + }; + match &measurement.kind { + MeasurementKind::Numeric { .. } => Value::Number(reading), + MeasurementKind::Boolean => Value::Bool(reading != 0.0), + MeasurementKind::Enum { options } => { + Value::Enum(options.get(reading as usize).cloned().unwrap_or_default()) + } + } +} + +/// Current UTC time from the system clock. +fn now() -> MessageTimestamp { + let seconds = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()); + let (year, month, day) = civil_from_days(seconds / 86_400); + let time = seconds % 86_400; + MessageTimestamp { + second: (time % 60) as u8, + minute: (time / 60 % 60) as u8, + hour: (time / 3600) as u8, + day, + month, + year, + } +} + +/// Days since 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's algorithm). +fn civil_from_days(days: u64) -> (u16, u8, u8) { + let z = days + 719_468; + let era = z / 146_097; + let doe = z % 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + u64::from(month <= 2); + (year as u16, month as u8, day as u8) +} diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index 4bd72cc06..45ae049fd 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -4,7 +4,7 @@ //! Payloads the backend sends implement `TopicPayload`, which names their topic //! and builds the complete message. //! Serde adapters define the frontend JSON representation for shared domain types. -//! See `websocket/payload/README.md` for the wire shapes and examples. +//! See `payload/README.md` for the wire shapes and examples. use serde::Serialize; @@ -19,9 +19,9 @@ mod serialize; pub use backend::BackendMessage; pub use connection::{Connection, ConnectionUpdate}; pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; -pub use message::{MessagePayload, MessageTimestamp, MessageUpdate, protection_level}; +pub use message::{MessageTimestamp, MessageUpdate}; pub use order::{OrderField, OrderSend}; -pub use protection::{ProtectionPayload, ProtectionUpdate}; +pub use protection::ProtectionUpdate; /// Payload of `logger/enable`: the requested recording state. pub type LoggerEnable = bool; @@ -72,9 +72,7 @@ mod tests { use std::collections::HashMap; use serde_json::json; - use software_core::model::{ - AdjId, MessageLevel, ProtectionPacket, Severity, ShortTimestamp, Value, - }; + use software_core::model::{AdjId, MessageLevel, ProtectionPacket, ShortTimestamp, Value}; use super::*; @@ -174,11 +172,11 @@ mod tests { #[test] fn message_update_matches_its_example() -> Result<(), serde_json::Error> { let message = MessageUpdate { - kind: MessageLevel::Info, - payload: MessagePayload::Text("Order Sent".into()), - board: "LCU".into(), - origin: String::new(), - name: "1001".into(), + kind: MessageLevel::Warning, + payload: "Brake pressure below the expected range".into(), + board: "VCU".into(), + origin: "Core/Src/main.c".into(), + name: "warning".into(), timestamp: MessageTimestamp { second: 5, minute: 30, @@ -232,45 +230,6 @@ mod tests { Ok(()) } - #[test] - fn message_protection_details_have_their_own_kind_and_data() -> Result<(), serde_json::Error> { - let details = |payload| MessageUpdate { - kind: MessageLevel::Fault, - payload: MessagePayload::Protection(payload), - board: "HVBMS".into(), - origin: String::new(), - name: "cell_temperature".into(), - timestamp: MessageTimestamp { - second: 6, - minute: 30, - hour: 12, - day: 24, - month: 11, - year: 2026, - }, - }; - - let out_of_bounds = message(&details(ProtectionPayload::OutOfBounds { - bounds: [json!(10), json!(90)], - value: json!(95.5), - }))?; - // The outer kind is the severity; the inner kind is the condition. - assert_eq!(out_of_bounds["payload"]["kind"], "fault"); - assert_eq!( - out_of_bounds["payload"]["payload"], - json!({"kind": "OUT_OF_BOUNDS", "data": {"bounds": [10, 90], "value": 95.5}}) - ); - - let error_handler = message(&details(ProtectionPayload::ErrorHandler( - "stack overflow".into(), - )))?; - assert_eq!( - error_handler["payload"]["payload"], - json!({"kind": "ERROR_HANDLER", "data": "stack overflow"}) - ); - Ok(()) - } - #[test] fn protection_values_keep_their_json_type() -> Result<(), serde_json::Error> { for (value, expected) in [ @@ -316,7 +275,7 @@ mod tests { ] { let update = MessageUpdate { kind: level, - payload: MessagePayload::Text("text".into()), + payload: "text".into(), board: "LCU".into(), origin: String::new(), name: "name".into(), @@ -334,17 +293,11 @@ mod tests { Ok(()) } - #[test] - fn protections_are_shown_with_the_level_of_their_severity() { - assert_eq!(protection_level(Severity::Fault), MessageLevel::Fault); - assert_eq!(protection_level(Severity::Warning), MessageLevel::Warning); - } - #[test] fn board_messages_carry_where_the_board_produced_them() -> Result<(), serde_json::Error> { let update = MessageUpdate { kind: MessageLevel::Warning, - payload: MessagePayload::Text("something went wrong".into()), + payload: "something went wrong".into(), board: "VCU".into(), origin: "main.c".into(), name: "warning".into(), diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index ade0d4558..ed4d7c479 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -19,8 +19,8 @@ such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model` | [`data.rs`](data.rs) | `DataUpdate`, `DataPacketUpdate` and measurement values. | | [`connection.rs`](connection.rs) | `ConnectionUpdate` and `Connection`. | | [`order.rs`](order.rs) | `OrderSend` and `OrderField`. | -| [`message.rs`](message.rs) | `MessageUpdate`, its content and calendar timestamp, and `protection_level`. | -| [`protection.rs`](protection.rs) | `ProtectionUpdate`, built from a `ProtectionPacket`, and legacy `ProtectionPayload`. | +| [`message.rs`](message.rs) | `MessageUpdate`, a board's message, and its calendar timestamp. | +| [`protection.rs`](protection.rs) | `ProtectionUpdate`, built from a `ProtectionPacket`. | | [`backend.rs`](backend.rs) | `BackendMessage`, a message the backend itself produces. | | [`serialize.rs`](serialize.rs) | Internal Serde adapters for `AdjId`, `Value` and `MessageLevel`. | @@ -179,7 +179,7 @@ Boolean and enum parameters use `"bool"` and `"enum"`, respectively. "topic": "message/update", "payload": { "kind": string, // "info", "warning", "fault" or "panic". - "payload": string, // Alternatively, the detailed object shown below. + "payload": string, "board": string, "origin": string, "name": string, @@ -195,46 +195,15 @@ Boolean and enum parameters use `"bool"` and `"enum"`, respectively. } ``` -The outer `kind` is a `software_core::model::MessageLevel`, written with its -ADJ name (`MessageLevel::name`). A protection shown as a message takes the level -of its severity, given by `protection_level`. +Only messages a board sent travel on this topic. Protections travel only on +`protection/update`, and messages the backend produces itself on +`backend/message`. + +`kind` is a `software_core::model::MessageLevel`, written with its ADJ name +(`MessageLevel::name`). `payload` is the message's text, as the board sent it. `origin` repeats the `origin` field of the board's message packet: where on the board the message was produced, such as a source file, at most 47 characters. -It is empty for messages the backend produces itself, such as order notices -and protections shown as messages. - -`MessagePayload::Text` is a JSON string. `MessagePayload::Protection` is an -object with its own `kind` and `data`. The outer `kind` always describes -severity; the inner `kind` describes the condition: - -```jsonc -{ - "kind": "UPPER_BOUND", - "data": { - "bound": number, - "value": number - } -} -``` - -The detailed forms are: - -| Inner `kind` | `data` template | -| --- | --- | -| `LOWER_BOUND` | `{"bound": number, "value": number}` | -| `UPPER_BOUND` | `{"bound": number, "value": number}` | -| `OUT_OF_BOUNDS` | `{"bounds": [number, number], "value": number}` | -| `EQUALS` | `{"value": number}` | -| `NOT_EQUALS` | `{"want": number, "value": number}` | -| `TIME_ACCUMULATION` | `{"value": number, "bound": number, "timelimit": number}` | -| `ERROR_HANDLER` | `string` | -| `WARNING` | `string` | - -Measured values and thresholds can also be booleans when appropriate for -the condition. `bounds` contains exactly two elements, lower then upper; -`timelimit` is expressed in seconds. The application validates the detailed -values against the ADJ. ### Protection Events (`ProtectionUpdate`) @@ -256,8 +225,9 @@ values against the ADJ. } ``` -The payload contains only the compound protection ID, the value that triggered -it and when it triggered, in the same timestamp format as `message/update`. +Protections travel only on this topic, never on `message/update`. The payload +contains only the compound protection ID, the value that triggered it and when +it triggered, in the same timestamp format as `message/update`. The ADJ catalog supplies the protection's name, condition and severity. `ProtectionUpdate::new(packet, timestamp)` takes the id and value from a domain `ProtectionPacket`; the publisher builds `timestamp` from the packet's time of diff --git a/backend/crates/station/src/payload/example/message.json b/backend/crates/station/src/payload/example/message.json index 294a4d9d4..270a98405 100644 --- a/backend/crates/station/src/payload/example/message.json +++ b/backend/crates/station/src/payload/example/message.json @@ -1,11 +1,11 @@ { "topic": "message/update", "payload": { - "kind": "info", - "payload": "Order Sent", - "board": "LCU", - "origin": "", - "name": "1001", + "kind": "warning", + "payload": "Brake pressure below the expected range", + "board": "VCU", + "origin": "Core/Src/main.c", + "name": "warning", "timestamp": { "second": 5, "minute": 30, diff --git a/backend/crates/station/src/payload/message.rs b/backend/crates/station/src/payload/message.rs index 425984c63..a9c4a324f 100644 --- a/backend/crates/station/src/payload/message.rs +++ b/backend/crates/station/src/payload/message.rs @@ -1,23 +1,26 @@ -use super::{ProtectionPayload, TopicPayload, serialize::serialize_message_level}; +use super::{TopicPayload, serialize::serialize_message_level}; use serde::Serialize; -use software_core::model::{MessageLevel, Severity}; +use software_core::model::MessageLevel; -/// Payload of `message/update`, preserving the legacy event envelope. +/// Payload of `message/update`: a message a board sent. +/// +/// Only board messages travel on this topic. Protections have their own +/// topic, `protection/update`, and messages the backend produces itself go on +/// `backend/message`. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct MessageUpdate { - /// Event severity, in the legacy JSON field `kind`, written with the ADJ's + /// Severity, in the legacy JSON field `kind`, written with the ADJ's /// name for the level: `"fault"`, `"warning"`, `"info"` or `"panic"`. #[serde(serialize_with = "serialize_message_level")] pub kind: MessageLevel, - /// Text or protection details. - pub payload: MessagePayload, - /// Name of the board that produced the event. + /// The message's text, as the board sent it. + pub payload: String, + /// Name of the board that sent the message. pub board: String, /// Where on the board the message was produced, as the board sends it in - /// the packet's `origin` field, such as a source file. Empty for messages - /// the backend produces itself, such as order notices and protections. + /// the packet's `origin` field, such as a source file. pub origin: String, - /// Display name of the event; order-sent notices use the order id as text. + /// Display name of the message. pub name: String, /// Original RTC fields, without a timezone conversion. pub timestamp: MessageTimestamp, @@ -27,24 +30,6 @@ impl TopicPayload for MessageUpdate { const TOPIC: &'static str = "message/update"; } -/// Both message shapes accepted by the existing frontend. -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(untagged)] -pub enum MessagePayload { - /// An informational notice or a board's free-text message. - Text(String), - /// Protection details, as published on `message/update` by Go. - Protection(ProtectionPayload), -} - -/// The message level that shows a triggered protection of this severity. -pub fn protection_level(severity: Severity) -> MessageLevel { - match severity { - Severity::Fault => MessageLevel::Fault, - Severity::Warning => MessageLevel::Warning, - } -} - /// Calendar timestamp used by `message/update`, `protection/update` and /// `backend/message`. /// diff --git a/backend/crates/station/src/payload/protection.rs b/backend/crates/station/src/payload/protection.rs index e64d1efd1..ef40aa4b4 100644 --- a/backend/crates/station/src/payload/protection.rs +++ b/backend/crates/station/src/payload/protection.rs @@ -3,11 +3,12 @@ use super::{ serialize::{serialize_adj_id, serialize_value}, }; use serde::Serialize; -use serde_json::Value as JsonValue; use software_core::model::{AdjId, ProtectionPacket, Value}; /// Payload of `protection/update`: the triggered id, measured value and time. +/// +/// Protections travel only on this topic, never on `message/update`. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ProtectionUpdate { /// Compound ID used to look up the protection definition in the ADJ catalog. @@ -36,58 +37,3 @@ impl ProtectionUpdate { } } } - -/// Legacy protection details used only by `message/update`. -/// -/// Values retain their JSON number or boolean representation. ADJ validation -/// and conversion from domain packets belong to the publisher. -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(tag = "kind", content = "data", rename_all = "SCREAMING_SNAKE_CASE")] -pub enum ProtectionPayload { - /// A value dropped below its lower bound. - LowerBound { - /// Lower bound. - bound: JsonValue, - /// Value that triggered the protection. - value: JsonValue, - }, - /// A value exceeded its upper bound. - UpperBound { - /// Upper bound. - bound: JsonValue, - /// Value that triggered the protection. - value: JsonValue, - }, - /// A value left the allowed interval. - OutOfBounds { - /// Lower and upper bounds, in that order. - bounds: [JsonValue; 2], - /// Value that triggered the protection. - value: JsonValue, - }, - /// A value matched the protected value. - Equals { - /// Value that triggered the protection. - value: JsonValue, - }, - /// A value differed from the expected value. - NotEquals { - /// Expected value. - want: JsonValue, - /// Value that triggered the protection. - value: JsonValue, - }, - /// The legacy time-accumulation protection. - TimeAccumulation { - /// Value that triggered the protection. - value: JsonValue, - /// Threshold. - bound: JsonValue, - /// Time limit in seconds. - timelimit: f32, - }, - /// Legacy firmware error text. - ErrorHandler(String), - /// Legacy warning text. - Warning(String), -} diff --git a/frontend/frontend-kit/kit/src/core/websocket.ts b/frontend/frontend-kit/kit/src/core/websocket.ts index 29767fd11..17990c888 100644 --- a/frontend/frontend-kit/kit/src/core/websocket.ts +++ b/frontend/frontend-kit/kit/src/core/websocket.ts @@ -107,6 +107,13 @@ class SocketService { */ private config: SocketConfig = {}; + /** + * Number of listeners of each topic. The backend keeps a single subscription + * per topic and connection, so it is requested for the first listener and + * dropped after the last one. + */ + private topicListeners = new Map(); + /** * The URL the current or next connection targets. */ @@ -271,6 +278,37 @@ class SocketService { return pipe$; } + /** + * Registers a listener of `topic`, asking the backend to publish it when it is + * the first one.\ + * Another listener unsubscribing must not leave this one without updates: + * the backend would stop the topic for the whole connection. + * @param topic - the topic to subscribe to. + * @returns a function that unregisters the listener, asking the backend to + * stop publishing the topic when it was the last one. + */ + subscribeTopic(topic: string): () => void { + const listeners = this.topicListeners.get(topic) ?? 0; + this.topicListeners.set(topic, listeners + 1); + if (listeners === 0) this.post(topic, { subscribe: true }); + + let released = false; + return () => { + if (released) return; + released = true; + + const remaining = (this.topicListeners.get(topic) ?? 1) - 1; + if (remaining > 0) { + this.topicListeners.set(topic, remaining); + return; + } + + this.topicListeners.delete(topic); + // A closed connection already dropped its subscriptions + this.ws?.next({ topic, payload: { subscribe: false } }); + }; + } + /** * Posts a message to the WebSocket server. If the connection is not established, an error is logged and the message is not sent. * @param topic - the topic to post to. diff --git a/frontend/frontend-kit/kit/src/hooks/webSocket/useTopic.ts b/frontend/frontend-kit/kit/src/hooks/webSocket/useTopic.ts index b1f4b0740..3de2d5666 100644 --- a/frontend/frontend-kit/kit/src/hooks/webSocket/useTopic.ts +++ b/frontend/frontend-kit/kit/src/hooks/webSocket/useTopic.ts @@ -19,7 +19,7 @@ export function useTopic( if (!isConnected) return; logger.testingView.log(`[useTopic] Subscribing to: ${topic}`); - socketService.post(topic, { subscribe: true }); + const unsubscribeTopic = socketService.subscribeTopic(topic); const sub = socketService.onTopic(topic, options).subscribe((data: T) => { callbackRef.current(data); @@ -27,7 +27,7 @@ export function useTopic( return () => { logger.testingView.log(`[useTopic] Unsubscribing from: ${topic}`); - socketService.post(topic, { subscribe: false }); + unsubscribeTopic(); sub.unsubscribe(); }; }, [topic, isConnected, JSON.stringify(options)]); diff --git a/frontend/testing-view/src/App.tsx b/frontend/testing-view/src/App.tsx index ebe5212d6..98bc1ea98 100644 --- a/frontend/testing-view/src/App.tsx +++ b/frontend/testing-view/src/App.tsx @@ -1,4 +1,5 @@ import { useTopic, useWebSocket } from "@hyperloopupv/frontend-kit/hooks"; +import { useMemo } from "react"; import { Route, Routes } from "react-router"; import { AppModeRouter } from "./components/AppModeRouter"; import { ModeSwitcher } from "./components/devTools/ModeSwitcher"; @@ -9,11 +10,18 @@ import { useAppMode } from "./hooks/useAppMode"; import { useErrorHandler } from "./hooks/useErrorHandler"; import { useTransformedBoards } from "./hooks/useTransformedBoards"; import { AppLayout } from "./layout/AppLayout"; +import { + backendMessageToMessage, + getMeasurementAliases, + keyMeasurementsByAlias, + protectionToMessage, +} from "./lib/utils"; import { Logs } from "./pages/Logs"; import { Testing } from "./pages/Testing"; import { useStore } from "./store/store"; import type { Connection } from "./types/common/connection"; -import type { MessagePacket } from "./types/data/message"; +import type { BackendMessage, MessagePacket } from "./types/data/message"; +import type { ProtectionUpdate } from "./types/data/protection"; import type { TelemetryData } from "./types/telemetry/telemetry"; function App() { @@ -21,7 +29,8 @@ function App() { const { reportError } = useErrorHandler(); // Fetch app configs - const { packets, commands, isLoading } = useAppConfigs(isConnected); + const { packets, commands, protections, isLoading } = + useAppConfigs(isConnected); // Determine app mode useAppMode(packets, commands, isLoading); @@ -35,11 +44,18 @@ function App() { // Callback executed when telemetry data is received const addTelemetry = useStore((s) => s.addTelemetry); + // The backend keys measurements by numeric id, the app by alias + const telemetryCatalog = useStore((s) => s.telemetryCatalog); + const measurementAliases = useMemo( + () => getMeasurementAliases(telemetryCatalog), + [telemetryCatalog], + ); + // Subscribe to telemetry updates useTopic( "podData/update", (data) => { - addTelemetry(data); + addTelemetry(keyMeasurementsByAlias(data, measurementAliases)); }, { downsample: "none", throttle: 100 }, ); @@ -55,12 +71,37 @@ function App() { // Callback executed when messages are received const addMessage = useStore((s) => s.addMessage); - useTopic("message/update", (data) => { - console.log("Message received:", data); - addMessage({ - ...data, - id: crypto.randomUUID(), - }); + // The backend doesn't send the category: it's the topic the message arrives on + const handleMessage = + (category: MessagePacket["category"]) => (data: MessagePacket) => { + console.log("Message received:", data); + addMessage({ + ...data, + category, + id: crypto.randomUUID(), + }); + }; + + // Each message category arrives on its own topic: message/update only + // carries the messages boards send + useTopic("message/update", handleMessage("message")); + useTopic("backend/message", (message) => + handleMessage("backend")(backendMessageToMessage(message)), + ); + + // Callback executed when a protection triggers + const addProtection = useStore((s) => s.addProtection); + + // Protections highlight the measurement that triggered them and are shown as messages + useTopic("protection/update", (protection) => { + addProtection(protection); + handleMessage("protection")( + protectionToMessage( + protection, + protections?.protections ?? [], + telemetryCatalog, + ), + ); }); return ( diff --git a/frontend/testing-view/src/features/keyBindings/components/AddKeyBindingDialog.tsx b/frontend/testing-view/src/features/keyBindings/components/AddKeyBindingDialog.tsx index 77844d240..8529b833c 100644 --- a/frontend/testing-view/src/features/keyBindings/components/AddKeyBindingDialog.tsx +++ b/frontend/testing-view/src/features/keyBindings/components/AddKeyBindingDialog.tsx @@ -17,7 +17,10 @@ import { } from "@hyperloopupv/frontend-kit"; import { X } from "@hyperloopupv/frontend-kit/icons"; import { useEffect, useRef, useState } from "react"; -import { getDefaultParameterValues } from "../../../lib/commandUtils"; +import { + getDefaultParameterValues, + getParameterKind, +} from "../../../lib/commandUtils"; import { useStore } from "../../../store/store"; import type { CommandCatalogItem } from "../../../types/data/commandCatalogItem"; import { CommandParameters } from "../../workspace/components/rightSidebar/tabs/commands/CommandParameters"; @@ -56,7 +59,7 @@ export const AddKeyBindingDialog = ({ : null; const hasParameters = selectedCommand - ? Object.keys(selectedCommand.fields).length > 0 + ? selectedCommand.measurements.length > 0 : false; // Reset state when dialog closes @@ -73,7 +76,7 @@ export const AddKeyBindingDialog = ({ useEffect(() => { if (selectedCommand) { const defaults: Record = getDefaultParameterValues( - selectedCommand.fields, + selectedCommand.measurements, ); setParameterValues(defaults); } @@ -124,9 +127,10 @@ export const AddKeyBindingDialog = ({ const hasInvalidNumericParams = selectedCommand !== null && selectedCommand !== undefined && - Object.entries(selectedCommand.fields).some( - ([key, field]) => - field.kind === "numeric" && isNaN(parseFloat(parameterValues[key])), + selectedCommand.measurements.some( + (field) => + getParameterKind(field) === "numeric" && + isNaN(parseFloat(parameterValues[field.alias])), ); const canSubmit = @@ -199,12 +203,12 @@ export const AddKeyBindingDialog = ({
- {Object.keys(selectedCommand.fields).length} parameter(s) + {selectedCommand.measurements.length} parameter(s)
diff --git a/frontend/testing-view/src/features/keyBindings/hooks/useGlobalKeyBindings.ts b/frontend/testing-view/src/features/keyBindings/hooks/useGlobalKeyBindings.ts index 9a46c26e0..e9898b16b 100644 --- a/frontend/testing-view/src/features/keyBindings/hooks/useGlobalKeyBindings.ts +++ b/frontend/testing-view/src/features/keyBindings/hooks/useGlobalKeyBindings.ts @@ -1,7 +1,11 @@ import { logger, socketService } from "@hyperloopupv/frontend-kit/core"; import { useEffect } from "react"; import { useLogger } from "../../../hooks/useLogger"; -import { getDefaultParameterValues } from "../../../lib/commandUtils"; +import { + getDefaultParameterValues, + getFieldType, + getParameterKind, +} from "../../../lib/commandUtils"; import { useStore } from "../../../store/store"; import type { CommandCatalogItem } from "../../../types/data/commandCatalogItem"; import { @@ -76,22 +80,29 @@ export const useGlobalKeyBindings = () => { // Build payload with binding's configured parameters const payload = { id: commandToExecute.id, - fields: Object.entries(commandToExecute.fields).reduce( - (acc, [fieldKey, field]) => { + fields: commandToExecute.measurements.reduce( + (acc, field) => { + const fieldKey = field.alias; + // Use binding's parameter value or fall back to default let value = parameterValues[fieldKey]; // If no value in binding, use field defaults if (value === undefined) { - value = getDefaultParameterValues(commandToExecute.fields)[ - fieldKey - ]; + value = getDefaultParameterValues( + commandToExecute.measurements, + )[fieldKey]; } const numericValue = - field.kind === "numeric" ? parseFloat(value) : value; - - if (field.kind === "numeric" && isNaN(numericValue as number)) { + getParameterKind(field) === "numeric" + ? parseFloat(value) + : value; + + if ( + getParameterKind(field) === "numeric" && + isNaN(numericValue as number) + ) { logger.testingView.warn( `Skipping command: numeric field "${fieldKey}" has no valid value`, ); @@ -101,7 +112,7 @@ export const useGlobalKeyBindings = () => { acc[fieldKey] = { value: numericValue, isEnabled: true, - type: field.type, + type: getFieldType(field), }; return acc; }, diff --git a/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessageItem.tsx b/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessageItem.tsx index aa12bdd89..0f6dda801 100644 --- a/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessageItem.tsx +++ b/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessageItem.tsx @@ -19,43 +19,15 @@ interface MessageItemProps { export const MessageItem = ({ message }: MessageItemProps) => { const [isOpen, setIsOpen] = useState(false); - let label = "Backend"; + // Backend messages carry the board they concern too, or "Backend" if none + const label = message.board; let Icon: LucideIcon | undefined = Rows3; if (message.category === "protection") { - label = `${message.board}`; Icon = Shield; } else if (message.category === "message") { - label = `${message.board}`; Icon = undefined; } - const renderMessageContent = (payload: any) => { - // 1. Simple string (Info messages) - if (typeof payload === "string") return payload; - - // 2. Protection object - if (payload && typeof payload === "object") { - const { kind, data } = payload; - - // Handle string-based data (ERROR_HANDLER, WARNING) - if (typeof data === "string") return data; - - // Handle numeric bounds (OUT_OF_BOUNDS, UPPER_BOUND, etc.) - if (kind === "OUT_OF_BOUNDS" && data.bounds) { - return `Value: ${data.value} (Bounds: [${data.bounds[0]}, ${data.bounds[1]}])`; - } - - if (kind === "UPPER_BOUND" || kind === "LOWER_BOUND") { - return `Value: ${data.value} (Limit: ${data.bound})`; - } - - // Fallback for complex data objects - return JSON.stringify(data); - } - - return "No detail available"; - }; - return ( { {message.name} + {/* Closed, the icon goes at the end of the row, so the message takes a single line */} + {Icon && !isOpen && ( +
- {/* Block (not flex) so the floated icon sits under the time and the - expanded text flows to its right, then wraps underneath it. */} + {/* Open, the icon moves under the time. Block (not flex) so the floated + icon sits there and the text flows to its right, then wraps underneath it. */}
- {Icon && ( + {Icon && isOpen && ( // Same font as the timestamp, so 8ch = width of "HH:MM:SS" { )}
e.stopPropagation()}> - {/* If it's a detailed message, showing the sub-kind can be helpful */} - {message.payload && - typeof message.payload === "object" && - message.payload.kind && ( - - {message.payload.kind.replace("_", " ")} - - )}

- {renderMessageContent(message.payload)} + {message.payload}

diff --git a/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessagesSection.tsx b/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessagesSection.tsx index 533c592c8..f8c39c1a1 100644 --- a/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessagesSection.tsx +++ b/frontend/testing-view/src/features/workspace/components/rightSidebar/sections/MessagesSection.tsx @@ -24,6 +24,8 @@ const MessagesSection = () => { variant="secondary" size="icon" className="text-muted-foreground hover:text-destructive h-6 w-6" + title="Clear messages and protections" + aria-label="Clear messages and protections" onClick={clearMessages} > diff --git a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandItem.tsx b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandItem.tsx index 70518b8bd..f1032e320 100644 --- a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandItem.tsx +++ b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandItem.tsx @@ -8,7 +8,11 @@ import { import { ChevronDown, Play, Send } from "@hyperloopupv/frontend-kit/icons"; import { cn } from "@hyperloopupv/frontend-kit/lib"; import { useState } from "react"; -import { getDefaultParameterValues } from "../../../../../../lib/commandUtils"; +import { + getDefaultParameterValues, + getFieldType, + getParameterKind, +} from "../../../../../../lib/commandUtils"; import { useStore } from "../../../../../../store/store"; import type { CommandCatalogItem } from "../../../../../../types/data/commandCatalogItem"; import { CommandParameters } from "./CommandParameters"; @@ -27,16 +31,16 @@ export const CommandItem = ({ item: commandCatalogItem }: CommandItemProps) => { ); const [parameterValues, setParameterValues] = useState>( - () => getDefaultParameterValues(commandCatalogItem.fields), + () => getDefaultParameterValues(commandCatalogItem.measurements), ); - const paramCount = Object.keys(commandCatalogItem.fields).length; + const paramCount = commandCatalogItem.measurements.length; const hasParameters = paramCount > 0; - const hasInvalidNumeric = Object.entries(commandCatalogItem.fields).some( - ([key, field]) => - field.kind === "numeric" && - !Number.isFinite(parseFloat(parameterValues[key])), + const hasInvalidNumeric = commandCatalogItem.measurements.some( + (field) => + getParameterKind(field) === "numeric" && + !Number.isFinite(parseFloat(parameterValues[field.alias])), ); const handleRun = (e: React.MouseEvent) => { @@ -45,15 +49,16 @@ export const CommandItem = ({ item: commandCatalogItem }: CommandItemProps) => { const payload = { id: commandCatalogItem.id, - fields: Object.entries(commandCatalogItem.fields).reduce( - (acc, [key, field]) => { + fields: commandCatalogItem.measurements.reduce( + (acc, field) => { + const key = field.alias; acc[key] = { value: - field.kind === "numeric" + getParameterKind(field) === "numeric" ? parseFloat(parameterValues[key]) : parameterValues[key], isEnabled: true, // Set to true by default, could be implemented in the future, but does not really make any sense for me - type: field.type, + type: getFieldType(field), }; return acc; }, @@ -133,7 +138,7 @@ export const CommandItem = ({ item: commandCatalogItem }: CommandItemProps) => {
diff --git a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandParameters.tsx b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandParameters.tsx index e7b8e32f4..8e5950306 100644 --- a/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandParameters.tsx +++ b/frontend/testing-view/src/features/workspace/components/rightSidebar/tabs/commands/CommandParameters.tsx @@ -8,14 +8,16 @@ import { SelectTrigger, SelectValue, } from "@hyperloopupv/frontend-kit"; -import type { - CommandParameter, - EnumCommandParameter, - NumericCommandParameter, -} from "../../../../../../types/data/commandCatalogItem"; +import { + getEnumOptions, + getFieldType, + getParameterKind, +} from "../../../../../../lib/commandUtils"; +import { describeCondition } from "../../../../../../lib/utils"; +import type { CommandParameter } from "../../../../../../types/data/commandCatalogItem"; interface CommandParametersProps { - fields: Record; + fields: CommandParameter[]; values: Record; onChange: (fieldId: string, value: any) => void; } @@ -26,63 +28,58 @@ export const CommandParameters = ({ onChange, }: CommandParametersProps) => { const renderParameterInput = (field: CommandParameter) => { - if (field.kind === "numeric") { - const numField = field as NumericCommandParameter; - const minSafeRange = numField.safeRange[0]; - const maxSafeRange = numField.safeRange[1]; - const minWarningRange = numField.warningRange[0]; - const maxWarningRange = numField.warningRange[1]; + const kind = getParameterKind(field); + if (kind === "numeric") { return ( -
+
onChange(field.id, e.target.value)} + placeholder={getFieldType(field)} + value={values[field.alias] ?? ""} + onChange={(e) => onChange(field.alias, e.target.value)} onWheel={(e) => e.currentTarget.blur()} className="h-8 text-xs" /> - {minSafeRange !== null && maxSafeRange !== null && ( -

- Range: {minSafeRange} to {maxSafeRange} -

- )} - {minWarningRange !== null && maxWarningRange !== null && ( -

- Warning range: {minWarningRange} to {maxWarningRange} + {field.protections.map((protection) => ( +

+ {protection.severity === "fault" ? "Fault" : "Warning"} if{" "} + {describeCondition(protection.type)} + {protection.time && ` for ${protection.time}`}

- )} + ))}
); } - if (field.kind === "enum") { - const enumField = field as EnumCommandParameter; + if (kind === "enum") { return ( -
+