namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS;
///
/// Parsed FOCAS address covering the four addressing spaces a driver touches:
/// (letter + byte + optional bit — X0.0, R100,
/// F20.3), (CNC parameter number —
/// PARAM:1020, PARAM:1815/0 for bit 0),
/// (macro variable number — MACRO:100, MACRO:500), and
/// (a logical path into the driver's fixed tree —
/// FIXED:Identity/SeriesNumber, FIXED:Axes/X/AbsolutePosition), plus
/// (a selector over the CNC's active alarm list — ALARM:*,
/// ALARM:Servo/401, ALARM:OTHER; see ).
///
///
/// PMC letters: X/Y (IO), F/G (signals between PMC + CNC), R (internal
/// relay), D (data table), C (counter), K (keep relay), A
/// (message display), E (extended relay), T (timer). Byte numbering is 0-based;
/// bit index when present is 0–7 and uses .N for PMC or /N for parameters.
///
/// FIXED: is not an area read. The first three forms name a location the driver
/// asks the CNC for on demand; a FIXED: path names a field of the per-device fixed-tree
/// snapshot the driver's own poll loop already maintains (cnc_sysinfo, cnc_rddynamic2,
/// program info, timers, spindle data). It exists because the fixed tree is the only part of the
/// FOCAS surface with no address of its own, and v3 publishes nodes only for authored tags — so
/// without a form to author, the fixed tree could not be published at all.
///
///
/// The path carries no device. A tag's device comes from its raw-tag Device row, and an
/// address that also named a host would be a second, conflicting routing channel — which is
/// precisely the defect once reported: the browse leaf's {host}/{path} full reference was
/// written into the address field verbatim and then failed to parse, so every browse-committed
/// fixed-tree tag read BadNodeIdUnknown forever.
///
///
public sealed record FocasAddress(
FocasAreaKind Kind,
string? PmcLetter,
int Number,
int? BitIndex,
string? FixedPath = null,
FocasAlarmSelector? AlarmSelector = null)
{
/// The prefix that introduces a address.
public const string FixedPrefix = "FIXED:";
/// The prefix that introduces a address.
public const string AlarmPrefix = "ALARM:";
/// Gets the canonical string representation of this address.
public string Canonical => Kind switch
{
FocasAreaKind.Pmc => BitIndex is null
? $"{PmcLetter}{Number}"
: $"{PmcLetter}{Number}.{BitIndex}",
FocasAreaKind.Parameter => BitIndex is null
? $"PARAM:{Number}"
: $"PARAM:{Number}/{BitIndex}",
FocasAreaKind.Macro => $"MACRO:{Number}",
FocasAreaKind.Fixed => FixedPrefix + FixedPath,
FocasAreaKind.Alarm => AlarmPrefix + AlarmSelector?.Canonical,
_ => $"?{Number}",
};
///
/// Builds the canonical authored address for a fixed-tree path. The one place the
/// FIXED: spelling is constructed, so the browse emitter and the parser cannot drift.
///
/// The fixed-tree path, e.g. Identity/SeriesNumber.
/// The canonical authored address string.
public static string ForFixedPath(string path) => FixedPrefix + path;
/// Builds an address over .
/// The alarm selector.
/// The address.
public static FocasAddress ForAlarm(FocasAlarmSelector selector) =>
new(FocasAreaKind.Alarm, null, 0, null, AlarmSelector: selector);
///
/// Why is not a usable ALARM: address, or when it
/// is one (or is not an ALARM: address at all). Shared by the AdminUI editor and the deploy-time
/// inspector so both say the same thing about the same string.
///
/// The authored address.
/// The refusal reason, or .
public static string? DescribeAlarmAddressError(string? value)
{
var src = value?.Trim() ?? "";
if (!src.StartsWith(AlarmPrefix, StringComparison.OrdinalIgnoreCase)) return null;
return FocasAlarmSelector.TryParse(src[AlarmPrefix.Length..], out _, out var error) ? null : error;
}
/// Attempts to parse a FOCAS address from the given string.
/// The address string to parse.
/// A FocasAddress if parsing succeeds; otherwise null.
public static FocasAddress? TryParse(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return null;
var src = value.Trim();
if (src.StartsWith("PARAM:", StringComparison.OrdinalIgnoreCase))
return ParseScoped(src["PARAM:".Length..], FocasAreaKind.Parameter, bitSeparator: '/');
if (src.StartsWith("MACRO:", StringComparison.OrdinalIgnoreCase))
return ParseScoped(src["MACRO:".Length..], FocasAreaKind.Macro, bitSeparator: null);
// Fixed-tree path. Tested BEFORE the PMC branch on purpose: "F" is a valid PMC letter, so a
// FIXED: address entering that branch would be diagnosed as a malformed PMC address rather
// than as the fixed-tree address it is. (It would still return null either way — this is
// about which rule owns the string, not about the result.)
if (src.StartsWith(FixedPrefix, StringComparison.OrdinalIgnoreCase))
{
var path = NormalizeFixedPath(src[FixedPrefix.Length..]);
return path is null ? null : new FocasAddress(FocasAreaKind.Fixed, null, 0, null, path);
}
// Alarm selector. Tested BEFORE the PMC branch for the same reason as FIXED: — "A" is a
// valid PMC letter (message display), so ALARM:… must be owned by this rule, not diagnosed as PMC.
if (src.StartsWith(AlarmPrefix, StringComparison.OrdinalIgnoreCase))
{
var selector = FocasAlarmSelector.TryParse(src[AlarmPrefix.Length..]);
return selector is null ? null : ForAlarm(selector);
}
// PMC path: letter + digits + optional .bit
if (src.Length < 2 || !char.IsLetter(src[0])) return null;
var letter = src[0..1].ToUpperInvariant();
if (!IsValidPmcLetter(letter)) return null;
var remainder = src[1..];
int? bit = null;
var dotIdx = remainder.IndexOf('.');
if (dotIdx >= 0)
{
if (!int.TryParse(remainder[(dotIdx + 1)..], out var bitValue) || bitValue is < 0 or > 7)
return null;
bit = bitValue;
remainder = remainder[..dotIdx];
}
if (!int.TryParse(remainder, out var number) || number < 0) return null;
return new FocasAddress(FocasAreaKind.Pmc, letter, number, bit);
}
private static FocasAddress? ParseScoped(string body, FocasAreaKind kind, char? bitSeparator)
{
int? bit = null;
if (bitSeparator is char sep)
{
var slashIdx = body.IndexOf(sep);
if (slashIdx >= 0)
{
if (!int.TryParse(body[(slashIdx + 1)..], out var bitValue) || bitValue is < 0 or > 31)
return null;
bit = bitValue;
body = body[..slashIdx];
}
}
if (!int.TryParse(body, out var number) || number < 0) return null;
return new FocasAddress(kind, PmcLetter: null, number, bit);
}
///
/// Validates a fixed-tree path and returns it, or null when it is not a usable path.
/// Accepts Segment[/Segment…] where each segment is non-blank and carries no
/// : — a colon would collide with the PARAM:/MACRO:/FIXED:
/// prefix grammar and make the address ambiguous to read back.
///
///
/// Deliberately shape-only: it does NOT check the path against the fixed tree a particular
/// CNC actually exposes. What that tree contains is per-device and discovered at runtime
/// (spindles, program info and timers are each capability-gated), so a parser that judged
/// membership would have to reject addresses that are valid on the machine they were
/// authored against. An unknown path resolves to no value at read time, which is where the
/// device is known.
///
private static string? NormalizeFixedPath(string body)
{
var path = body.Trim();
if (path.Length == 0) return null;
if (path.Contains(':', StringComparison.Ordinal)) return null;
if (path[0] == '/' || path[^1] == '/') return null;
foreach (var segment in path.Split('/'))
if (string.IsNullOrWhiteSpace(segment)) return null;
return path;
}
private static bool IsValidPmcLetter(string letter) => letter switch
{
"X" or "Y" or "F" or "G" or "R" or "D" or "C" or "K" or "A" or "E" or "T" => true,
_ => false,
};
}
/// Addressing-space kinds the driver understands.
public enum FocasAreaKind
{
/// PMC area — letter + byte + optional bit (X0.0, R100).
Pmc,
/// CNC parameter number (PARAM:1020, PARAM:1815/0).
Parameter,
/// Macro variable number (MACRO:100).
Macro,
///
/// A logical path into the driver's per-device fixed tree (FIXED:Identity/SeriesNumber).
/// Served from the fixed-tree poll snapshot, never from an area read — and read-only, because
/// nothing in that tree is a writable location on the CNC.
///
Fixed,
///
/// A selector over the device's active CNC alarm list (ALARM:*, ALARM:Servo/401-453,
/// ALARM:OTHER). Meaningful only on a raw tag that also carries the cross-driver
/// alarm object, which makes it ONE Part 9 condition at its RawPath; it has no value to read
/// and nothing to write.
///
Alarm,
}