#![allow(clippy::print_stdout, clippy::print_stderr, clippy::cast_precision_loss)]
#[path = "ied/scl_edit.rs"]
mod scl_edit;
use std::fmt::Write as _;
use std::process::ExitCode;
use std::time::Duration;
use iec61850_kit::client::{Client, ClientConfig, RcbSettings, Unsolicited};
use iec61850_kit::common::{Edition, EntryTime, Fc, Instant, Limits, TimeQuality, UtcTime};
use iec61850_kit::model::IedModel;
use iec61850_kit::pcap::{Capture, Writer};
use iec61850_kit::proto::data::{Typed, Value as IedValue};
use iec61850_kit::proto::ethernet::{ETHERTYPE_GOOSE, ETHERTYPE_GSE_MGMT, ETHERTYPE_SV, Frame, FrameHeader, MacAddr, VlanTag};
use iec61850_kit::proto::goose::{GoosePduView, Subscriber as GooseSubscriber, SubscriberConfig, SubscriberEvent, SubscriptionKey};
use iec61850_kit::proto::mms::control::{AddCause, Check, ControlModel, OriginCategory};
use iec61850_kit::proto::mms::file;
use iec61850_kit::proto::mms::report::{OptFlds, ReasonCode, Report, TrgOps};
use iec61850_kit::proto::mms::typespec::TypeSpec;
use iec61850_kit::proto::sv::le::PhsMeas1;
use iec61850_kit::proto::sv::{ChannelValue, Publisher, PublisherConfig, SavPduView, SmpMod, SmpSynch, StreamConfig, StreamKey, SvProfile};
use iec61850_kit::scl::{self, LoadOptions};
use iec61850_kit::server::{DirectoryStore, Ied, Server};
const USAGE: &str = "\
ied — IEC 61850 command line
USAGE:
ied <COMMAND> [ARGS]
COMMANDS:
goose sniff <FILE.pcap> Decode GOOSE and run the subscriber's verdict over it
goose sniff --iface <IF> …on a live interface
goose publish --iface <IF> --scd <FILE> --gocb <REF>
Publish a GOOSE control block of an SCD on an interface
mms sniff <FILE.pcap> Decode MMS over the OSI stack: association, services, values
mms identify <HOST[:PORT]> Associate with a server and print what it says it is
mms status <HOST[:PORT]> Ask whether the server is healthy — the cheapest round trip there is
mms browse <HOST[:PORT]> Walk the server: logical devices, data, data sets
mms read <HOST[:PORT]> <REF> Read one data attribute
mms tariff <HOST[:PORT]> <LD/FSCH> <START> <END> <UNIT>
Read a daily tariff; START and END are UTC Unix seconds
mms write <HOST[:PORT]> <REF> <VALUE>
Write one data attribute
mms report <HOST[:PORT]> Enable a report control block and print its reports
mms rcb <HOST[:PORT]> <REF> Print a report control block's configuration
mms control <HOST[:PORT]> <REF> <VALUE>
Operate a controllable object
mms type <HOST[:PORT]> <REF> What type a variable is, read from the server
mms files <HOST[:PORT]> [DIR] List the server's files
mms get <HOST[:PORT]> <PATH> [OUT]
Read a file off the server (COMTRADE records live here)
mms put <HOST[:PORT]> <LOCAL> <REMOTE>
Send a file to the server (SetFile)
mms log <HOST[:PORT]> <LOG> Read a log's entries; --lcb prints its control block
mms sg <HOST[:PORT]> [REF] Setting groups: print, --activate N, --edit N
sv monitor <FILE.pcap> Track sampled-value streams: gaps, sync, staleness
sv monitor --iface <IF> …on a live interface
pcap info <FILE.pcap> Summarise what a capture contains
scl validate <FILE.scl> Engineering checks the XML schema does not make
scl show <FILE.scl> [IED] Print an IED's model: devices, nodes, control blocks
scl subs <FILE.scd> <IED> What an IED subscribes to, resolved from the publishers
scl edit <FILE.scl> <EDIT> Change the file without reformatting it (see below)
mu <FILE.pcap> [OPTIONS] Generate a sampled-value stream into a capture
mu --iface <IF> [OPTIONS] …onto a live interface, paced at the profile's rate
sim <FILE.scd|.icd|.cid> Serve the file's IEDs as real MMS servers
`mms tariff` options:
--start-object <NAME> Absolute start object (default StrTm1)
--first-price <NAME> First numbered price object (default ValASG001)
--fc <SP|SG> Settings constraint (default SP)
Every command answers -h / --help with its own usage.
Live interfaces need CAP_NET_RAW on Linux — grant it to the binary with
`sudo setcap cap_net_raw+ep $(command -v ied)` rather than running as root — or access to
/dev/bpf* on macOS. The capability is dropped as soon as the interface is open.
Live options (goose sniff, sv monitor):
--iface <IF> the interface to listen on
--duration <S> how long to listen before reporting (default 10)
--write <FILE.pcap> keep the capture
--promiscuous also receive frames addressed elsewhere (port mirrors)
--group <MAC> receive exactly this multicast group (repeatable) instead of the
IEC range, e.g. a publisher engineered outside it
`mms` client options (identify/browse/read/write/report):
--fc <ST|MX|CO|SP|...> functional constraint for a dotted reference. Reads default to
ST; `mms write` requires it, because a conforming server refuses
a write to ST and MX — those are what the process reports.
Settings are SP/SE, configuration CF, description DC.
--password <TEXT> ACSE password (IEC 61850-8-1 authentication)
--type <bool|int|uint|float|string>
how to encode the value of `mms write` (default bool)
--timeout <SECONDS> how long to wait for an answer (default 30)
--seconds <N> how long `mms report` listens (default 30)
--rcb <REF> report control block for `mms report` to enable
--buffered the control block is buffered (BR); inferred from a $BR$ reference
--data-set <REF> data set to report, in MMS form (LD/LLN0$dsTrip)
--intg-pd <MS> integrity period; also turns the integrity trigger on
--gi request a general interrogation after enabling
--model <direct|sbo|direct-enhanced|sbo-enhanced>
control model of the object (default direct)
--orcat <0-8> originator category (default 3, remote control)
--orident <TEXT> originator identifier (default `ied`)
--synchro, --interlock ask the server to run these checks before operating
--test mark the command as a test
--max-size <BYTES> largest file `mms get` will read (default 16777216)
--activate <N> `mms sg`: put setting group N into force
--edit <N> `mms sg`: reserve setting group N for editing
--lcb <REF> `mms log`: also read this log control block
--entries <N> `mms log`: stop after this many entries (default 1000)
--scd <FILE> --ied <N> take the OSI selectors and AP-title from the engineering file;
with a host of `-`, take the IP address from it too
--local-tsel <HEX> OSI transport selector this end presents (default 0001)
--remote-tsel <HEX> OSI transport selector of the server (default 0001)
`goose publish` options:
--iface <IF> the interface to publish on
--scd <FILE> the engineering file
--ied <NAME> the publishing IED (default: the file's only one)
--gocb <REF> the control block, LD/LN.name (IED1LD0/LLN0.gcbTrip)
--value <TEXT> a value per data-set member, in order (default: the file's values)
--duration <S> publish for this long (default 10): the first frame, then the
retransmission curve the file's MinTime/MaxTime give
`sim` options:
--iface <IF> publish the GoCBs and MSVCBs a client enables on this interface
--freq <50|60> nominal frequency, for an MSVCB's smpRate per period (default 50)
--ied <NAME> serve only this IED (default: every IED in the file)
--bind <ADDR> address to listen on (default 127.0.0.1)
--port <N> first port; each further IED takes the next one (default 102)
--files <DIR> serve this directory through the MMS file services, read-only
--writable also let clients delete files there and send files to it (SetFile);
with --password, only a client that presents the password may send
--password <TEXT> require this ACSE password of every association
--edition <1|2|2.1> serve as this edition, overriding the file's own schema version
(Edition 1 has no ResvTms and no Owner on a report control block)
--log-db <PATH> keep the logs in a file that survives a restart (a directory of
<IED>.redb files when the SCD has several IEDs)
`scl validate` options:
--freq <50|60> nominal frequency, to read smpRate (default 50)
--edition <1|2|2.1> edition whose object-reference limit applies (default 2.1)
--strict treat warnings as errors
`scl subs` options:
--freq <50|60> nominal frequency, to read smpRate (default 50)
`scl edit` edits (references to a renamed or removed IED move with it):
rename-ied <OLD> <NEW>
remove-ied <NAME>
gse <IED> <LD> <CB> --mac M --appid HEX --vlan HEX --vlan-priority N
--min-time MS --max-time MS (unset fields keep their value)
smv <IED> <LD> <CB> --mac M --appid HEX --vlan HEX --vlan-priority N
ap-address <IED> <AP> <P-TYPE> <VALUE> e.g. IP 10.0.0.5
history --what TEXT [--version V] [--revision R] add a Header/History item
`scl edit` options:
-o <FILE> | --in-place where to write (default stdout); written atomically
--dry-run print a unified diff and write nothing
--who <NAME> --why <TEXT>
also record the edit as a Header/History item
--check refuse to write if the result has any validation error
--force write even if the edit adds validation errors (refused otherwise)
--max-size <BYTES> refuse larger input before reading it (default 1 GiB)
--freq <50|60> nominal frequency, for validation (default 50)
`sv monitor` options:
--freq <50|60> nominal frequency, to read smpRate in samples per period (default 50)
--rate <N> samples per second, overriding what the stream advertises
--scd <FILE.scd> configure the streams from an engineering file instead of from the
capture: rate, confRev and the data set that says what each ASDU's
octets mean, so samples decode into named channels
--ied <NAME> with --scd, only the streams this IED publishes
`mu` options:
--profile <le80-50|le80-60|le256-50|le256-60|f4800s2|f14400s6> default le80-50
--frames <N> frames to generate (default 1000)
--sv-id <ID> svID to publish (default MU01)
--appid <HEX> APPID (default 4000)
--freq <N> nominal frequency of the synthetic waveform in Hz (default: 60 for a 60 Hz 9-2LE profile, else 50)
--amplitude <N> peak of the synthetic sinusoid, raw units (default 100000)
--gm <HEX> publish gmIdentity, 8 octets as 16 hex digits
--refr-tm publish refrTm on every ASDU
--iface <IF> send on this interface instead of writing a capture
--launch-time hand each frame to the kernel with its launch time (SO_TXTIME;
needs an etf or taprio qdisc on the interface)
";
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let words: Vec<&str> = args.iter().map(String::as_str).collect();
if words.len() > 1 && words.iter().any(|w| matches!(*w, "-h" | "--help")) {
print!("{}", help_for(&words));
return ExitCode::SUCCESS;
}
let result = match words.as_slice() {
[] | ["-h" | "--help" | "help"] => {
print!("{USAGE}");
return ExitCode::SUCCESS;
}
["--version" | "-V"] => {
println!("ied {}", env!("CARGO_PKG_VERSION"));
return ExitCode::SUCCESS;
}
["goose", "sniff", rest @ ..] => goose_sniff_cmd(rest),
["goose", "publish", rest @ ..] => goose_publish(rest),
["mms", "sniff", file] => file_arg(file).and_then(mms_sniff),
["mms", "identify", host, rest @ ..] => mms_identify(host, rest),
["mms", "status", host, rest @ ..] => mms_status(host, rest),
["mms", "browse", host, rest @ ..] => mms_browse(host, rest),
["mms", "tariff", host, node, start, end, unit, rest @ ..] => mms_tariff(host, node, start, end, unit, rest),
["mms", "read", host, reference, rest @ ..] => mms_read(host, reference, rest),
["mms", "write", host, reference, value, rest @ ..] => mms_write(host, reference, value, rest),
["mms", "report", host, rest @ ..] => mms_report(host, rest),
["mms", "rcb", host, reference, rest @ ..] => mms_rcb(host, reference, rest),
["mms", "control", host, reference, value, rest @ ..] => mms_control(host, reference, value, rest),
["mms", "type", host, reference, rest @ ..] => mms_type(host, reference, rest),
["mms", "files", host, rest @ ..] => mms_files(host, rest),
["mms", "get", host, path, rest @ ..] => mms_get(host, path, rest),
["mms", "put", host, local, remote, rest @ ..] => mms_put(host, local, remote, rest),
["mms", "log", host, log, rest @ ..] => mms_log(host, log, rest),
["mms", "sg", host, rest @ ..] => mms_setting_groups(host, rest),
["sv", "monitor", rest @ ..] => sv_monitor_cmd(rest),
["pcap", "info", file] => file_arg(file).and_then(pcap_info),
["scl", "validate", file, rest @ ..] => file_arg(file).and_then(|f| scl_validate(f, rest)),
["scl", "show", file, rest @ ..] => file_arg(file).and_then(|f| scl_show(f, rest.first().copied())),
["scl", "subs", file, ied, rest @ ..] => file_arg(file).and_then(|f| scl_subs(f, ied, rest)),
["scl", "edit", file, rest @ ..] => file_arg(file).and_then(|f| scl_edit::run(f, rest)),
["mu", rest @ ..] => mu_cmd(rest),
["sim", file, rest @ ..] => file_arg(file).and_then(|f| simulate(f, rest)),
other => Err(format!("unknown command `{}`\n\n{USAGE}", other.join(" "))),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("ied: {e}");
ExitCode::FAILURE
}
}
}
fn file_arg(file: &str) -> Result<&str, String> {
if file.starts_with('-') {
return Err(format!("expected a file name, found the option `{file}` (see --help)"));
}
Ok(file)
}
fn help_for(words: &[&str]) -> String {
let command: Vec<&str> = words.iter().take_while(|w| !w.starts_with('-')).take(2).copied().collect();
let prefix = command.join(" ");
let first = command.first().copied().unwrap_or_default();
let mut out = String::from("ied — IEC 61850 command line\n\nUSAGE:\n");
let mut lines = USAGE.lines().peekable();
while let Some(line) = lines.next() {
let l = line.trim_start();
if !prefix.is_empty() && l.starts_with(&prefix) && line.starts_with(" ") {
let _ = writeln!(out, " ied {l}");
while let Some(next) = lines.next_if(|n| n.starts_with(" ") && !n.trim_start().starts_with(first)) {
let _ = writeln!(out, "{next}");
}
}
}
let mut in_section = false;
for l in USAGE.lines() {
if l.is_empty() {
in_section = false;
continue;
}
if !l.starts_with(' ') && !l.ends_with(':') {
in_section = false;
continue;
}
if !l.starts_with(' ') {
in_section = l.contains(&format!("`{prefix}`"))
|| l.contains(&format!("`{first}`"))
|| (l.starts_with("Live") && matches!(prefix.as_str(), "goose sniff" | "sv monitor"));
if in_section {
let _ = writeln!(out, "\n{l}");
}
continue;
}
if in_section {
let _ = writeln!(out, "{l}");
}
}
if matches!(prefix.as_str(), "goose sniff" | "sv monitor" | "goose publish" | "mu" | "sim") {
out.push_str("\nLive interfaces need CAP_NET_RAW (Linux) or /dev/bpf* access (macOS); see `ied --help`.\n");
}
out
}
struct LiveOptions {
iface: String,
duration: Duration,
write: Option<String>,
promiscuous: bool,
groups: Vec<MacAddr>,
}
fn live_options<'a>(args: &[&'a str]) -> Result<(Option<LiveOptions>, Vec<&'a str>), String> {
let mut live = LiveOptions { iface: String::new(), duration: Duration::from_secs(10), write: None, promiscuous: false, groups: Vec::new() };
let mut rest = Vec::new();
let mut it = args.iter();
while let Some(arg) = it.next() {
let mut value = || it.next().copied().ok_or_else(|| format!("{arg} needs a value"));
match *arg {
"--iface" => live.iface = value()?.to_string(),
"--duration" => live.duration = Duration::from_secs_f64(value()?.parse().map_err(|_| "--duration needs seconds".to_string())?),
"--write" => live.write = Some(file_arg(value()?)?.to_string()),
"--promiscuous" => live.promiscuous = true,
"--group" => {
let mac = value()?;
live.groups.push(MacAddr::parse(mac).map_err(|e| format!("--group {mac}: {e}"))?);
}
other => rest.push(other),
}
}
Ok((if live.iface.is_empty() { None } else { Some(live) }, rest))
}
fn capture_live(live: &LiveOptions, options: iec61850_kit::net::LinkOptions) -> Result<String, String> {
use iec61850_kit::net::{Link, drop_capabilities};
let options = live.groups.iter().fold(options, |o, g| o.join(*g));
let mut link = Link::open(&live.iface, &options.promiscuous(live.promiscuous)).map_err(|e| format!("{}: {e}", live.iface))?;
drop_capabilities().map_err(|e| e.to_string())?;
let path = live.write.clone().unwrap_or_else(|| std::env::temp_dir().join(format!("ied-live-{}.pcap", std::process::id())).display().to_string());
let mut out = Writer::create(&path).map_err(|e| format!("{path}: {e}"))?;
eprintln!("listening on {} ({}, {:?}) for {:.1} s", link.interface(), link.mac(), link.receive_path(), live.duration.as_secs_f64());
let end = std::time::Instant::now() + live.duration;
let (mut frames, mut truncated) = (0u64, 0u64);
loop {
let left = end.saturating_duration_since(std::time::Instant::now());
if left.is_zero() {
break;
}
let Some(rx) = link.recv(Some(left.min(Duration::from_millis(100)))).map_err(|e| e.to_string())? else { continue };
if rx.truncated {
truncated += 1;
continue;
}
let ts = rx.wire_time.map_or(rx.at.0, |w| u64::try_from(w.secs).unwrap_or(0).saturating_mul(1_000_000_000).saturating_add(u64::from(w.nanos)));
out.write(ts, rx.frame).map_err(|e| e.to_string())?;
frames += 1;
}
out.finish().map_err(|e| e.to_string())?;
let stats = link.stats().map_err(|e| e.to_string())?;
eprintln!(
"captured {frames} frame(s){}{}",
if truncated > 0 { format!(", {truncated} truncated (not decoded)") } else { String::new() },
if stats.dropped > 0 { format!(", {} dropped by the kernel", stats.dropped) } else { String::new() }
);
Ok(path)
}
fn goose_sniff_cmd(args: &[&str]) -> Result<(), String> {
let (live, rest) = live_options(args)?;
match (live, rest.as_slice()) {
(Some(live), []) => {
let path = capture_live(&live, iec61850_kit::net::LinkOptions::goose())?;
let result = goose_sniff(&path);
if live.write.is_none() {
let _ = std::fs::remove_file(&path);
}
result
}
(None, [file]) => goose_sniff(file_arg(file)?),
_ => Err(String::from("usage: ied goose sniff (<FILE.pcap> | --iface <IF> [--duration S] [--write FILE])")),
}
}
fn sv_monitor_cmd(args: &[&str]) -> Result<(), String> {
let (live, rest) = live_options(args)?;
if let Some(live) = live {
let path = capture_live(&live, iec61850_kit::net::LinkOptions::sv())?;
let result = sv_monitor(&path, &rest);
if live.write.is_none() {
let _ = std::fs::remove_file(&path);
}
return result;
}
let (file, options) = rest.split_first().ok_or("usage: ied sv monitor (<FILE.pcap> | --iface <IF>) [OPTIONS]")?;
sv_monitor(file_arg(file)?, options)
}
fn goose_publish(args: &[&str]) -> Result<(), String> {
use iec61850_kit::net::{Link, LinkOptions, drop_capabilities};
let (mut iface, mut scd, mut ied, mut gocb, mut values, mut duration) = (None, None, None, None, Vec::new(), Duration::from_secs(10));
let mut it = args.iter();
while let Some(arg) = it.next() {
let mut value = || it.next().copied().ok_or_else(|| format!("{arg} needs a value"));
match *arg {
"--iface" => iface = Some(value()?),
"--scd" => scd = Some(file_arg(value()?)?),
"--ied" => ied = Some(value()?),
"--gocb" => gocb = Some(value()?),
"--value" => values.push(value()?),
"--duration" => duration = Duration::from_secs_f64(value()?.parse().map_err(|_| "--duration needs seconds".to_string())?),
other => return Err(format!("unknown option `{other}`")),
}
}
let (Some(iface), Some(scd), Some(gocb)) = (iface, scd, gocb) else {
return Err(String::from("usage: ied goose publish --iface <IF> --scd <FILE> --gocb <LD/LN.name> [--value V]…"));
};
let xml = std::fs::read_to_string(scd).map_err(|e| format!("{scd}: {e}"))?;
let model = scl::Scl::parse(&xml).and_then(|s| s.model(ied)).map_err(|e| format!("{scd}: {e}"))?;
let served = Ied::new(model).map_err(|e| e.to_string())?;
let (ld_ln, name) = gocb.split_once('.').ok_or("--gocb is LD/LN.name, for example IED1LD0/LLN0.gcbTrip")?;
let block_ref = format!("{ld_ln}$GO${name}");
let block = served.block(&block_ref).ok_or_else(|| format!("{scd}: no GOOSE control block {gocb}"))?;
let members = block
.data_set
.as_deref()
.and_then(|ds| served.data_set(ds))
.map(iec61850_kit::server::ServedDataSet::references)
.ok_or("the control block has no data set")?;
if !values.is_empty() && values.len() != members.len() {
return Err(format!("{} --value given, the data set has {} members", values.len(), members.len()));
}
let mut data = Vec::with_capacity(members.len());
for (k, m) in members.iter().enumerate() {
let v = match values.get(k) {
Some(text) => served.parse_text(m, text).ok_or_else(|| format!("{m}: cannot read `{text}`"))?,
None => served.read_reference(m).ok_or_else(|| format!("{m}: no value"))?,
};
data.push(v);
}
let link = Link::open(iface, &LinkOptions::goose()).map_err(|e| format!("{iface}: {e}"))?;
drop_capabilities().map_err(|e| e.to_string())?;
let cfg = served.model.goose_publisher_config(gocb, link.mac()).map_err(|e| format!("{gocb}: {e}"))?;
let t = UtcTime::from_unix_nanos(unix_nanos(), TimeQuality::default());
let mut publisher = iec61850_kit::proto::goose::Publisher::new(cfg, &data, t).map_err(|e| e.to_string())?;
let start = iec61850_kit::common::monotonic_now();
let end = start.plus_nanos(duration.as_nanos().min(u128::from(u64::MAX)) as u64);
let mut sent = 0u64;
loop {
let now = iec61850_kit::common::monotonic_now();
if now >= end {
break;
}
publisher.on_timeout(now).map_err(|e| e.to_string())?;
if let Some(frame) = publisher.poll_transmit() {
link.send(frame).map_err(|e| e.to_string())?;
sent += 1;
}
let next = publisher.next_timeout().unwrap_or(end).min(end);
std::thread::sleep(Duration::from_nanos(next.nanos_since(iec61850_kit::common::monotonic_now())));
}
println!("{gocb}: {sent} frames on {iface}, stNum {} sqNum {}", publisher.st_num(), publisher.sq_num());
Ok(())
}
fn unix_nanos() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos().min(u128::from(u64::MAX)) as u64)
}
fn read(file: &str) -> Result<Capture, String> {
Capture::read(file).map_err(|e| format!("{file}: {e}"))
}
fn goose_sniff(file: &str) -> Result<(), String> {
let capture = read(file)?;
let mut keys: Vec<SubscriptionKey> = Vec::new();
for (_, frame) in &capture.frames {
let Ok(fr) = Frame::parse(frame) else { continue };
if fr.ethertype != ETHERTYPE_GOOSE {
continue;
}
let Ok(p) = GoosePduView::parse(fr.apdu) else { continue };
if !keys.iter().any(|k| k.dst == fr.dst && k.appid == fr.appid && k.gocb_ref == p.gocb_ref) {
keys.push(SubscriptionKey { dst: fr.dst, appid: fr.appid, gocb_ref: p.gocb_ref.to_string() });
}
}
let mut subs: Vec<GooseSubscriber> = keys.iter().map(|k| GooseSubscriber::new(SubscriberConfig::new(k.clone()))).collect();
let t0 = capture.frames.first().map_or(0, |(t, _)| *t);
let mut n = 0u64;
let mut malformed = 0u64;
for (ts, frame) in &capture.frames {
let Ok(fr) = Frame::parse(frame) else { continue };
if fr.ethertype != ETHERTYPE_GOOSE {
continue;
}
let at = (ts - t0) as f64 / 1e6;
let Ok(p) = GoosePduView::parse(fr.apdu) else {
malformed += 1;
println!("{at:>10.3}ms malformed GOOSE");
continue;
};
n += 1;
let flags =
[if p.simulation { "sim " } else { "" }, if p.nds_com { "ndsCom " } else { "" }, if p.member_count_matches() { "" } else { "COUNT-MISMATCH " }]
.concat();
println!(
"{at:>10.3}ms {} appid={:#06x} stNum={} sqNum={} tal={}ms conf={} members={} {}t={}",
p.gocb_ref, fr.appid, p.st_num, p.sq_num, p.time_allowed_to_live, p.conf_rev, p.num_dat_set_entries, flags, p.t
);
let Some(i) = keys.iter().position(|k| k.dst == fr.dst && k.appid == fr.appid && k.gocb_ref == p.gocb_ref) else { continue };
let Some(sub) = subs.get_mut(i) else { continue };
let now = Instant(ts - t0);
sub.on_frame(now, frame);
sub.on_timeout(now);
while let Some(e) = sub.poll_event() {
if !matches!(e, SubscriberEvent::NewState { .. } | SubscriberEvent::Retransmission { .. }) {
println!("{:>12} {e:?}", "!");
}
}
}
for (k, sub) in keys.iter().zip(&subs) {
let s = sub.stats();
println!("{} {} appid={:#06x}", k.dst, k.gocb_ref, k.appid);
println!(
" accepted={} states={} retransmissions={} replays={} expiries={} malformed={} member-count={} sim-mismatch={}",
s.accepted, s.state_changes, s.retransmissions, s.replays, s.expiries, s.malformed, s.member_count_mismatches, s.simulation_mismatches
);
if s.state_gaps > 0 {
println!(" state gaps={} ({} state changes never arrived)", s.state_gaps, s.states_missed);
}
if let Some(d) = sub.deltas() {
println!(
" last deltas: stDiff={} sqDiff={} arrival={:.3}ms t={:.3}ms sinceChange={:.3}ms",
d.st_diff,
d.sq_diff,
d.arrival_delta as f64 / 1e6,
d.t_delta as f64 / 1e6,
d.since_state_change as f64 / 1e6
);
}
}
println!("{n} GOOSE frames in {} stream(s){}", keys.len(), if malformed > 0 { format!(", {malformed} malformed") } else { String::new() });
Ok(())
}
fn mms_sniff(file: &str) -> Result<(), String> {
use iec61850_kit::proto::osi::cotp::Tpdu;
use iec61850_kit::proto::osi::presentation::Ppdu;
use iec61850_kit::proto::osi::session::Spdu;
use iec61850_kit::proto::osi::tpkt;
let capture = read(file)?;
let t0 = capture.frames.first().map_or(0, |(t, _)| *t);
let (mut to_server, mut to_client) = (tpkt::Reader::new(), tpkt::Reader::new());
let mut tally = MmsTally::default();
let mut printed = 0u32;
for (ts, frame) in &capture.frames {
let Some((to_srv, payload)) = tcp_payload(frame) else { continue };
let reader = if to_srv { &mut to_server } else { &mut to_client };
reader.push(payload);
loop {
let tpdu = match reader.next_tpdu() {
Ok(Some(t)) => t.to_vec(),
Ok(None) => break,
Err(e) => {
println!(" not a TPKT stream: {e}");
break;
}
};
let at = (ts - t0) as f64 / 1e6;
let arrow = if to_srv { "->" } else { "<-" };
let Ok(cotp) = Tpdu::parse(&tpdu) else {
tally.malformed += 1;
continue;
};
let payload = match cotp {
Tpdu::ConnectionRequest(c) => {
println!(
"{at:>10.3}ms {arrow} COTP CR src-ref={:#06x} tpdu-size={} tsel {:02x?}->{:02x?}",
c.src_ref,
c.max_data() + 3,
c.src_tsel.map(|t| t.0).unwrap_or_default(),
c.dst_tsel.map(|t| t.0).unwrap_or_default()
);
continue;
}
Tpdu::ConnectionConfirm(c) => {
println!("{at:>10.3}ms {arrow} COTP CC dst-ref={:#06x} tpdu-size={}", c.dst_ref, c.max_data() + 3);
continue;
}
Tpdu::Data { payload, .. } => payload,
other => {
println!("{at:>10.3}ms {arrow} COTP {other:?}");
continue;
}
};
let Ok(spdu) = Spdu::parse(payload) else {
tally.malformed += 1;
continue;
};
let (bytes, handshake) = match spdu {
Spdu::Connect(ref c) | Spdu::Accept(ref c) => (c.user_data, true),
Spdu::DataTransfer(p) => (p, false),
other => {
println!("{at:>10.3}ms {arrow} session {other:?}");
continue;
}
};
let Ok(ppdu) = Ppdu::parse(bytes, handshake) else {
tally.malformed += 1;
continue;
};
let pdvs = match &ppdu {
Ppdu::Reject(cp) => {
println!("{at:>10.3}ms {arrow} CPR presentation connection REFUSED, provider reason {:?}", cp.provider_reason);
cp.user_data.clone()
}
Ppdu::Connect(cp) | Ppdu::Accept(cp) => {
let what = if matches!(ppdu, Ppdu::Connect(_)) { "CP " } else { "CPA" };
let contexts: Vec<String> = cp.contexts.iter().map(|c| format!("{}={}", c.id, c.abstract_syntax)).collect();
if contexts.is_empty() {
println!("{at:>10.3}ms {arrow} {what} {} context result(s), all accepted: {}", cp.results.len(), cp.all_accepted());
} else {
println!("{at:>10.3}ms {arrow} {what} contexts {}", contexts.join(" "));
}
cp.user_data.clone()
}
Ppdu::UserData(p) => p.clone(),
};
for pdv in pdvs {
let Some(value) = pdv.values.single() else { continue };
print_pdv(at, arrow, pdv.context_id, value, &mut tally, &mut printed);
}
}
}
println!("{} request(s), {} response(s), {} report(s), {} value(s)", tally.requests, tally.responses, tally.reports, tally.values);
if tally.iec_reports > 0 || tally.terminations > 0 {
println!(" of those, {} IEC 61850 report(s) and {} command termination(s)", tally.iec_reports, tally.terminations);
}
if tally.malformed > 0 {
println!("{} PDU(s) did not decode", tally.malformed);
}
Ok(())
}
#[derive(Default)]
struct MmsTally {
requests: u64,
responses: u64,
reports: u64,
iec_reports: u64,
terminations: u64,
values: usize,
malformed: u64,
}
fn print_pdv(at: f64, arrow: &str, context_id: u16, value: &[u8], tally: &mut MmsTally, printed: &mut u32) {
use iec61850_kit::proto::mms::{ConfirmedResponse, Mms, ObjectName, Unconfirmed, VariableAccess};
use iec61850_kit::proto::osi::Oid;
use iec61850_kit::proto::osi::acse::Apdu;
let mms = if context_id == 1 {
match Apdu::parse(value) {
Ok(Apdu::Associate(a)) => {
let auth = if a.mechanism_name == Some(Oid::PASSWORD_MECHANISM) { " (ACSE password)" } else { "" };
println!("{at:>10.3}ms {arrow} AARQ context {}{auth}", a.context_name.map_or_else(String::new, |o| o.to_string()));
a.mms_pdu()
}
Ok(Apdu::AssociateResponse(a)) => {
println!("{at:>10.3}ms {arrow} AARE {}", if a.accepted() { "accepted" } else { "REJECTED" });
a.mms_pdu()
}
Ok(other) => {
println!("{at:>10.3}ms {arrow} ACSE {other:?}");
None
}
Err(_) => {
tally.malformed += 1;
None
}
}
} else {
Some(value)
};
let Some(bytes) = mms else { return };
let Ok(pdu) = Mms::parse(bytes, &Limits::DEFAULT) else {
tally.malformed += 1;
return;
};
let line = match &pdu {
Mms::InitiateRequest(i) | Mms::InitiateResponse(i) => format!(
"Initiate maxPDU={:?} outstanding {}/{} nesting {:?} version {}",
i.local_detail, i.max_serv_outstanding_calling, i.max_serv_outstanding_called, i.data_structure_nesting_level, i.version
),
Mms::ConfirmedRequest { invoke_id, service } => {
tally.requests += 1;
format!("invoke {invoke_id} {}", describe_request(service))
}
Mms::ConfirmedResponse { invoke_id, service } => {
tally.responses += 1;
if let ConfirmedResponse::Read { results, .. } = service {
tally.values += results.len();
}
format!("invoke {invoke_id} {}", describe_response(service))
}
Mms::ConfirmedError { invoke_id, .. } => format!("invoke {invoke_id} ERROR"),
Mms::Unconfirmed(Unconfirmed::InformationReport { access, results }) => {
tally.reports += 1;
tally.values += results.len();
let name = match access {
VariableAccess::VariableListName(ObjectName::DomainSpecific { domain, item }) => format!("{domain}/{item}"),
VariableAccess::VariableListName(n) => object_name(n),
VariableAccess::ListOfVariable(v) => format!("{} variable(s)", v.len()),
};
match Unsolicited::from_pdu(bytes, &Limits::DEFAULT) {
Some(Unsolicited::Report(r)) => {
tally.iec_reports += 1;
format!(
"report {} sq={} {} of {} members{}",
r.rpt_id,
r.seq_num.map_or_else(|| String::from("-"), |n| n.to_string()),
r.entries.len(),
r.data_set_len(),
if r.is_partial() { " (more segments follow)" } else { "" }
)
}
Some(Unsolicited::CommandTermination(t)) => {
tally.terminations += 1;
format!("command termination {} {}", if t.is_positive() { "+" } else { "-" }, t.control_object())
}
_ => format!("report {name} ({} values)", results.len()),
}
}
other => format!("{other:?}"),
};
if *printed < 20 || !matches!(pdu, Mms::Unconfirmed(_)) {
println!("{at:>10.3}ms {arrow} {line}");
*printed += 1;
}
}
fn describe_request(service: &iec61850_kit::proto::mms::ConfirmedRequest<'_>) -> String {
use iec61850_kit::proto::mms::{ConfirmedRequest, VariableAccess};
match service {
ConfirmedRequest::Identify => "identify".to_string(),
ConfirmedRequest::Status { extended_derivation } => format!("status{}", if *extended_derivation { " (extended derivation)" } else { "" }),
ConfirmedRequest::GetCapabilityList { .. } => String::from("getCapabilityList"),
ConfirmedRequest::GetNameList { object_class, .. } => format!("getNameList class {object_class}"),
ConfirmedRequest::Read { access, .. } => match access {
VariableAccess::VariableListName(n) => format!("read {}", object_name(n)),
VariableAccess::ListOfVariable(v) => {
format!("read {}", v.first().map_or_else(|| format!("{} variables", v.len()), |s| variable(s, v.len())))
}
},
ConfirmedRequest::Write { access, values } => match access {
VariableAccess::VariableListName(n) => format!("write {} ({} values)", object_name(n), values.len()),
VariableAccess::ListOfVariable(v) => format!("write {}", v.first().map_or_else(String::new, |s| variable(s, v.len()))),
},
ConfirmedRequest::GetNamedVariableListAttributes(n) => format!("getNamedVariableListAttributes {}", object_name(n)),
ConfirmedRequest::GetVariableAccessAttributes(n) => format!("getVariableAccessAttributes {}", object_name(n)),
ConfirmedRequest::DefineNamedVariableList { name, variables } => format!("defineNamedVariableList {} ({} members)", object_name(name), variables.len()),
ConfirmedRequest::DeleteNamedVariableList { names, .. } => format!("deleteNamedVariableList ({} name(s))", names.len()),
ConfirmedRequest::ReadJournal(r) => format!("readJournal {}", r.name.as_ref().map_or_else(String::new, object_name)),
ConfirmedRequest::FileOpen { name, position } => format!("fileOpen {} at {position}", name.display()),
ConfirmedRequest::FileRead(id) => format!("fileRead frsm {id}"),
ConfirmedRequest::FileClose(id) => format!("fileClose frsm {id}"),
ConfirmedRequest::FileDelete(name) => format!("fileDelete {}", name.display()),
ConfirmedRequest::ObtainFile { source, destination, .. } => format!("obtainFile {} -> {}", source.display(), destination.display()),
ConfirmedRequest::FileDirectory { specification, .. } => {
format!("fileDirectory {}", specification.as_ref().map_or_else(|| String::from("*"), file::FileName::display))
}
ConfirmedRequest::Other(t) => format!("service [{}]", t.tag.number),
}
}
fn describe_response(service: &iec61850_kit::proto::mms::ConfirmedResponse<'_>) -> String {
use iec61850_kit::proto::mms::ConfirmedResponse;
match service {
ConfirmedResponse::Identify { vendor, model, revision } => format!("identify {vendor} {model} {revision}"),
ConfirmedResponse::Status { logical, physical, .. } => format!("status logical={logical} physical={physical}"),
ConfirmedResponse::GetCapabilityList { capabilities, more_follows } => {
format!("getCapabilityList {} capabilit(y|ies){}", capabilities.len(), if *more_follows { ", more follow" } else { "" })
}
ConfirmedResponse::GetNameList { identifiers, more_follows } => {
format!("getNameList {} name(s){}", identifiers.len(), if *more_follows { ", more follow" } else { "" })
}
ConfirmedResponse::Read { results, .. } => format!("read {} value(s)", results.len()),
ConfirmedResponse::Write(results) => format!("write {} result(s)", results.len()),
ConfirmedResponse::GetNamedVariableListAttributes { variables, .. } => format!("data set of {} member(s)", variables.len()),
ConfirmedResponse::GetVariableAccessAttributes { type_spec, .. } => format!("type {}", describe_type(type_spec)),
ConfirmedResponse::DefineNamedVariableList => String::from("data set created"),
ConfirmedResponse::DeleteNamedVariableList { matched, deleted } => format!("deleted {deleted} of {matched} matched"),
ConfirmedResponse::ReadJournal { entries, more_follows } => {
format!("{} log entr(y|ies){}", entries.len(), if *more_follows { ", more follow" } else { "" })
}
ConfirmedResponse::FileOpen { frsm_id, attributes } => format!("fileOpen frsm {frsm_id}, {} octets", attributes.size),
ConfirmedResponse::FileRead { data, more_follows } => format!("{} octets{}", data.len(), if *more_follows { ", more follow" } else { "" }),
ConfirmedResponse::FileClose => String::from("fileClose"),
ConfirmedResponse::FileDelete => String::from("fileDelete"),
ConfirmedResponse::ObtainFile => String::from("obtainFile"),
ConfirmedResponse::FileDirectory { entries, more_follows } => {
format!("{} file(s){}", entries.len(), if *more_follows { ", more follow" } else { "" })
}
ConfirmedResponse::Other(t) => format!("service [{}]", t.tag.number),
}
}
fn describe_type(t: &TypeSpec) -> String {
match t {
TypeSpec::Structure { components, .. } => {
format!("struct {{{}}}", components.iter().map(|c| c.name.clone().unwrap_or_default()).collect::<Vec<_>>().join(", "))
}
TypeSpec::Array { elements, element_type, .. } => format!("array[{elements}] of {}", describe_type(element_type)),
TypeSpec::Boolean => String::from("BOOLEAN"),
TypeSpec::BitString(n) => format!("BIT STRING({n})"),
TypeSpec::Integer(w) => format!("INT{w}"),
TypeSpec::Unsigned(w) => format!("INT{w}U"),
TypeSpec::FloatingPoint { format_width, .. } => format!("FLOAT{format_width}"),
TypeSpec::OctetString(n) => format!("OCTET STRING({n})"),
TypeSpec::VisibleString(n) => format!("VisString({n})"),
TypeSpec::MmsString(n) => format!("MMSString({n})"),
TypeSpec::UtcTime => String::from("Timestamp"),
TypeSpec::BinaryTime(dated) => String::from(if *dated { "EntryTime" } else { "TimeOfDay" }),
TypeSpec::GeneralizedTime => String::from("GeneralizedTime"),
TypeSpec::Bcd(n) => format!("BCD({n})"),
TypeSpec::Named { domain, item } => domain.as_ref().map_or_else(|| item.clone(), |d| format!("{d}/{item}")),
other => format!("{other:?}"),
}
}
fn object_name(n: &iec61850_kit::proto::mms::ObjectName<'_>) -> String {
use iec61850_kit::proto::mms::ObjectName;
match n {
ObjectName::DomainSpecific { domain, item } => format!("{domain}/{item}"),
ObjectName::VmdSpecific(s) | ObjectName::AaSpecific(s) => (*s).to_string(),
}
}
fn variable(s: &iec61850_kit::proto::mms::VariableSpecification<'_>, total: usize) -> String {
use iec61850_kit::proto::mms::VariableSpecification;
let more = if total > 1 { format!(" (+{} more)", total - 1) } else { String::new() };
match s {
VariableSpecification::Name(n) => format!("{}{more}", object_name(n)),
VariableSpecification::Element { name, access } => format!("{}{access}{more}", object_name(name)),
VariableSpecification::Other(_) => format!("{total} variable(s)"),
}
}
fn tcp_payload(frame: &[u8]) -> Option<(bool, &[u8])> {
if frame.len() < 34 || u16::from_be_bytes([*frame.get(12)?, *frame.get(13)?]) != 0x0800 || *frame.get(23)? != 6 {
return None;
}
let ip_end = 14 + usize::from(u16::from_be_bytes([*frame.get(16)?, *frame.get(17)?]));
let tcp = 14 + usize::from(frame.get(14)? & 0x0F) * 4;
let data_off = usize::from(frame.get(tcp + 12)? >> 4) * 4;
let payload = frame.get(tcp + data_off..ip_end.min(frame.len()))?;
if payload.is_empty() {
return None;
}
let dst_port = u16::from_be_bytes([*frame.get(tcp + 2)?, *frame.get(tcp + 3)?]);
Some((dst_port == 102, payload))
}
fn mms_type(host: &str, reference: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let mut c = mms_connect(host, &o)?;
let spec = c.variable_type(reference, o.fc).map_err(|e| format!("{reference}: {e}"))?;
print_type(&spec, 0);
let _ = c.release();
Ok(())
}
fn print_type(spec: &TypeSpec, depth: usize) {
let pad = " ".repeat(depth);
match spec {
TypeSpec::Structure { components, .. } => {
println!("{pad}struct");
for c in components {
let name = c.name.as_deref().unwrap_or("(unnamed)");
match &c.type_spec {
TypeSpec::Structure { .. } | TypeSpec::Array { .. } => {
println!("{pad} {name}");
print_type(&c.type_spec, depth + 2);
}
other => println!("{pad} {name:<12} {}", describe_type(other)),
}
}
}
TypeSpec::Array { elements, element_type, .. } => {
println!("{pad}array[{elements}]");
print_type(element_type, depth + 1);
}
other => println!("{pad}{}", describe_type(other)),
}
}
fn mms_files(host: &str, args: &[&str]) -> Result<(), String> {
let (dir, rest) = split_leading(args);
let o = mms_options(rest)?;
let mut c = mms_connect(host, &o)?;
let files = c.file_directory(dir).map_err(|e| e.to_string())?;
for f in &files {
println!("{:>12} {} {}", f.size, f.last_modified.as_deref().unwrap_or(" "), f.name);
}
println!("{} file(s)", files.len());
let _ = c.release();
Ok(())
}
fn mms_get(host: &str, path: &str, args: &[&str]) -> Result<(), String> {
let (out, rest) = split_leading(args);
let o = mms_options(rest)?;
let mut c = mms_connect(host, &o)?;
let data = c.read_file(path, o.max_size).map_err(|e| format!("{path}: {e}"))?;
if let Some(file) = out {
std::fs::write(file, &data).map_err(|e| format!("{file}: {e}"))?;
println!("{} octets -> {file}", data.len());
} else {
use std::io::Write as _;
std::io::stdout().write_all(&data).map_err(|e| e.to_string())?;
}
let _ = c.release();
Ok(())
}
fn mms_put(host: &str, local: &str, remote: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let mut c = mms_connect(host, &o)?;
c.set_file_path(std::path::Path::new(local), remote).map_err(|e| format!("{remote}: {e}"))?;
let size = std::fs::metadata(local).map_or(0, |m| m.len());
println!("{local} -> {remote} ({size} octets)");
let _ = c.release();
Ok(())
}
fn mms_log(host: &str, log: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let mut c = mms_connect(host, &o)?;
let mut from = EntryTime::default();
if let Some(reference) = &o.lcb {
let lcb = c.read_lcb(reference, Fc::LG).map_err(|e| format!("{reference}: {e}"))?;
println!("{} {}", lcb.reference, if lcb.log_ena { "enabled" } else { "disabled" });
println!(" LogRef {}", lcb.log_ref.as_deref().unwrap_or("(none)"));
println!(" DatSet {}", lcb.data_set.as_deref().unwrap_or("(none)"));
println!(" TrgOps {}", describe_trg_ops(lcb.trg_ops));
if let Some((_, oldest)) = lcb.oldest() {
println!(" oldest {oldest}");
from = oldest;
}
if let Some(newest) = lcb.new_entry_time {
println!(" newest {newest}");
}
}
let entries = c.read_whole_log(log, from, o.entries).map_err(|e| format!("{log}: {e}"))?;
for e in &entries {
let mut id = String::with_capacity(e.entry_id.len() * 2);
for b in &e.entry_id {
let _ = write!(id, "{b:02x}");
}
if let Some(text) = &e.annotation {
println!("{} {id} {text}", e.occurred);
} else {
match e.reason {
Some(reason) => println!("{} {id} {reason:?}", e.occurred),
None => println!("{} {id}", e.occurred),
}
for (name, value) in &e.variables {
println!(" {name} = {}", show_value(value));
}
}
}
println!("{} entr(y|ies)", entries.len());
let _ = c.release();
Ok(())
}
fn mms_setting_groups(host: &str, args: &[&str]) -> Result<(), String> {
let (reference, rest) = split_leading(args);
let o = mms_options(rest)?;
let mut c = mms_connect(host, &o)?;
let reference = if let Some(r) = reference {
String::from(r)
} else {
let ld = c.server_directory().map_err(|e| e.to_string())?;
let first = ld.first().ok_or_else(|| String::from("the server has no logical device"))?;
format!("{first}/LLN0$SP$SGCB")
};
if let Some(group) = o.edit {
c.select_edit_setting_group(&reference, group).map_err(|e| format!("{reference}: {e}"))?;
println!("editing group {group}");
}
if let Some(group) = o.activate {
c.select_active_setting_group(&reference, group).map_err(|e| format!("{reference}: {e}"))?;
println!("group {group} activated");
}
let sgcb = c.read_sgcb(&reference).map_err(|e| format!("{reference}: {e}"))?;
println!("{}", sgcb.reference);
println!(" NumOfSG {}", sgcb.num_of_sg.map_or_else(|| String::from("-"), |n| n.to_string()));
println!(" ActSG {}", sgcb.act_sg.map_or_else(|| String::from("-"), |n| n.to_string()));
println!(" EditSG {}", sgcb.edit_sg.map_or_else(|| String::from("-"), |n| n.to_string()));
println!(" CnfEdit {}", sgcb.cnf_edit.map_or_else(|| String::from("-"), |b| b.to_string()));
if let Some(t) = sgcb.last_activation {
println!(" LActTm {t}");
}
let _ = c.release();
Ok(())
}
fn simulate(file: &str, args: &[&str]) -> Result<(), String> {
let mut o = SimOptions::default();
let mut it = args.iter();
while let Some(arg) = it.next() {
let mut value = || it.next().copied().ok_or_else(|| format!("{arg} needs a value"));
match *arg {
"--ied" => o.ied = Some(value()?.to_string()),
"--bind" => o.bind = value()?.to_string(),
"--port" => o.port = value()?.parse().map_err(|_| "--port needs a number".to_string())?,
"--files" => o.files = Some(value()?.to_string()),
"--writable" => o.writable = true,
"--edition" => o.edition = Some(parse_edition(value()?)?),
"--log-db" => o.log_db = Some(value()?.to_string()),
"--password" => o.password = Some(value()?.to_string()),
"--iface" => o.iface = Some(value()?.to_string()),
"--freq" => o.freq = value()?.parse().map_err(|_| "--freq needs a number".to_string())?,
other => return Err(format!("unknown option `{other}`")),
}
}
let xml = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
let scl = scl::Scl::parse(&xml).map_err(|e| format!("{file}: {e}"))?;
let names: Vec<String> = match &o.ied {
Some(name) => vec![name.clone()],
None => scl.ied_names(),
};
if names.is_empty() {
return Err(format!("{file}: no IED to serve"));
}
if let Some(dir) = &o.files {
guard_files_root(dir, file, o.log_db.as_deref())?;
}
let mut servers = Vec::new();
for (n, name) in names.iter().enumerate() {
let model = scl.model(Some(name)).map_err(|e| format!("{name}: {e}"))?;
for d in &model.diagnostics {
eprintln!("ied: {name}: {d}");
}
let ied = match o.edition {
Some(e) => Ied::with_edition(model, e),
None => Ied::new(model),
}
.map_err(|e| format!("{name}: {e}"))?;
let edition = ied.edition();
let devices = ied.domain_names();
let trackers = iec61850_kit::server::Tracking::new(&ied).references();
let port = u16::try_from(n).ok().and_then(|n| o.port.checked_add(n)).ok_or_else(|| format!("{} IEDs do not fit above port {}", names.len(), o.port))?;
let server = sim_server(&o, file, name, names.len(), port, ied)?;
let addr = server.local_addr().map_err(|e| e.to_string())?;
println!("{name} on {addr} — {} — logical device(s) {}", edition_name(edition), devices.join(", "));
if !trackers.is_empty() {
println!(" service tracking: {}", trackers.join(", "));
}
servers.push(server);
}
if let Some(dir) = &o.files {
let mode = match (o.writable, o.password.is_some()) {
(false, _) => " (read-only)",
(true, false) => " (writable: delete and SetFile by any client)",
(true, true) => " (writable: delete and SetFile by password-authenticated clients)",
};
println!("files from {dir}{mode}");
}
if let Some(iface) = &o.iface {
iec61850_kit::net::drop_capabilities().map_err(|e| e.to_string())?;
println!("GOOSE and sampled values a client enables go out on {iface}");
}
println!("serving; ^C to stop");
let mut handles = Vec::new();
let mut watched = Vec::new();
for server in servers {
if o.iface.is_some() {
watched.push(server.handle());
}
handles.push(std::thread::spawn(move || server.run()));
}
if !watched.is_empty() {
std::thread::spawn(move || report_dropped_frames(&watched));
}
for h in handles {
if let Ok(Err(e)) = h.join() {
return Err(e.to_string());
}
}
Ok(())
}
fn report_dropped_frames(servers: &[iec61850_kit::server::ServerHandle]) {
let mut reported = 0u64;
loop {
std::thread::sleep(Duration::from_secs(10));
let dropped: u64 = servers.iter().map(iec61850_kit::server::ServerHandle::frames_dropped).sum();
if dropped > reported {
eprintln!("ied: {dropped} GOOSE/SV frame(s) dropped so far: the publisher could not keep up");
reported = dropped;
}
}
}
fn sim_server(o: &SimOptions, file: &str, name: &str, ieds: usize, port: u16, ied: Ied) -> Result<Server, String> {
let mut cfg = iec61850_kit::server::ServerConfig::default();
cfg.association.password.clone_from(&o.password);
if o.writable && o.files.is_some() {
cfg.acsi.file_write =
if o.password.is_some() { iec61850_kit::server::FileWritePolicy::Authenticated } else { iec61850_kit::server::FileWritePolicy::Anyone };
}
let mut server = Server::bind_with(&format!("{}:{port}", o.bind), ied, &cfg).map_err(|e| format!("{name}: {e}"))?;
if let Some(dir) = &o.files {
let mut store = DirectoryStore::new(dir).hiding(file);
if let Some(log) = &o.log_db {
store = store.hiding(log);
}
server.set_file_store(Box::new(if o.writable { store.writable() } else { store }));
}
if let Some(path) = &o.log_db {
let path = if ieds == 1 {
std::path::PathBuf::from(path)
} else {
std::fs::create_dir_all(path).map_err(|e| format!("{path}: {e}"))?;
std::path::Path::new(path).join(format!("{name}.redb"))
};
let store = iec61850_kit::server::RedbLog::open(&path, server.log_references(), iec61850_kit::server::DEFAULT_LOG_CAPACITY)
.map_err(|e| format!("{name}: {e}"))?;
println!(" log in {}", path.display());
server.set_log_store(Box::new(store));
}
server.set_nominal_hz(o.freq);
if let Some(iface) = &o.iface {
let link = iec61850_kit::net::Link::open(iface, &iec61850_kit::net::LinkOptions::process_bus()).map_err(|e| format!("{iface}: {e}"))?;
server.publish_on(link).map_err(|e| format!("{name}: {e}"))?;
}
Ok(server)
}
fn guard_files_root(dir: &str, scl_file: &str, log_db: Option<&str>) -> Result<(), String> {
let canonical = |p: &str| {
let path = std::path::Path::new(p);
path.canonicalize().ok().or_else(|| {
let parent = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| std::path::Path::new("."));
parent.canonicalize().ok().map(|d| d.join(path.file_name().unwrap_or_default()))
})
};
let root = canonical(dir).ok_or_else(|| format!("{dir}: no such directory"))?;
let mut guarded = vec![("the SCL file", scl_file)];
if let Some(log) = log_db {
guarded.push(("the log (--log-db)", log));
}
for (what, path) in guarded {
let Some(real) = canonical(path) else { continue };
if real.starts_with(&root) || root.starts_with(&real) {
return Err(format!("--files {dir} would expose {what} {path}: serve a directory that holds neither"));
}
}
Ok(())
}
#[derive(Debug)]
struct SimOptions {
ied: Option<String>,
bind: String,
port: u16,
files: Option<String>,
writable: bool,
edition: Option<Edition>,
log_db: Option<String>,
password: Option<String>,
iface: Option<String>,
freq: u32,
}
impl Default for SimOptions {
fn default() -> SimOptions {
SimOptions {
ied: None,
bind: String::from("127.0.0.1"),
port: 102,
files: None,
writable: false,
edition: None,
log_db: None,
password: None,
iface: None,
freq: 50,
}
}
}
fn split_leading<'a>(args: &'a [&'a str]) -> (Option<&'a str>, &'a [&'a str]) {
if let Some((first, rest)) = args.split_first()
&& !first.starts_with("--")
{
return (Some(*first), rest);
}
(None, args)
}
fn sv_monitor(file: &str, args: &[&str]) -> Result<(), String> {
let mut freq = 50u32;
let mut rate: Option<u32> = None;
let mut scd: Option<&str> = None;
let mut ied: Option<&str> = None;
let mut it = args.iter();
while let Some(arg) = it.next() {
let mut value = || it.next().copied().ok_or_else(|| format!("{arg} needs a value"));
match *arg {
"--freq" => freq = value()?.parse().map_err(|_| "--freq needs a number".to_string())?,
"--rate" => rate = Some(value()?.parse().map_err(|_| "--rate needs a number".to_string())?),
"--scd" => scd = Some(value()?),
"--ied" => ied = Some(value()?),
other => return Err(format!("unknown option `{other}`")),
}
}
if ied.is_some() && scd.is_none() {
return Err(String::from("--ied only means something with --scd"));
}
if let Some(path) = scd {
return sv_monitor_from_scl(file, path, ied, freq);
}
let capture = read(file)?;
let found = discover_streams(&capture);
if found.is_empty() {
println!("no sampled values in {file}");
return Ok(());
}
let configs: Vec<StreamConfig> = found
.iter()
.map(|d| {
let per_second = rate.unwrap_or_else(|| d.samples_per_second(freq));
StreamConfig::new(d.key.clone()).with_samples_per_second(per_second).with_stale_after_ms(1000)
})
.collect();
let wraps: Vec<(u32, &str)> = configs
.iter()
.zip(&found)
.map(|(c, d)| {
(
c.samples_per_second,
if rate.is_some() {
"given"
} else if c.samples_per_second == u32::from(d.max_smp_cnt) + 1 && d.smp_rate.is_none() {
"observed"
} else {
"smpRate"
},
)
})
.collect();
let mut sub = iec61850_kit::proto::sv::Subscriber::new(configs).with_event_capacity(4096);
let t0 = capture.frames.first().map_or(0, |(t, _)| *t);
let mut events: Vec<String> = Vec::new();
for (ts, frame) in &capture.frames {
let now = Instant(ts.saturating_sub(t0));
sub.on_frame(now, frame, |_| {});
while let Some(e) = sub.poll_event() {
if events.len() < 20 {
events.push(format!(" {:>10.3}ms {e:?}", (ts - t0) as f64 / 1e6));
}
}
}
for (i, d) in found.iter().enumerate() {
let Some(st) = sub.state(i) else { continue };
let per_frame = st.asdus.checked_div(st.frames).unwrap_or(0);
let (wrap, source) = wraps.get(i).copied().unwrap_or((0, "?"));
println!("svID={} appid={:#06x} dst={} confRev={} smpCnt wraps at {wrap} ({source})", d.key.sv_id, d.key.appid, d.key.dst, d.conf_rev);
println!(
" frames={} asdus={} ({per_frame}/frame) last smpCnt={:?} smpSynch={:?} gaps={} samples lost={}",
st.frames, st.asdus, st.last_smp_cnt, st.smp_synch, st.gaps, st.samples_lost
);
if let Some(gm) = st.gm_identity {
println!(" grandmaster={}", gm.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().concat());
}
}
if !events.is_empty() {
println!("events:");
for e in &events {
println!("{e}");
}
}
if sub.malformed() > 0 {
println!("{} malformed frames", sub.malformed());
}
if sub.events_dropped() > 0 {
println!("{} further events not shown", sub.events_dropped());
}
Ok(())
}
fn sv_monitor_from_scl(capture_file: &str, scl_file: &str, ied: Option<&str>, freq: u32) -> Result<(), String> {
let xml = std::fs::read_to_string(scl_file).map_err(|e| format!("{scl_file}: {e}"))?;
let scl = scl::Scl::parse(&xml).map_err(|e| e.to_string())?;
let names: Vec<String> = match ied {
Some(n) => vec![n.to_string()],
None => scl.ied_names(),
};
let mut labels: Vec<String> = Vec::new();
let mut configs: Vec<StreamConfig> = Vec::new();
for name in &names {
let model = scl.model(Some(name)).map_err(|e| format!("{name}: {e}"))?;
for ld in &model.logical_devices {
for ln in &ld.logical_nodes {
for cb in &ln.smv_controls {
let reference = format!("{}/{}.{}", ld.name, ln.name, cb.name);
match model.sv_stream_config(&reference, freq) {
Ok(cfg) => {
labels.push(format!("{name} {reference}"));
configs.push(cfg.with_stale_after_ms(1000));
}
Err(e) => println!("skipping {reference}: {e}"),
}
}
}
}
}
if configs.is_empty() {
return Err(format!("{scl_file} configures no addressed sampled-value stream"));
}
let capture = read(capture_file)?;
let n = configs.len();
let mut sub = iec61850_kit::proto::sv::Subscriber::new(configs).with_event_capacity(4096);
let mut last: Vec<(u16, Vec<u8>)> = vec![(0, Vec::new()); n];
let t0 = capture.frames.first().map_or(0, |(t, _)| *t);
let mut events: Vec<String> = Vec::new();
for (ts, frame) in &capture.frames {
let now = Instant(ts.saturating_sub(t0));
sub.on_frame(now, frame, |s| {
if let Some(slot) = last.get_mut(s.stream) {
slot.0 = s.asdu.smp_cnt;
slot.1.clear();
slot.1.extend_from_slice(s.asdu.sample);
}
});
while let Some(e) = sub.poll_event() {
if events.len() < 20 {
events.push(format!(" {:>10.3}ms {e:?}", (ts - t0) as f64 / 1e6));
}
}
}
for i in 0..n {
let (Some(cfg), Some(st), Some(label)) = (sub.stream_config(i), sub.state(i), labels.get(i)) else { continue };
println!("{label}");
println!(
" svID={} appid={:#06x} dst={} smpCnt wraps at {} frames={} asdus={} gaps={} samples lost={}",
cfg.key.sv_id, cfg.key.appid, cfg.key.dst, cfg.samples_per_second, st.frames, st.asdus, st.gaps, st.samples_lost
);
let Some(layout) = cfg.layout.as_ref() else {
println!(" no fixed-width data set in the file: samples stay octets");
continue;
};
println!(" {} channels, {} octets per ASDU", layout.channels().len(), layout.len());
let Some((cnt, sample)) = last.get(i).filter(|(_, s)| !s.is_empty()) else {
println!(" no sample of this stream in the capture");
continue;
};
println!(" last sample (smpCnt={cnt}):");
for (c, v) in layout.decode(sample) {
println!(" {:<40} {}", c.name, show(v));
}
}
if !events.is_empty() {
println!("events:");
for e in &events {
println!("{e}");
}
}
if sub.malformed() > 0 {
println!("{} malformed frames", sub.malformed());
}
Ok(())
}
fn show(v: ChannelValue) -> String {
match v {
ChannelValue::Boolean(b) => b.to_string(),
ChannelValue::Int(i) => i.to_string(),
ChannelValue::Unsigned(u) => u.to_string(),
ChannelValue::Float(f) => format!("{f}"),
ChannelValue::Quality(q) => {
if q.is_good() {
String::from("good")
} else {
format!("{q:?}")
}
}
ChannelValue::Timestamp(t) => t.to_string(),
other => format!("{other:?}"),
}
}
fn discover_streams(capture: &Capture) -> Vec<Discovered> {
let mut found: Vec<Discovered> = Vec::new();
for (_, frame) in &capture.frames {
let Ok(fr) = Frame::parse(frame) else { continue };
if fr.ethertype != ETHERTYPE_SV {
continue;
}
let Ok(pdu) = SavPduView::parse(fr.apdu, &Limits::DEFAULT) else { continue };
for a in pdu.asdus().flatten() {
match found.iter_mut().find(|d| d.key.dst == fr.dst && d.key.appid == fr.appid && d.key.sv_id == a.sv_id) {
Some(d) => d.max_smp_cnt = d.max_smp_cnt.max(a.smp_cnt),
None => found.push(Discovered {
key: StreamKey { dst: fr.dst, appid: fr.appid, sv_id: a.sv_id.to_string() },
smp_rate: a.smp_rate,
smp_mod: a.smp_mod,
conf_rev: a.conf_rev,
max_smp_cnt: a.smp_cnt,
}),
}
}
}
found
}
struct Discovered {
key: StreamKey,
smp_rate: Option<u16>,
smp_mod: Option<u8>,
conf_rev: u32,
max_smp_cnt: u16,
}
impl Discovered {
fn samples_per_second(&self, freq: u32) -> u32 {
let observed = || u32::from(self.max_smp_cnt) + 1;
match (self.smp_rate, self.smp_mod.and_then(SmpMod::from_u8)) {
(Some(r), Some(SmpMod::SamplesPerSecond)) if r != 0 => u32::from(r),
(Some(1), Some(SmpMod::SecondsPerSample)) => 1,
(Some(r), None | Some(SmpMod::SamplesPerPeriod)) if r != 0 => u32::from(r) * freq,
_ => observed(),
}
}
}
fn pcap_info(file: &str) -> Result<(), String> {
let capture = read(file)?;
let (mut goose, mut sv, mut other, mut tagged) = (0u64, 0u64, 0u64, 0u64);
let mut gse_mgmt = 0u64;
let mut span = (u64::MAX, 0u64);
for (ts, frame) in &capture.frames {
span = (span.0.min(*ts), span.1.max(*ts));
match Frame::parse(frame) {
Ok(fr) => {
if fr.vlan.is_some() {
tagged += 1;
}
match fr.ethertype {
ETHERTYPE_GOOSE => goose += 1,
ETHERTYPE_SV => sv += 1,
ETHERTYPE_GSE_MGMT => gse_mgmt += 1,
_ => other += 1,
}
}
Err(_) => other += 1,
}
}
let seconds = if capture.frames.is_empty() { 0.0 } else { (span.1 - span.0) as f64 / 1e9 };
println!("{file}: {} frames over {seconds:.3} s", capture.frames.len());
println!(" GOOSE {goose}, sampled values {sv}, other {other}, VLAN-tagged {tagged}");
if gse_mgmt > 0 {
println!(" GSE management (IEC 61850-8-1 Ed1, deprecated) {gse_mgmt}");
}
if seconds > 0.0 {
println!(" {:.0} process-bus frames per second", (goose + sv) as f64 / seconds);
}
Ok(())
}
struct MmsOptions {
fc: Fc,
fc_given: bool,
password: Option<String>,
value_type: String,
timeout: Duration,
seconds: u64,
local_tsel: Option<Vec<u8>>,
remote_tsel: Option<Vec<u8>>,
rcb: Option<String>,
buffered: bool,
data_set: Option<String>,
intg_pd: Option<u32>,
gi: bool,
model: Option<ControlModel>,
orcat: OriginCategory,
scd: Option<String>,
ied: Option<String>,
orident: String,
synchro: bool,
interlock: bool,
test: bool,
max_size: usize,
activate: Option<u32>,
edit: Option<u32>,
lcb: Option<String>,
entries: usize,
first_price: Option<String>,
start_object: Option<String>,
}
impl Default for MmsOptions {
fn default() -> MmsOptions {
MmsOptions {
fc: Fc::ST,
fc_given: false,
password: None,
value_type: String::from("bool"),
timeout: Duration::from_secs(30),
seconds: 30,
local_tsel: None,
remote_tsel: None,
rcb: None,
buffered: false,
data_set: None,
intg_pd: None,
gi: false,
model: None,
orcat: OriginCategory::RemoteControl,
scd: None,
ied: None,
orident: String::from("ied"),
synchro: false,
interlock: false,
test: false,
max_size: 16 * 1024 * 1024,
activate: None,
edit: None,
lcb: None,
entries: 1000,
first_price: None,
start_object: None,
}
}
}
fn mms_options(args: &[&str]) -> Result<MmsOptions, String> {
let mut o = MmsOptions::default();
let mut it = args.iter();
while let Some(arg) = it.next() {
let mut value = || it.next().copied().ok_or_else(|| format!("{arg} needs a value"));
match *arg {
"--fc" => {
let v = value()?;
o.fc = Fc::parse(&v.to_ascii_uppercase()).ok_or_else(|| format!("unknown functional constraint `{v}`"))?;
o.fc_given = true;
}
"--password" => o.password = Some(value()?.to_string()),
"--type" => o.value_type = value()?.to_ascii_lowercase(),
"--timeout" => o.timeout = Duration::from_secs(value()?.parse().map_err(|_| "--timeout needs seconds".to_string())?),
"--seconds" => o.seconds = value()?.parse().map_err(|_| "--seconds needs a number".to_string())?,
"--local-tsel" => o.local_tsel = Some(parse_hex(value()?)?),
"--remote-tsel" => o.remote_tsel = Some(parse_hex(value()?)?),
"--rcb" => o.rcb = Some(value()?.to_string()),
"--buffered" => o.buffered = true,
"--data-set" => o.data_set = Some(value()?.to_string()),
"--intg-pd" => o.intg_pd = Some(value()?.parse().map_err(|_| "--intg-pd needs milliseconds".to_string())?),
"--gi" => o.gi = true,
"--model" => {
o.model = Some(match value()? {
"direct" | "direct-normal" | "1" => ControlModel::DirectNormal,
"sbo" | "sbo-normal" | "2" => ControlModel::SboNormal,
"direct-enhanced" | "3" => ControlModel::DirectEnhanced,
"sbo-enhanced" | "4" => ControlModel::SboEnhanced,
other => return Err(format!("unknown control model `{other}`; use direct, sbo, direct-enhanced or sbo-enhanced")),
});
}
"--orcat" => {
let v = value()?;
o.orcat = OriginCategory::from_code(v.parse().map_err(|_| format!("--orcat needs a number, not `{v}`"))?);
}
"--orident" => o.orident = value()?.to_string(),
"--synchro" => o.synchro = true,
"--interlock" => o.interlock = true,
"--test" => o.test = true,
"--max-size" => o.max_size = value()?.parse().map_err(|_| "--max-size needs a number of bytes".to_string())?,
"--activate" => o.activate = Some(value()?.parse().map_err(|_| "--activate needs a group number".to_string())?),
"--edit" => o.edit = Some(value()?.parse().map_err(|_| "--edit needs a group number".to_string())?),
"--lcb" => o.lcb = Some(value()?.to_string()),
"--first-price" => o.first_price = Some(value()?.to_owned()),
"--start-object" => o.start_object = Some(value()?.to_owned()),
"--entries" => o.entries = value()?.parse().map_err(|_| "--entries needs a number".to_string())?,
"--scd" => o.scd = Some(value()?.to_string()),
"--ied" => o.ied = Some(value()?.to_string()),
other => return Err(format!("unknown option `{other}`")),
}
}
Ok(o)
}
fn parse_hex(s: &str) -> Result<Vec<u8>, String> {
let s = s.trim_start_matches("0x");
if !s.len().is_multiple_of(2) || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(format!("`{s}` is not an even number of hex digits"));
}
(0..s.len() / 2).map(|i| u8::from_str_radix(s.get(i * 2..i * 2 + 2).unwrap_or(""), 16).map_err(|e| e.to_string())).collect()
}
fn mms_connect(host: &str, o: &MmsOptions) -> Result<Client, String> {
let mut cfg = match (&o.scd, &o.ied) {
(Some(path), Some(ied)) => {
let xml = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
let scl = scl::Scl::parse(&xml).map_err(|e| format!("{path}: {e}"))?;
let (cfg, ip) = ClientConfig::from_scl(&scl, ied, None).map_err(|e| format!("{path}: {ied}: {e}"))?;
if host == "-" {
let ip = ip.ok_or_else(|| format!("{path}: {ied} has no IP address in the file"))?;
return connect_with(&ip, cfg, o);
}
cfg
}
(Some(_), None) | (None, Some(_)) => return Err("--scd and --ied go together".to_string()),
(None, None) => ClientConfig::default(),
};
if host == "-" {
return Err("a host of `-` needs --scd and --ied to say where to connect".to_string());
}
if let Some(t) = &o.local_tsel {
cfg.association.local.t_sel.clone_from(t);
}
if let Some(t) = &o.remote_tsel {
cfg.association.remote.t_sel.clone_from(t);
}
connect_with(host, cfg, o)
}
fn connect_with(host: &str, mut cfg: ClientConfig, o: &MmsOptions) -> Result<Client, String> {
cfg.association.password.clone_from(&o.password);
cfg.association.request_timeout_ms = o.timeout.as_millis() as u64;
cfg.connect_timeout = o.timeout;
Client::connect_with(host, &cfg).map_err(|e| format!("{host}: {e}"))
}
fn mms_tariff(host: &str, node: &str, start: &str, end: &str, unit: &str, args: &[&str]) -> Result<(), String> {
use iec61850_kit::client::TariffProfile;
let o = mms_options(args)?;
let timestamp = |s: &str| s.parse::<u32>().map_err(|_| format!("expected UTC Unix seconds, got {s}"));
let window = timestamp(start)?..timestamp(end)?;
let mut profile = TariffProfile::new(unit);
if let Some(name) = o.first_price.as_deref() {
profile.first_price = name;
}
if let Some(name) = o.start_object.as_deref() {
profile.start_object = name;
}
if o.fc_given {
profile.settings_fc = o.fc;
}
let mut client = mms_connect(host, &o)?;
let schedule = client.read_tariff_schedule(node, profile, window).map_err(|e| format!("{node}: {e}"))?;
let _ = client.release();
println!("start_utc_s\tend_utc_s\tprice\tunit");
for slot in schedule.slots {
println!("{}\t{}\t{}\t{}", slot.utc.start, slot.utc.end, slot.price, schedule.price_unit);
}
Ok(())
}
fn mms_identify(host: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let mut c = mms_connect(host, &o)?;
let id = c.identify().map_err(|e| e.to_string())?;
println!("vendor {}", id.vendor);
println!("model {}", id.model);
println!("revision {}", id.revision);
if let Some(n) = c.negotiated() {
println!("max PDU {} octets", n.max_pdu);
println!("outstanding {}", n.max_outstanding);
}
let _ = c.release();
Ok(())
}
fn mms_status(host: &str, args: &[&str]) -> Result<(), String> {
use iec61850_kit::proto::mms::{vmd_logical, vmd_physical};
let o = mms_options(args)?;
let mut c = mms_connect(host, &o)?;
let s = c.status(false).map_err(|e| e.to_string())?;
let logical = match s.logical {
vmd_logical::STATE_CHANGES_ALLOWED => "state-changes-allowed",
vmd_logical::NO_STATE_CHANGES_ALLOWED => "no-state-changes-allowed",
vmd_logical::LIMITED_SERVICES_ALLOWED => "limited-services-allowed",
vmd_logical::SUPPORT_SERVICES_ALLOWED => "support-services-allowed",
_ => "unknown",
};
let physical = match s.physical {
vmd_physical::OPERATIONAL => "operational",
vmd_physical::PARTIALLY_OPERATIONAL => "partially-operational",
vmd_physical::INOPERABLE => "inoperable",
vmd_physical::NEEDS_COMMISSIONING => "needs-commissioning",
_ => "unknown",
};
println!("logical {} ({})", logical, s.logical);
println!("physical {} ({})", physical, s.physical);
println!("healthy {}", s.is_healthy());
match c.capabilities() {
Ok(caps) if !caps.is_empty() => {
println!("capabilities");
for cap in caps {
println!(" {cap}");
}
}
Ok(_) => println!("capabilities (none)"),
Err(e) => println!("capabilities unavailable ({e})"),
}
let _ = c.release();
Ok(())
}
fn mms_browse(host: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let mut c = mms_connect(host, &o)?;
let devices = c.server_directory().map_err(|e| e.to_string())?;
if devices.is_empty() {
println!("(the server reports no logical devices)");
}
for ld in &devices {
println!("{ld}");
let names = c.logical_device_directory(ld).map_err(|e| e.to_string())?;
for name in &names {
println!(" {name}");
}
let sets = c.data_set_directory(ld).unwrap_or_default();
for set in &sets {
println!(" data set {set}");
for member in c.data_set_members(ld, set).unwrap_or_default() {
println!(" {member}");
}
}
println!(" {} variables, {} data sets", names.len(), sets.len());
}
let _ = c.release();
Ok(())
}
fn mms_read(host: &str, reference: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let mut c = mms_connect(host, &o)?;
let value = c.read(reference, o.fc).map_err(|e| format!("{reference}: {e}"))?;
println!("{reference} = {}", show_value(&value));
let _ = c.release();
Ok(())
}
fn mms_write(host: &str, reference: &str, literal: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
if !o.fc_given {
return Err("a write needs --fc: settings are SP or SE, configuration CF, description DC, control CO.\n ST and MX are what the process reports; a conforming server refuses a write to them.".to_string());
}
let value = parse_value(&o.value_type, literal)?;
let mut c = mms_connect(host, &o)?;
c.write(reference, o.fc, &value).map_err(|e| format!("{reference}: {e}"))?;
println!("{reference} <- {}", show_value(&value));
let _ = c.release();
Ok(())
}
fn mms_report(host: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let mut c = mms_connect(host, &o)?;
if let Some(reference) = &o.rcb {
let fc = if reference.contains("$BR$") || o.buffered { Fc::BR } else { Fc::RP };
let mut settings = RcbSettings::new().with_useful_fields().with_trg_ops(TrgOps::EVENTS);
if let Some(ms) = o.intg_pd {
settings = settings.with_intg_pd(ms).with_trg_ops(TrgOps::EVENTS.with_integrity(true));
}
if let Some(ds) = &o.data_set {
settings.data_set = Some(ds.clone());
}
let rcb = c.enable_rcb(reference, fc, &settings).map_err(|e| format!("{reference}: {e}"))?;
println!("enabled {} — data set {}, {} ", rcb.reference, rcb.data_set.as_deref().unwrap_or("(none)"), describe_trg_ops(rcb.trg_ops));
if o.gi {
c.general_interrogation(reference, fc).map_err(|e| format!("{reference}: {e}"))?;
println!("general interrogation requested");
}
}
println!("listening for {} s", o.seconds);
let deadline = std::time::Instant::now() + Duration::from_secs(o.seconds);
let mut n = 0u64;
while std::time::Instant::now() < deadline {
let left = deadline.saturating_duration_since(std::time::Instant::now());
match c.next_unsolicited(left.min(Duration::from_millis(500))) {
Ok(Some(Unsolicited::Report(r))) => {
n += 1;
print_report(n, &r);
}
Ok(Some(Unsolicited::CommandTermination(t))) => {
println!("command termination {} for {}", if t.is_positive() { "+" } else { "-" }, t.control_object());
}
Ok(Some(Unsolicited::Other { name, values, .. })) => {
n += 1;
println!("report {n} {name} — {} values (not an IEC 61850 report)", values.len());
}
Ok(None) => {}
Err(e) => return Err(e.to_string()),
}
}
println!("{n} reports");
if let Some(reference) = &o.rcb {
let fc = if reference.contains("$BR$") || o.buffered { Fc::BR } else { Fc::RP };
let _ = c.disable_rcb(reference, fc);
}
let _ = c.release();
Ok(())
}
fn print_report(n: u64, r: &Report) {
print!("report {n} {}", r.rpt_id);
if let Some(sq) = r.seq_num {
print!(" sq={sq}");
}
if let Some(t) = r.time_of_entry {
print!(" t={t}");
}
if let Some(ds) = &r.data_set {
print!(" dataSet={ds}");
}
if let Some(rev) = r.conf_rev {
print!(" confRev={rev}");
}
if r.buf_ovfl == Some(true) {
print!(" BUFFER OVERFLOW");
}
if r.is_partial() {
print!(" (segment {}, more follow)", r.sub_seq_num.unwrap_or(0));
}
println!(" — {} of {} members", r.entries.len(), r.data_set_len());
for e in &r.entries {
let name = e.reference.clone().unwrap_or_else(|| format!("[{}]", e.index));
let reason = e.reason.map_or_else(String::new, |r| format!(" ({})", describe_reason(r)));
println!(" {name} = {}{reason}", show_value(&e.value));
}
}
fn describe_reason(r: ReasonCode) -> String {
let mut parts = Vec::new();
if r.data_change() {
parts.push("data change");
}
if r.quality_change() {
parts.push("quality change");
}
if r.data_update() {
parts.push("data update");
}
if r.integrity() {
parts.push("integrity");
}
if r.general_interrogation() {
parts.push("general interrogation");
}
if parts.is_empty() { String::from("no reason given") } else { parts.join(", ") }
}
fn describe_trg_ops(t: Option<TrgOps>) -> String {
let Some(t) = t else { return String::from("triggers unknown") };
let mut parts = Vec::new();
if t.data_change() {
parts.push("data change");
}
if t.quality_change() {
parts.push("quality change");
}
if t.data_update() {
parts.push("data update");
}
if t.integrity() {
parts.push("integrity");
}
if t.general_interrogation() {
parts.push("GI");
}
if parts.is_empty() { String::from("no triggers") } else { format!("triggers: {}", parts.join(", ")) }
}
fn mms_control(host: &str, reference: &str, literal: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let value = parse_value(&o.value_type, literal)?;
let mut model = o.model;
if let (Some(path), Some(ied)) = (&o.scd, &o.ied) {
let xml = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
let scl = scl::Scl::parse(&xml).map_err(|e| format!("{path}: {e}"))?;
if let Some(m) = scl.model(Some(ied)).ok().and_then(|m| m.control_model(reference)) {
println!("{reference}: control model {m:?}, from {path}");
model = Some(m);
}
}
let mut c = mms_connect(host, &o)?;
let mut control = c.control(reference);
if let Some(m) = model {
control = control.model(m);
}
let outcome = control.origin(o.orcat, &o.orident).check(Check { synchro: o.synchro, interlock: o.interlock }).test(o.test).execute(&value);
let _ = c.release();
match outcome {
Ok(None) => {
println!("{reference} <- {} (accepted)", show_value(&value));
Ok(())
}
Ok(Some(t)) => {
println!("{reference} <- {} (command termination + for {})", show_value(&value), t.control_object());
Ok(())
}
Err(iec61850_kit::Error::ControlRejected { add_cause }) => {
Err(format!("{reference}: refused — {:?} (AddCause {add_cause})", AddCause::from_code(add_cause)))
}
Err(e) => Err(format!("{reference}: {e}")),
}
}
fn mms_rcb(host: &str, reference: &str, args: &[&str]) -> Result<(), String> {
let o = mms_options(args)?;
let fc = if reference.contains("$BR$") || o.buffered { Fc::BR } else { Fc::RP };
let mut c = mms_connect(host, &o)?;
let rcb = c.read_rcb(reference, fc).map_err(|e| format!("{reference}: {e}"))?;
println!("{}", rcb.reference);
println!(" kind {}", if rcb.buffered { "buffered (BR)" } else { "unbuffered (RP)" });
println!(" RptID {}", rcb.rpt_id.as_deref().unwrap_or("-"));
println!(" RptEna {}", rcb.rpt_ena);
println!(" DatSet {}", rcb.data_set.as_deref().unwrap_or("-"));
println!(" ConfRev {}", rcb.conf_rev.map_or_else(|| String::from("-"), |v| v.to_string()));
println!(" OptFlds {}", rcb.opt_flds.map_or_else(|| String::from("-"), describe_opt_flds));
println!(" TrgOps {}", describe_trg_ops(rcb.trg_ops));
println!(" BufTm {} ms", rcb.buf_tm.map_or_else(|| String::from("-"), |v| v.to_string()));
println!(" IntgPd {} ms", rcb.intg_pd.map_or_else(|| String::from("-"), |v| v.to_string()));
println!(" SqNum {}", rcb.sq_num.map_or_else(|| String::from("-"), |v| v.to_string()));
if rcb.buffered {
println!(" EntryID {}", rcb.entry_id.as_ref().map_or_else(|| String::from("-"), |b| format!("{b:02X?}")));
println!(" ResvTms {}", rcb.resv_tms.map_or_else(|| String::from("-"), |v| v.to_string()));
} else {
println!(" Resv {}", rcb.resv.map_or_else(|| String::from("-"), |v| v.to_string()));
}
let _ = c.release();
Ok(())
}
fn describe_opt_flds(o: OptFlds) -> String {
let mut parts = Vec::new();
for (on, name) in [
(o.sequence_number(), "SqNum"),
(o.report_time_stamp(), "TimeOfEntry"),
(o.reason_for_inclusion(), "ReasonCode"),
(o.data_set_name(), "DatSet"),
(o.data_reference(), "DataRef"),
(o.buffer_overflow(), "BufOvfl"),
(o.entry_id(), "EntryID"),
(o.conf_revision(), "ConfRev"),
(o.segmentation(), "segmentation"),
] {
if on {
parts.push(name);
}
}
if parts.is_empty() { String::from("none") } else { parts.join(", ") }
}
fn parse_value(kind: &str, literal: &str) -> Result<IedValue, String> {
Ok(match kind {
"bool" => IedValue::Boolean(match literal {
"1" | "true" | "on" => true,
"0" | "false" | "off" => false,
other => return Err(format!("`{other}` is not a boolean; use true/false")),
}),
"int" => IedValue::Integer(literal.parse().map_err(|_| format!("`{literal}` is not an integer"))?),
"uint" => IedValue::Unsigned(literal.parse().map_err(|_| format!("`{literal}` is not an unsigned integer"))?),
"float" => IedValue::Float32(literal.parse().map_err(|_| format!("`{literal}` is not a number"))?),
"string" => IedValue::VisibleString(literal.to_string()),
other => return Err(format!("unknown --type `{other}`; use bool, int, uint, float or string")),
})
}
fn show_value(v: &IedValue) -> String {
match v {
IedValue::Boolean(b) => format!("{b}"),
IedValue::Integer(i) => format!("{i}"),
IedValue::Unsigned(u) => format!("{u}"),
IedValue::Float32(f) => format!("{f}"),
IedValue::Float64(f) => format!("{f}"),
IedValue::VisibleString(s) | IedValue::MmsString(s) => format!("{s:?}"),
IedValue::UtcTime(t) => format!("{t}"),
IedValue::BitString { unused, bytes } => match v.as_dbpos() {
Some(p) => format!("{p:?}"),
None => match v.as_quality() {
Some(q) => format!("{q:?}"),
None => format!("bitstring {bytes:02X?} ({unused} unused)"),
},
},
IedValue::OctetString(b) | IedValue::BinaryTime(b) => format!("{b:02X?}"),
IedValue::Array(m) | IedValue::Structure(m) => {
let inner: Vec<String> = m.iter().map(show_value).collect();
format!("{{ {} }}", inner.join(", "))
}
IedValue::Other { tag, bytes, .. } => format!("[{tag}] {bytes:02X?}"),
}
}
fn parse_edition(value: &str) -> Result<Edition, String> {
match value {
"1" => Ok(Edition::Ed1),
"2" => Ok(Edition::Ed2),
"2.1" => Ok(Edition::Ed2_1),
other => Err(format!("unknown edition `{other}`; expected 1, 2 or 2.1")),
}
}
fn edition_name(edition: Edition) -> &'static str {
match edition {
Edition::Ed1 => "Edition 1",
Edition::Ed2 => "Edition 2",
Edition::Ed2_1 => "Edition 2.1",
_ => "Edition ?",
}
}
fn scl_validate(file: &str, args: &[&str]) -> Result<(), String> {
let mut freq = 50u32;
let mut edition = Edition::Ed2_1;
let mut warnings_are_errors = false;
let mut it = args.iter();
while let Some(arg) = it.next() {
let mut value = || it.next().copied().ok_or_else(|| format!("{arg} needs a value"));
match *arg {
"--freq" => freq = value()?.parse().map_err(|_| "--freq needs a number".to_string())?,
"--edition" => edition = parse_edition(value()?)?,
"--strict" => warnings_are_errors = true,
other => return Err(format!("unknown option `{other}`")),
}
}
let xml = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
let report = scl::validate(&xml, freq, edition).map_err(|e| e.to_string())?;
println!("{file}: SCL {}, {} IED(s)", report.scl_version, report.ieds.len());
for f in &report.findings {
println!(" {f}");
}
let (errors, warnings) = (report.errors().count(), report.warnings().count());
if errors == 0 && warnings == 0 {
println!(" no problems found");
return Ok(());
}
println!(" {errors} error(s), {warnings} warning(s)");
if errors > 0 || (warnings_are_errors && warnings > 0) { Err(format!("{} problem(s)", errors + warnings)) } else { Ok(()) }
}
fn scl_show(file: &str, ied: Option<&str>) -> Result<(), String> {
let xml = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
let model = IedModel::from_scl_with(&xml, ied, LoadOptions::default()).map_err(|e| e.to_string())?;
println!(
"IED {} ({} {}, config {})",
model.name,
model.manufacturer.as_deref().unwrap_or("-"),
model.ied_type.as_deref().unwrap_or("-"),
model.config_version.as_deref().unwrap_or("-")
);
for ap in &model.access_points {
match &ap.address {
Some(a) => {
let sel = |s: &Option<Vec<u8>>| {
s.as_ref().map_or_else(
|| "-".to_string(),
|v| {
v.iter().fold(String::new(), |mut acc, b| {
use std::fmt::Write;
let _ = write!(acc, "{b:02X}");
acc
})
},
)
};
println!(
" AccessPoint {} ip={} tsel={} ssel={} psel={} ap-title={} ae-qual={}",
ap.name,
a.ip.as_deref().unwrap_or("-"),
sel(&a.t_sel),
sel(&a.s_sel),
sel(&a.p_sel),
a.ap_title.as_ref().map_or_else(|| "-".to_string(), |t| t.iter().map(ToString::to_string).collect::<Vec<_>>().join(".")),
a.ae_qualifier.map_or_else(|| "-".to_string(), |q| q.to_string())
);
}
None => println!(" AccessPoint {} (no OSI address)", ap.name),
}
}
for ld in &model.logical_devices {
println!(" LD {} (inst {})", ld.name, ld.inst);
for ln in &ld.logical_nodes {
println!(" LN {} [{}] {} data objects", ln.name, ln.ln_type, ln.data_objects.len());
for object in &ln.data_objects {
println!(" DO {} [{}]", object.name, if object.cdc.is_empty() { "-" } else { object.cdc.as_str() });
}
for ds in &ln.data_sets {
println!(" DataSet {} ({} members)", ds.name, ds.members.len());
for m in &ds.members {
println!(" {}", model.fcda_reference(&ld.name, m));
}
}
for g in &ln.gse_controls {
let addr = g.address.as_ref().map_or_else(|| "no address".to_string(), |a| format!("{} appid={:#06x} vlan={}", a.mac, a.appid, a.vlan_id));
println!(" GSEControl {} confRev={} {}", g.name, g.conf_rev, addr);
}
for s in &ln.smv_controls {
let addr = s.address.as_ref().map_or_else(|| "no address".to_string(), |a| format!("{} appid={:#06x}", a.mac, a.appid));
let kind = if s.multicast { "multicast" } else { "unicast" };
println!(" SampledValueControl {} {kind} smvID={} smpRate={} nofASDU={} {}", s.name, s.smv_id, s.smp_rate, s.nof_asdu, addr);
}
for r in &ln.report_controls {
println!(" ReportControl {} buffered={} confRev={} bufTime={}ms", r.name, r.buffered, r.conf_rev, r.buf_time_ms);
}
}
}
if !model.diagnostics.is_empty() {
println!(" {} diagnostic(s); run `ied scl validate` for detail", model.diagnostics.len());
}
Ok(())
}
struct MuOptions {
profile: SvProfile,
frames: u32,
sv_id: String,
appid: u16,
amplitude: i32,
freq: f64,
gm: Option<[u8; 8]>,
refr_tm: bool,
}
impl MuOptions {
fn parse(args: &[&str]) -> Result<MuOptions, String> {
let mut o = MuOptions {
profile: SvProfile::LE_80_50HZ,
frames: 1000,
sv_id: String::from("MU01"),
appid: 0x4000,
amplitude: 100_000,
freq: 0.0,
gm: None,
refr_tm: false,
};
let mut freq = None;
let mut it = args.iter();
while let Some(arg) = it.next() {
let mut value = || it.next().copied().ok_or_else(|| format!("{arg} needs a value"));
match *arg {
"--profile" => {
o.profile = match value()? {
"le80-50" => SvProfile::LE_80_50HZ,
"le80-60" => SvProfile::LE_80_60HZ,
"le256-50" => SvProfile::LE_256_50HZ,
"le256-60" => SvProfile::LE_256_60HZ,
"f4800s2" => SvProfile::F4800S2I4U4,
"f14400s6" => SvProfile::F14400S6I4U4,
other => return Err(format!("unknown profile `{other}`")),
}
}
"--frames" => o.frames = value()?.parse().map_err(|_| "--frames needs a number".to_string())?,
"--sv-id" => o.sv_id = value()?.to_string(),
"--appid" => o.appid = u16::from_str_radix(value()?.trim_start_matches("0x"), 16).map_err(|_| "--appid needs hex".to_string())?,
"--amplitude" => o.amplitude = value()?.parse().map_err(|_| "--amplitude needs a number".to_string())?,
"--freq" => freq = Some(value()?.parse().map_err(|_| "--freq needs a number".to_string())?),
"--refr-tm" => o.refr_tm = true,
"--gm" => o.gm = Some(parse_hex8(value()?)?),
other => return Err(format!("unknown option `{other}`")),
}
}
o.freq = freq.unwrap_or(match o.profile.samples_per_second {
4800 | 15_360 if o.profile.smp_mod.is_none() => 60.0,
_ => 50.0,
});
Ok(o)
}
}
fn parse_hex8(hex: &str) -> Result<[u8; 8], String> {
let bad = || "--gm needs 16 hex digits".to_string();
let mut id = [0u8; 8];
if hex.len() != 16 {
return Err(bad());
}
for (i, slot) in id.iter_mut().enumerate() {
*slot = hex.get(i * 2..i * 2 + 2).ok_or_else(bad).and_then(|p| u8::from_str_radix(p, 16).map_err(|_| bad()))?;
}
Ok(id)
}
fn scl_subs(file: &str, ied: &str, args: &[&str]) -> Result<(), String> {
let mut freq = 50u32;
let mut it = args.iter();
while let Some(arg) = it.next() {
match *arg {
"--freq" => {
freq = it.next().copied().ok_or("--freq needs a value")?.parse().map_err(|_| "--freq needs a number".to_string())?;
}
other => return Err(format!("unknown option `{other}`")),
}
}
let xml = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
let subs = scl::subscriptions(&xml, ied, freq).map_err(|e| e.to_string())?;
println!("{ied} subscribes to {} GOOSE and {} sampled-value stream(s)", subs.goose.len(), subs.sv.len());
for s in subs.goose.iter().chain(&subs.sv) {
let rate = s.samples_per_second.map_or_else(String::new, |r| format!(" rate={r}/s"));
let channels = s.layout.as_ref().map_or_else(String::new, |l| format!(" {} channels/{} octets per ASDU", l.channels().len(), l.len()));
println!(" {} from {} ({})", s.identifier, s.publisher, s.control_block);
println!(" {} appid={:#06x} confRev={}{rate}{channels}", s.dst, s.appid, s.conf_rev);
for x in &s.ext_refs {
let target = format!(
"{}{}{}.{}{}",
x.prefix,
x.ln_class.as_deref().unwrap_or("LLN0"),
x.ln_inst,
x.do_name.as_deref().unwrap_or("-"),
x.da_name.as_deref().map(|d| format!(".{d}")).unwrap_or_default()
);
println!(" <- {target}{}", x.int_addr.as_deref().map(|a| format!(" [{a}]")).unwrap_or_default());
}
}
let scl = scl::Scl::parse(&xml).map_err(|e| e.to_string())?;
let model = scl.model(Some(ied)).map_err(|e| e.to_string())?;
let nodes = model.supervision();
if !nodes.is_empty() {
println!("supervision:");
for n in &nodes {
match &n.control_block {
Some(cb) => {
let watched = subs.goose.iter().chain(&subs.sv).any(|s| n.watches(&s.control_block));
println!(" {} ({}) -> {cb}{}", n.node, n.ln_class, if watched { "" } else { " [not subscribed]" });
}
None => println!(" {} ({}) -> nothing engineered", n.node, n.ln_class),
}
}
}
if subs.unresolved.is_empty() {
Ok(())
} else {
for d in &subs.unresolved {
println!(" unresolved: {d}");
}
Err(format!("{} unresolved binding(s)", subs.unresolved.len()))
}
}
enum MuSink {
File { out: Writer, path: String },
Live { link: Box<iec61850_kit::net::Link>, launch: bool, start: Instant, first: u64 },
}
impl MuSink {
fn emit(&mut self, nanos: u64, frame: &[u8]) -> Result<(), String> {
match self {
MuSink::File { out, .. } => out.write(nanos, frame).map_err(|e| e.to_string()),
MuSink::Live { link, launch, start, first } => {
let due = start.plus_nanos(nanos - *first);
if *launch {
wait_until(Instant(due.0.saturating_sub(1_000_000)));
link.send_at(frame, due).map_err(|e| e.to_string())
} else {
wait_until(due);
link.send(frame).map_err(|e| e.to_string())
}
}
}
}
}
fn wait_until(due: Instant) {
loop {
let now = iec61850_kit::common::monotonic_now();
let left = due.nanos_since(now);
if left == 0 {
return;
}
if left > 200_000 {
std::thread::sleep(Duration::from_nanos(left - 150_000));
} else {
std::hint::spin_loop();
}
}
}
fn mu_cmd(args: &[&str]) -> Result<(), String> {
let (target, options) = match args.split_first() {
Some((first, rest)) if !first.starts_with('-') => (Some(*first), rest),
_ => (None, args),
};
let mut iface = None;
let mut launch = false;
let mut rest = Vec::new();
let mut it = options.iter();
while let Some(arg) = it.next() {
match *arg {
"--iface" => iface = Some(*it.next().ok_or("--iface needs a value")?),
"--launch-time" => launch = true,
other => rest.push(other),
}
}
match (target, iface) {
(Some(file), None) => merging_unit(MuTarget::File(file_arg(file)?), &rest),
(None, Some(iface)) => merging_unit(MuTarget::Live(iface, launch), &rest),
_ => Err(String::from("usage: ied mu (<OUT.pcap> | --iface <IF> [--launch-time]) [OPTIONS]")),
}
}
enum MuTarget<'a> {
File(&'a str),
Live(&'a str, bool),
}
fn merging_unit(target: MuTarget<'_>, args: &[&str]) -> Result<(), String> {
let opt = MuOptions::parse(args)?;
let (link, src) = match target {
MuTarget::Live(iface, launch) => {
let link = iec61850_kit::net::Link::open(iface, &iec61850_kit::net::LinkOptions::sv().launch_time(launch)).map_err(|e| format!("{iface}: {e}"))?;
iec61850_kit::net::drop_capabilities().map_err(|e| e.to_string())?;
let src = link.mac();
(Some((link, launch)), src)
}
MuTarget::File(_) => (None, MacAddr([0x02, 0, 0, 0, 0, 1])),
};
let header = FrameHeader {
dst: MacAddr([0x01, 0x0C, 0xCD, 0x04, (opt.appid >> 8) as u8 & 0x01, opt.appid as u8]),
src,
vlan: Some(VlanTag::DEFAULT),
ethertype: ETHERTYPE_SV,
appid: opt.appid,
reserved1: 0,
reserved2: 0,
};
let mut publisher = Publisher::new(PublisherConfig::new(header, opt.sv_id.clone(), opt.profile).with_time_fields(opt.refr_tm, opt.gm.is_some()))
.map_err(|e| e.to_string())?;
publisher.set_smp_synch(SmpSynch::Global).map_err(|e| e.to_string())?;
if let Some(id) = opt.gm {
publisher.set_gm_identity(id);
}
let interval = opt.profile.frame_interval_nanos();
let per_frame = publisher.asdus_per_frame();
let mut nanos = 1_700_000_000u64 * 1_000_000_000;
let mut sink = match (target, link) {
(MuTarget::File(file), _) => MuSink::File { out: Writer::create(file).map_err(|e| format!("{file}: {e}"))?, path: file.to_string() },
(MuTarget::Live(..), Some((link, launch))) => {
MuSink::Live { link: Box::new(link), launch, start: iec61850_kit::common::monotonic_now().plus_millis(5), first: nanos }
}
(MuTarget::Live(..), None) => return Err(String::from("no link")),
};
let mut sample_index = 0u32;
for _ in 0..opt.frames {
let blocks: Vec<[u8; 64]> = (0..per_frame)
.map(|k| {
let i = sample_index + k as u32;
let phase = |offset: f64| {
let turn = f64::from(i) / f64::from(opt.profile.samples_per_second) * opt.freq * core::f64::consts::TAU;
(f64::from(opt.amplitude) * (turn + offset).sin()) as i32
};
let (a, b, c) = (phase(0.0), phase(-2.0944), phase(2.0944));
PhsMeas1 {
currents: [a / 10, b / 10, c / 10, 0],
current_quality: [iec61850_kit::Quality::GOOD; 4],
voltages: [a, b, c, 0],
voltage_quality: [iec61850_kit::Quality::GOOD; 4],
}
.encode()
})
.collect();
let refs: Vec<&[u8]> = blocks.iter().map(<[u8; 64]>::as_slice).collect();
if opt.refr_tm {
publisher.set_refr_tm(UtcTime::from_unix_nanos(nanos, TimeQuality::SYNCHRONIZED));
}
publisher.publish(Instant(nanos), &refs).map_err(|e| e.to_string())?;
if let Some(frame) = publisher.poll_transmit() {
sink.emit(nanos, frame)?;
}
sample_index += per_frame as u32;
nanos += interval;
}
let destination = match sink {
MuSink::File { out, path } => {
out.finish().map_err(|e| e.to_string())?;
format!("wrote {} frames to {path}", opt.frames)
}
MuSink::Live { mut link, launch, .. } => {
let late = if launch { link.launch_errors().map_err(|e| e.to_string())? } else { iec61850_kit::net::LaunchErrors::default() };
let note = match (late.missed, late.invalid) {
(0, 0) => String::new(),
(m, 0) => format!(" ({m} missed their launch time)"),
(0, i) => format!(" ({i} refused by the qdisc)"),
(m, i) => format!(" ({m} missed their launch time, {i} refused by the qdisc)"),
};
format!("sent {} frames on {}{note}", opt.frames, link.interface())
}
};
println!(
"{destination}: svID={} {} samples/s, {per_frame} ASDU/frame, {} frames/s, {} Hz waveform",
opt.sv_id,
opt.profile.samples_per_second,
opt.profile.frames_per_second(),
opt.freq
);
Ok(())
}