mxaccesscli: read/write/subscribe System Platform tags via MxAccess

New tool wrapping ArchestrA.MxAccess.LMXProxyServerClass (the same COM
proxy aaObjectViewer / WindowViewer use) as a CliFx CLI for LLM-driven
debugging.

Commands:
- mxa info      — loaded MxAccess assembly identity, supported value
                   types, MxStatusCategory enum.
- mxa read      — fetch one or more tag values; subscribes briefly,
                   captures first OnDataChange per tag, tears down.
- mxa write     — write a value with optional --type coercion; advises
                   first to resolve the attribute type, then waits for
                   OnWriteComplete with a per-call timeout.
- mxa subscribe — stream OnDataChange events for --seconds; JSON Lines
                   under --llm-json for piped agent consumption.
- mxa diag      — minimal smoke test on a private STA thread; bypasses
                   the CliFx pipeline for diagnosing apartment / pump
                   issues.

Implementation notes documented in docs/api-notes.md (reverse-engineered
because AVEVA does not publish a single canonical MxAccess reference):

- Net48 / x86 / [STAThread] are non-negotiable. The CLI runs the entire
  CliFx pipeline on a dedicated STA thread.
- COM events are dispatched as Win32 messages; AutoResetEvent.WaitOne
  alone does not pump them on this configuration. MxSession.WaitForUpdate
  loops Application.DoEvents() + drain + Sleep(20ms) instead.
- Write requires the target attribute's type to be resolved first.
  WriteCommand advises and waits for the initial OnDataChange before
  calling LMXProxyServerClass.Write to avoid ArgumentException
  "Value does not fall within the expected range".
- Errors carry the full MXSTATUS_PROXY[] from MxAccess (Success,
  Category, DetectedBy, Detail) so an agent can tell exactly which
  layer rejected a request.

Verified against the live ZB galaxy with a writeable tag identified
via grdb (TestChildObject.TestInt, mx_attribute_category=10):
  read:      99 (q=192, MxCategoryOk)
  write 7:   round-tripped — read returned 7 — written back to 99
  write str: TestChildObject.TestString round-tripped a timestamp
  subscribe: captured initial value plus subsequent change from a
             separate process

The vendored ArchestrA.MxAccess.dll is gitignored — it is copied from
C:\Program Files (x86)\ArchestrA\Framework\Bin\ on any System Platform
install per the README.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-05-03 20:02:51 -04:00
parent 5a78ec5a76
commit ab202a1fa1
20 changed files with 1466 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
using System;
using ArchestrA.MxAccess;
namespace MxAccess.Cli.Mx
{
/// One AddItem-handle. Owns Advise/UnAdvise pairing so a Dispose tears
/// down the subscription cleanly even if the caller forgets.
public sealed class MxItem : IDisposable
{
private readonly MxSession _session;
private readonly LMXProxyServerClass _proxy;
private readonly int _hServer;
private bool _advised;
private bool _disposed;
public int Handle { get; }
public string Reference { get; }
internal MxItem(MxSession session, LMXProxyServerClass proxy, int hServer, int hItem, string reference)
{
_session = session;
_proxy = proxy;
_hServer = hServer;
Handle = hItem;
Reference = reference;
}
public void Advise()
{
if (_advised) return;
_proxy.Advise(_hServer, Handle);
_advised = true;
}
public void UnAdvise()
{
if (!_advised) return;
try { _proxy.UnAdvise(_hServer, Handle); } catch { /* best effort */ }
_advised = false;
}
/// `Write` blocks neither the caller nor the proxy — it queues a write and
/// returns. Use MxSession.WaitForUpdate() to await OnWriteComplete.
/// `userId = 0` means "unauthenticated"; OK for simple writes when galaxy
/// security allows it.
public void Write(object value, int userId = 0) =>
_proxy.Write(_hServer, Handle, value, userId);
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { UnAdvise(); } catch { }
try { _proxy.RemoveItem(_hServer, Handle); } catch { }
_session.RemoveItem(Handle);
}
}
}
@@ -0,0 +1,167 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using ArchestrA.MxAccess;
namespace MxAccess.Cli.Mx
{
/// Wraps the MxAccess COM proxy with caller-friendly primitives.
///
/// MxAccess events are dispatched as COM messages on the apartment that
/// called Register. Pure Monitor / AutoResetEvent waits do *not* drain
/// those messages reliably even on STA, so MxSession exposes a
/// `WaitForUpdate` that polls Application.DoEvents() instead. This is the
/// pattern Object Viewer / WindowViewer / aaTagViewer all use under the
/// hood — see docs/api-notes.md "Threading model".
public sealed class MxSession : IDisposable
{
private readonly LMXProxyServerClass _proxy;
private readonly int _hServer;
private readonly object _lock = new object();
private readonly Dictionary<int, MxItem> _itemsByHandle = new Dictionary<int, MxItem>();
private readonly ConcurrentQueue<MxUpdate> _updates = new ConcurrentQueue<MxUpdate>();
private bool _disposed;
public MxSession(string clientName)
{
_proxy = new LMXProxyServerClass();
_proxy.OnDataChange += OnDataChange;
_proxy.OnWriteComplete += OnWriteComplete;
_proxy.OperationComplete += OnOperationComplete;
_hServer = _proxy.Register(string.IsNullOrWhiteSpace(clientName) ? "mxa" : clientName);
}
public int ServerHandle => _hServer;
public MxItem AddItem(string itemRef)
{
if (string.IsNullOrWhiteSpace(itemRef))
throw new ArgumentException("Item reference must be non-empty.", nameof(itemRef));
var hItem = _proxy.AddItem(_hServer, itemRef);
var item = new MxItem(this, _proxy, _hServer, hItem, itemRef);
lock (_lock) _itemsByHandle[hItem] = item;
return item;
}
/// Pump COM messages while watching for an update that matches the predicate.
/// Returns true when one is captured, false on timeout.
public bool WaitForUpdate(Predicate<MxUpdate> match, TimeSpan timeout, out MxUpdate captured)
{
captured = null;
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
Application.DoEvents();
while (_updates.TryDequeue(out var u))
{
if (match(u)) { captured = u; return true; }
}
Thread.Sleep(20);
}
// One last drain after the deadline so we don't miss an event that arrived
// between the final Sleep and the loop exit.
Application.DoEvents();
while (_updates.TryDequeue(out var u))
{
if (match(u)) { captured = u; return true; }
}
return false;
}
/// Drain all pending updates without blocking. Caller must call PumpOnce()
/// in their own loop to keep the COM message queue moving.
public IEnumerable<MxUpdate> DrainUpdates()
{
while (_updates.TryDequeue(out var u)) yield return u;
}
/// Pump COM messages once. Used by streaming subscribers between drains.
public void PumpOnce(TimeSpan slice)
{
Application.DoEvents();
if (slice > TimeSpan.Zero) Thread.Sleep(slice);
}
internal void RemoveItem(int hItem)
{
lock (_lock) _itemsByHandle.Remove(hItem);
}
// ---- Event plumbing ----
private void OnDataChange(int hServer, int hItem, object value, int quality, object timestamp,
ref MXSTATUS_PROXY[] vars)
{
string itemRef;
lock (_lock) itemRef = _itemsByHandle.TryGetValue(hItem, out var it) ? it.Reference : null;
_updates.Enqueue(new MxUpdate
{
Kind = MxUpdateKind.DataChange,
ItemHandle = hItem,
ItemReference = itemRef,
Value = value,
Quality = quality,
Timestamp = TryFiletimeToDateTime(timestamp),
Statuses = MxStatusInfo.From(vars),
});
}
private void OnWriteComplete(int hServer, int hItem, ref MXSTATUS_PROXY[] vars)
{
string itemRef;
lock (_lock) itemRef = _itemsByHandle.TryGetValue(hItem, out var it) ? it.Reference : null;
_updates.Enqueue(new MxUpdate
{
Kind = MxUpdateKind.WriteComplete,
ItemHandle = hItem,
ItemReference = itemRef,
Statuses = MxStatusInfo.From(vars),
});
}
private void OnOperationComplete(int hServer, int hItem, ref MXSTATUS_PROXY[] vars)
{
string itemRef;
lock (_lock) itemRef = _itemsByHandle.TryGetValue(hItem, out var it) ? it.Reference : null;
_updates.Enqueue(new MxUpdate
{
Kind = MxUpdateKind.OperationComplete,
ItemHandle = hItem,
ItemReference = itemRef,
Statuses = MxStatusInfo.From(vars),
});
}
private static DateTime? TryFiletimeToDateTime(object ft)
{
if (ft == null) return null;
try
{
var asLong = Convert.ToInt64(ft);
return DateTime.FromFileTimeUtc(asLong).ToLocalTime();
}
catch { return null; }
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
MxItem[] items;
lock (_lock)
{
items = new MxItem[_itemsByHandle.Count];
_itemsByHandle.Values.CopyTo(items, 0);
_itemsByHandle.Clear();
}
foreach (var it in items)
{
try { it.Dispose(); } catch { }
}
try { _proxy.Unregister(_hServer); } catch { }
}
}
}
@@ -0,0 +1,66 @@
using System;
using ArchestrA.MxAccess;
namespace MxAccess.Cli.Mx
{
public enum MxUpdateKind
{
DataChange,
WriteComplete,
OperationComplete,
}
public sealed class MxUpdate
{
public MxUpdateKind Kind { get; init; }
public int ItemHandle { get; init; }
public string ItemReference { get; init; }
public object Value { get; init; }
public int Quality { get; init; }
public DateTime? Timestamp { get; init; }
public MxStatusInfo[] Statuses { get; init; }
public bool IsOk
{
get
{
if (Statuses == null || Statuses.Length == 0) return true;
foreach (var s in Statuses)
{
if (s.Category != MxStatusCategory.MxCategoryOk &&
s.Category != MxStatusCategory.MxCategoryPending)
return false;
}
return true;
}
}
}
public sealed class MxStatusInfo
{
public short Success { get; init; }
public MxStatusCategory Category { get; init; }
public MxStatusSource DetectedBy { get; init; }
public short Detail { get; init; }
public static MxStatusInfo[] From(MXSTATUS_PROXY[] raw)
{
if (raw == null) return Array.Empty<MxStatusInfo>();
var output = new MxStatusInfo[raw.Length];
for (int i = 0; i < raw.Length; i++)
{
output[i] = new MxStatusInfo
{
Success = raw[i].success,
Category = raw[i].category,
DetectedBy = raw[i].detectedBy,
Detail = raw[i].detail,
};
}
return output;
}
public override string ToString() =>
$"{Category} (success={Success}, detail={Detail}, detectedBy={DetectedBy})";
}
}
@@ -0,0 +1,66 @@
using System;
using System.Globalization;
namespace MxAccess.Cli.Mx
{
/// MxAccess's Write() takes an object and the LMX proxy figures out the
/// type by looking at the destination attribute. The CLI accepts strings
/// and either trusts the proxy (default) or coerces to a caller-specified
/// .NET type up-front so the LMX side gets exactly what we mean.
public static class ValueCoercion
{
public static object Coerce(string raw, string typeHint)
{
if (raw == null) throw new ArgumentNullException(nameof(raw));
if (string.IsNullOrEmpty(typeHint))
return InferAndCoerce(raw);
switch (typeHint.Trim().ToLowerInvariant())
{
case "bool": return ParseBool(raw);
case "byte": return byte.Parse(raw, CultureInfo.InvariantCulture);
case "short": return short.Parse(raw, CultureInfo.InvariantCulture);
case "int":
case "int32": return int.Parse(raw, CultureInfo.InvariantCulture);
case "long":
case "int64": return long.Parse(raw, CultureInfo.InvariantCulture);
case "float":
case "single": return float.Parse(raw, CultureInfo.InvariantCulture);
case "double": return double.Parse(raw, CultureInfo.InvariantCulture);
case "string": return raw;
case "time":
case "datetime":
return DateTime.Parse(raw, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
default:
throw new ArgumentException(
$"Unknown --type '{typeHint}'. Supported: bool, byte, short, int, long, float, double, string, datetime.");
}
}
private static object InferAndCoerce(string raw)
{
if (ParseBool(raw, out var b)) return b;
if (int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var i)) return i;
if (long.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var l)) return l;
if (double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var d)) return d;
return raw;
}
private static bool ParseBool(string raw, out bool result)
{
switch (raw.Trim().ToLowerInvariant())
{
case "true": case "1": case "on": case "yes": result = true; return true;
case "false": case "0": case "off": case "no": result = false; return true;
default: result = false; return false;
}
}
private static bool ParseBool(string raw)
{
if (ParseBool(raw, out var b)) return b;
throw new ArgumentException($"Cannot parse '{raw}' as bool. Use true/false, 1/0, on/off, yes/no.");
}
}
}