fix(focas): scale positions from each cnc_rddynamic2 block; delete the fabricated cnc_getfigure

Every 0x0026 position block is self-describing: [i32 raw][u16 base][u16 exponent],
value = raw / base^exponent. The live 31i-B capture (ref-dynamic2-axis1.bin)
reports base 10 / exponent 4 on every block, so axis 1 is 280.1574 mm, not
2801574. The driver ignored the envelope and instead sent 'cnc_getfigure'
(0x00D3) -- a command that does not exist in the FOCAS wire protocol, served only
by the in-tree mock; the real control refuses it with rc=1, so on hardware every
position fell back to PositionDecimalPlaces (default 0) and published raw counts.

- ParsePositionBlock decodes the envelope into FocasPosition; the driver applies
  raw / base^exponent at publish. PositionDecimalPlaces is now only the fallback
  for a scale-less (4-byte) block.
- A block describing no position (0xFFFF vacant marker, base not 2/10, exponent
  > 18 -- raw / 10^400 would read as a Good 0.0) publishes BadNoData on that node
  alone; siblings are untouched.
- ReadPositionFiguresAsync / IFocasClient.GetPositionFiguresAsync and the
  per-axis figure cache are deleted.

Ported from the sister ignitionoee FOCAS driver v0.17.0 (+ Focas.Wire-014);
live axis-scoped captures live-dynamic2-axis{1,2}-0x0026.bin (Z-34184 X 0.0374,
Y 370.177) added as fixtures.
This commit is contained in:
Joseph Doherty
2026-10-07 14:03:08 -04:00
parent 9460da513c
commit 69e0a622f3
16 changed files with 380 additions and 356 deletions
@@ -132,12 +132,11 @@ public sealed class FocasAlarmProjectionOptions
/// default) to skip range validation and preserve legacy behaviour.
/// </param>
/// <param name="PositionDecimalPlaces">
/// Axis positions returned by <c>cnc_rddynamic2</c> are scaled integers. The driver
/// divides AbsolutePosition / MachinePosition / RelativePosition / DistanceToGo by
/// <c>10^PositionDecimalPlaces</c> at the publish seam so they surface in engineering
/// units on the Float64 axis nodes. Default <c>0</c> (no scaling) is byte-identical to
/// legacy behaviour. Auto-fetching this via <c>cnc_getfigure</c> is deferred (wire-gated),
/// so it is config-supplied. Negative values are clamped to 0 (no scaling).
/// <b>Fallback only.</b> A real CNC's <c>cnc_rddynamic2</c> position block carries its own
/// scale (<c>raw / base^exponent</c>), which the driver always applies and which wins over
/// this setting. Only a block that carries no scale (a 4-byte payload, e.g. an older
/// simulator) is divided by <c>10^PositionDecimalPlaces</c>. Default <c>0</c> (no scaling).
/// Negative values are clamped to 0.
/// </param>
public sealed record FocasDeviceOptions(
string HostAddress,
@@ -925,12 +925,6 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
var sys = await client.GetSysInfoAsync(ct).ConfigureAwait(false);
var axes = await client.GetAxisNamesAsync(ct).ConfigureAwait(false);
// Per-axis decimal-place figures (cnc_getfigure), fetched once. Auto figures win
// over the manual PositionDecimalPlaces config at the publish seam; an empty list
// (or a failed/empty figure read) makes every axis fall back to the config knob.
// Defensive: a figure-read failure must NOT fault device init — default to empty.
state.PositionFigures = await SafeProbe(() => client.GetPositionFiguresAsync(ct), []);
// Optional-API probes — each returns empty / throws when unsupported.
var spindles = await SafeProbe(() => client.GetSpindleNamesAsync(ct), []);
var spindleMaxRpms = await SafeProbe(() => client.GetSpindleMaxRpmsAsync(ct), []);
@@ -999,7 +993,7 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
var snap = await client.ReadDynamicAsync(axisIndex, ct).ConfigureAwait(false);
// Keyed by the disambiguated segment, matching what DiscoverAsync emitted —
// two same-named axes must not share (and overwrite) one cache slot (#548).
PublishAxisSnapshot(state, cache.AxisSegments[i], snap, i); // i = 0-based axis index → PositionFigures lookup
PublishAxisSnapshot(state, cache.AxisSegments[i], snap);
if (i == 0) { firstAxisSnap = snap; PublishRateSnapshot(state, snap); }
}
@@ -1102,40 +1096,34 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// <see cref="PollGroupEngine"/> → <see cref="ReadAsync"/> path, which hits
/// <see cref="TryReadFixedTree"/> and returns these cached values.
/// </summary>
private static void PublishAxisSnapshot(DeviceState state, string axisSegment, FocasDynamicSnapshot snap, int axisIndex)
private static void PublishAxisSnapshot(DeviceState state, string axisSegment, FocasDynamicSnapshot snap)
{
var host = state.Options.HostAddress;
// cnc_rddynamic2 returns positions as scaled integers; divide by 10^figures so they
// surface in engineering units on the Float64 axis nodes. The figure is per-axis:
// an auto cnc_getfigure figure WINS, and the configured PositionDecimalPlaces is the
// fallback when the CNC didn't report one for that axis (see AxisFactor). A figure of
// 0 yields factor 1.0 — i.e. the integer widened to double, byte-identical to legacy
// behaviour (12345 / 1.0 == 12345.0). The managed WireFocasClient fetches figures live
// via ReadPositionFiguresAsync; the config knob is the per-axis fallback only. FeedRate /
// Each cnc_rddynamic2 position block carries its OWN scale (raw / base^exponent — see
// FocasPosition), so positions surface in engineering units with no second read; the
// configured PositionDecimalPlaces applies only to a block that carried no scale. A block
// describing no usable position (vacant 0xFFFF marker, odd base, absurd exponent) is
// cached as NaN and read back as BadNoData for that node alone (see NoValue). FeedRate /
// SpindleSpeed (rate snapshot) and ServoLoad are NOT position-scaled (published elsewhere).
var factor = AxisFactor(state, axisIndex);
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/AbsolutePosition")] = snap.AbsolutePosition / factor;
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/MachinePosition")] = snap.MachinePosition / factor;
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/RelativePosition")] = snap.RelativePosition / factor;
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/DistanceToGo")] = snap.DistanceToGo / factor;
var dp = state.Options.PositionDecimalPlaces;
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/AbsolutePosition")] = snap.AbsolutePosition.ToEngineering(dp) ?? NoValue;
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/MachinePosition")] = snap.MachinePosition.ToEngineering(dp) ?? NoValue;
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/RelativePosition")] = snap.RelativePosition.ToEngineering(dp) ?? NoValue;
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axisSegment}/DistanceToGo")] = snap.DistanceToGo.ToEngineering(dp) ?? NoValue;
}
/// <summary>
/// Resolve the position-scale factor (10^figure) for a single axis. Auto
/// (<c>cnc_getfigure</c>) wins per-axis; manual <c>PositionDecimalPlaces</c> is the
/// fallback when the CNC didn't report a figure for that axis. Both clamp non-negative;
/// 0 ⇒ factor 1.0 (legacy byte-identical). The managed wire backend fetches figures live
/// via <c>ReadPositionFiguresAsync</c>; the fallback branch fires only when the CNC
/// reports no figure for a given axis (or the figure read returns empty).
/// Cache sentinel for "the CNC answered, but this field holds no usable value" (an
/// undescribable position / meter record). The read path turns it into
/// <see cref="FocasStatusMapper.BadNoData"/> for that node only — never a Good number.
/// </summary>
private static double AxisFactor(DeviceState state, int axisIndex)
{
var figures = state.PositionFigures;
var dp = axisIndex >= 0 && axisIndex < figures.Count && figures[axisIndex] >= 0
? figures[axisIndex]
: Math.Max(0, state.Options.PositionDecimalPlaces);
return dp > 0 ? Math.Pow(10, dp) : 1.0;
}
private const double NoValue = double.NaN;
/// <summary>Builds the snapshot for one cached double, mapping <see cref="NoValue"/> to BadNoData.</summary>
private static DataValueSnapshot CachedDouble(double value, uint status, DateTime sourceUtc, DateTime now) =>
double.IsNaN(value)
? new DataValueSnapshot(null, status == FocasStatusMapper.Good ? FocasStatusMapper.BadNoData : status, sourceUtc, now)
: new DataValueSnapshot(value, status, sourceUtc, now);
private static void PublishRateSnapshot(DeviceState state, FocasDynamicSnapshot snap)
{
@@ -1241,7 +1229,7 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
if (state.LastFixedSnapshots.TryGetValue(
FixedTreeReference(state.Options.HostAddress, path), out var raw))
return new DataValueSnapshot(raw, status, sourceUtc, now);
return CachedDouble(raw, status, sourceUtc, now);
// Servo-load match: path shape is "Axes/{name}/ServoLoad"
var suffixFull = path;
@@ -1249,7 +1237,7 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
{
var axisName = suffixFull["Axes/".Length..^"/ServoLoad".Length];
if (state.LastServoLoads.TryGetValue(axisName, out var load))
return new DataValueSnapshot(load, status, sourceUtc, now);
return CachedDouble(load, status, sourceUtc, now);
}
// Spindle matches: "Spindle/{name}/Load" + "Spindle/{name}/MaxRpm"
@@ -1578,9 +1566,10 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
public DateTime? LastFixedPollUtc { get; set; }
/// <summary>
/// Gets the last fixed-tree snapshots by field name. Double-typed so axis
/// positions can carry the <c>10^PositionDecimalPlaces</c> engineering-unit
/// scale applied at <see cref="PublishAxisSnapshot"/>; integer fields
/// (feed rate, spindle speed) widen to double on store.
/// positions can carry the engineering-unit scale applied at
/// <see cref="PublishAxisSnapshot"/>; integer fields (feed rate, spindle speed) widen
/// to double on store. <see cref="NoValue"/> (NaN) marks a field the CNC described as
/// holding no value.
/// </summary>
public ConcurrentDictionary<string, double> LastFixedSnapshots { get; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Gets or sets the last program information snapshot.</summary>
@@ -1593,13 +1582,6 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
public ConcurrentDictionary<string, double> LastServoLoads { get; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Gets the last spindle load percentages by spindle index.</summary>
public ConcurrentDictionary<int, int> LastSpindleLoads { get; } = new();
/// <summary>
/// Gets or sets the per-axis position decimal-place figures fetched once at init via
/// <c>cnc_getfigure</c> (parallel to the axis-name list; index = axis). An auto figure
/// for an axis WINS over the configured <c>PositionDecimalPlaces</c>; an empty list (or
/// a failed/empty figure read) makes every axis fall back to that config knob.
/// </summary>
public IReadOnlyList<int> PositionFigures { get; set; } = [];
/// <summary>Disposes the FOCAS client instance.</summary>
public void DisposeClient()
@@ -290,9 +290,9 @@ public static class FocasDriverFactoryExtensions
public string? Series { get; init; }
/// <summary>
/// Gets or sets the axis-position decimal places. <c>cnc_rddynamic2</c> returns
/// positions as scaled integers; the driver divides by <c>10^PositionDecimalPlaces</c>
/// so they surface in engineering units. Omitted / <c>0</c> = no scaling (legacy).
/// Gets or sets the fallback axis-position decimal places, applied only to a
/// <c>cnc_rddynamic2</c> position block that carries no scale of its own (a real CNC's
/// block does, and its scale wins). Omitted / <c>0</c> = no scaling.
/// </summary>
public int? PositionDecimalPlaces { get; init; }
}
@@ -167,16 +167,6 @@ public interface IFocasClient : IDisposable
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Per-spindle maximum RPM values, indexed as per <see cref="GetSpindleLoadsAsync"/>.</returns>
Task<IReadOnlyList<int>> GetSpindleMaxRpmsAsync(CancellationToken cancellationToken);
/// <summary>
/// Read the per-axis position decimal-place figure via <c>cnc_getfigure</c>. The returned
/// list is parallel to <see cref="GetAxisNamesAsync"/> (index = axis). An EMPTY list means the
/// CNC/backend does not report figures — the driver then falls back to the configured
/// <c>PositionDecimalPlaces</c>. Values are clamped non-negative.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Per-axis position decimal-place figures; empty when the CNC/backend doesn't report them.</returns>
Task<IReadOnlyList<int>> GetPositionFiguresAsync(CancellationToken cancellationToken);
}
/// <summary>One servo-meter entry — one axis's current load percentage.</summary>
@@ -238,12 +228,6 @@ public sealed record FocasSpindleName(string Name, string Suffix1, string Suffix
}
}
/// <summary>
/// Fast-poll bundle for one axis. Position values are scaled integers; the caller
/// divides by <c>10^DecimalPlaces</c> to get the decimal value. DecimalPlaces is
/// supplied by the caller — either via device config (<c>PositionDecimalPlaces</c>) or
/// the per-axis <see cref="IFocasClient.GetPositionFiguresAsync"/> (<c>cnc_getfigure</c>) path.
/// </summary>
/// <summary>
/// Program + operation-mode snapshot. Name is the currently-executing
/// program filename (e.g. "O0001.NC"); ONumber is its Fanuc O-number (1-9999).
@@ -277,6 +261,10 @@ public static class FocasOpMode
};
}
/// <summary>
/// Fast-poll bundle for one axis (<c>cnc_rddynamic2</c>). Each position carries its own scale
/// (see <see cref="FocasPosition"/>); the driver converts it to engineering units at publish.
/// </summary>
public sealed record FocasDynamicSnapshot(
int AxisIndex,
int AlarmFlags,
@@ -285,10 +273,63 @@ public sealed record FocasDynamicSnapshot(
int SequenceNumber,
int ActualFeedRate,
int ActualSpindleSpeed,
int AbsolutePosition,
int MachinePosition,
int RelativePosition,
int DistanceToGo);
FocasPosition AbsolutePosition,
FocasPosition MachinePosition,
FocasPosition RelativePosition,
FocasPosition DistanceToGo);
/// <summary>
/// One <c>cnc_rddynamic2</c> position (command <c>0x0026</c>) as the CNC reported it. The 8-byte
/// wire block is self-describing — <c>[0..3] i32 raw</c>, <c>[4..5] u16 base</c> (2 or 10),
/// <c>[6..7] u16 exponent</c> (<c>0xFFFF</c> = the slot holds no valid position) — and the real
/// coordinate is <c>raw / base^exponent</c>. Confirmed on a real FANUC 31i-B: every block of the
/// <c>ref-dynamic2-axis1.bin</c> capture reports base 10 / exponent 4 (280.1574 mm, not
/// 2801574). That envelope is why no separate figure read exists: the <c>cnc_getfigure</c>
/// (0x00D3) this driver used to send is not a FOCAS wire command, and the 31i-B refuses it.
/// </summary>
/// <param name="Raw">The raw i32 position value.</param>
/// <param name="Base">The block's scale base (only 2 and 10 are meaningful).</param>
/// <param name="Exponent">The block's scale exponent.</param>
/// <param name="HasScale">
/// True when the block carried the base/exponent envelope. A scale-less block (a 4-byte payload
/// from an older simulator, or a raw integer a test supplies) falls back to the device's
/// configured <c>PositionDecimalPlaces</c>.
/// </param>
public readonly record struct FocasPosition(int Raw, int Base = 0, int Exponent = 0, bool HasScale = false)
{
/// <summary>
/// Largest exponent that can describe a real coordinate. An i32 carries at most ten digits,
/// so anything beyond is a misread block — and left unbounded, <c>raw / 10^400</c> is
/// <c>raw / Infinity = 0.0</c>, a Good reading of a machine parked at the origin.
/// </summary>
public const int MaxExponent = 18;
/// <summary>
/// False when the block says it holds no usable position: the <c>0xFFFF</c> vacant marker, a
/// base other than 2 or 10, or an absurd exponent. A per-node quality decision — that node
/// publishes Bad, its siblings are unaffected.
/// </summary>
public bool IsValid => !HasScale || (Exponent <= MaxExponent && Base is 2 or 10);
/// <summary>
/// The position in engineering units: <c>Raw / Base^Exponent</c> when the block carried its
/// own scale (the configured fallback is then ignored), else <c>Raw / 10^fallbackDecimalPlaces</c>.
/// Null when <see cref="IsValid"/> is false.
/// </summary>
/// <param name="fallbackDecimalPlaces">The device's configured <c>PositionDecimalPlaces</c>.</param>
/// <returns>The scaled position, or null when the block describes none.</returns>
public double? ToEngineering(int fallbackDecimalPlaces)
{
if (!IsValid) return null;
if (HasScale) return Exponent == 0 ? Raw : Raw / Math.Pow(Base, Exponent);
var dp = Math.Max(0, fallbackDecimalPlaces);
return dp > 0 ? Raw / Math.Pow(10, dp) : Raw;
}
/// <summary>A bare integer is a scale-less position (legacy shape; tests and fakes).</summary>
/// <param name="raw">The raw position value.</param>
public static implicit operator FocasPosition(int raw) => new(raw);
}
/// <summary>
/// One active alarm surfaced by <see cref="IFocasClient.ReadAlarmsAsync"/>. Shape
@@ -106,10 +106,6 @@ public sealed class SynchronizedFocasClient : IFocasClient
public Task<IReadOnlyList<int>> GetSpindleMaxRpmsAsync(CancellationToken cancellationToken) =>
RunBoundedAsync(ct => _inner.GetSpindleMaxRpmsAsync(ct), cancellationToken);
/// <inheritdoc />
public Task<IReadOnlyList<int>> GetPositionFiguresAsync(CancellationToken cancellationToken) =>
RunBoundedAsync(ct => _inner.GetPositionFiguresAsync(ct), cancellationToken);
/// <summary>Disposes the inner client and the call gate.</summary>
public void Dispose()
{
@@ -339,21 +339,59 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable
var rc = AggregateRc(blocks);
if (rc != 0) return new FocasResult<WireDynamic>(rc, null);
return new FocasResult<WireDynamic>(rc, ParseDynamic2(blocks));
}
/// <summary>
/// Aggregate the <c>cnc_rddynamic2</c> response blocks of one axis read into a
/// <see cref="WireDynamic"/>. The four <c>0x0026</c> blocks are taken in request order
/// (absolute / machine / relative / distance-to-go), each decoded with its own scale by
/// <see cref="ParsePositionBlock"/>.
/// </summary>
/// <param name="blocks">The response blocks of one <see cref="ReadDynamic2Async"/> request.</param>
/// <returns>The decoded fast-poll bundle.</returns>
internal static WireDynamic ParseDynamic2(IReadOnlyList<ResponseBlock> blocks)
{
var programPayload = FindPayload(blocks, 0x001c);
return new FocasResult<WireDynamic>(
rc,
new WireDynamic(
ReadFirstInt32(blocks, 0x001a),
programPayload.Length >= 4 ? ReadInt32(programPayload, 0) : 0,
programPayload.Length >= 8 ? ReadInt32(programPayload, 4) : 0,
ReadFirstInt32(blocks, 0x001d),
ReadFirstInt32(blocks, 0x0024),
ReadFirstInt32(blocks, 0x0025),
new WireAxisPosition(
ReadSelectorPosition(blocks, 0x0026, 0),
ReadSelectorPosition(blocks, 0x0026, 1),
ReadSelectorPosition(blocks, 0x0026, 2),
ReadSelectorPosition(blocks, 0x0026, 3))));
return new WireDynamic(
ReadFirstInt32(blocks, 0x001a),
programPayload.Length >= 4 ? ReadInt32(programPayload, 0) : 0,
programPayload.Length >= 8 ? ReadInt32(programPayload, 4) : 0,
ReadFirstInt32(blocks, 0x001d),
ReadFirstInt32(blocks, 0x0024),
ReadFirstInt32(blocks, 0x0025),
new WireAxisPosition(
ReadSelectorPosition(blocks, 0x0026, 0),
ReadSelectorPosition(blocks, 0x0026, 1),
ReadSelectorPosition(blocks, 0x0026, 2),
ReadSelectorPosition(blocks, 0x0026, 3)));
}
/// <summary>
/// Decode one <c>cnc_rddynamic2</c> position block (0x0026). The 8-byte block is
/// self-describing — <c>[0..3] i32 raw</c>, <c>[4..5] u16 base</c>, <c>[6..7] u16 exponent</c>,
/// value = <c>raw / base^exponent</c> — pinned on a real FANUC 31i-B (every block of
/// <c>ref-dynamic2-axis1.bin</c> reports base 10 / exponent 4). A 4..7-byte block carries no
/// envelope and is returned scale-less (the driver then applies the configured
/// <c>PositionDecimalPlaces</c>); a shorter one decodes as a scale-less 0, as before.
/// </summary>
/// <remarks>
/// Validity (vacant <c>0xFFFF</c> exponent, a base other than 2/10, an absurd exponent) is a
/// per-node quality decision made by <see cref="FocasPosition.IsValid"/>, not a fault here:
/// raising would let one empty slot take out the whole poll. Ported from the sister
/// ignitionoee driver v0.17.0 (<c>Dynamic2.scaledPosition</c>, Focas.Wire-014).
/// </remarks>
/// <param name="payload">The 0x0026 response-block payload.</param>
/// <returns>The position with whatever scale the block carried.</returns>
internal static FocasPosition ParsePositionBlock(byte[] payload)
{
if (payload.Length >= 8)
return new FocasPosition(
ReadInt32(payload, 0),
BinaryPrimitives.ReadUInt16BigEndian(payload.AsSpan(4, 2)),
BinaryPrimitives.ReadUInt16BigEndian(payload.AsSpan(6, 2)),
HasScale: true);
return new FocasPosition(payload.Length >= 4 ? ReadInt32(payload, 0) : 0);
}
/// <summary>Read servo-meter load percentages via <c>cnc_rdsvmeter</c> (command <c>0x0056</c>).</summary>
@@ -382,42 +420,6 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable
return new FocasResult<IReadOnlyList<WireServoMeter>>(rc, result);
}
/// <summary>
/// Read the per-axis position decimal-place figures via <c>cnc_getfigure</c>
/// (command <c>0x00d3</c>). The response payload is a self-delimiting sequence of
/// big-endian <c>short</c> decimal-place counts — one per configured axis — which the
/// driver applies as a <c>10^figure</c> scale on raw position reads.
/// </summary>
/// <remarks>
/// The <c>0x00d3</c> command id is co-designed with the in-tree <c>focas_mock</c> sim and
/// validated against it; like the rest of this managed wire backend the binary shape is
/// sim-consistent and has not been validated against a real Fanuc CNC (bench-CNC-gated).
/// </remarks>
/// <param name="cancellationToken">Cancellation token for the read operation.</param>
/// <param name="timeout">Optional per-call timeout override.</param>
/// <param name="pathId">Optional path ID override; defaults to <see cref="PathId"/>.</param>
/// <returns>The per-axis position decimal-place figures, wrapped in a <see cref="FocasResult{T}"/>.</returns>
public async Task<FocasResult<IReadOnlyList<int>>> ReadPositionFiguresAsync(
CancellationToken cancellationToken = default,
TimeSpan? timeout = null,
ushort? pathId = null)
{
using var callTimeout = CreateCallTimeout(cancellationToken, timeout);
var requestPathId = EffectivePathId(pathId);
var block = await SendSingleRequestAsync(
callTimeout.Token,
new RequestBlock(0x00d3, PathId: requestPathId)).ConfigureAwait(false);
if (block.Rc != 0) return new FocasResult<IReadOnlyList<int>>(block.Rc, null);
var payload = block.Payload;
var figures = new List<int>(payload.Length / 2);
for (var offset = 0; offset + 2 <= payload.Length; offset += 2)
figures.Add(ReadInt16(payload, offset));
return new FocasResult<IReadOnlyList<int>>(block.Rc, figures);
}
/// <summary>Read per-spindle load percentages via <c>cnc_rdspload</c> (command <c>0x0040</c> with arg1=0).</summary>
/// <param name="spindleSelector">Spindle selector; -1 selects all spindles.</param>
/// <param name="cancellationToken">Cancellation token for the read operation.</param>
@@ -1044,17 +1046,17 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable
return payload.Length >= 4 ? ReadInt32(payload, 0) : 0;
}
private static int ReadSelectorPosition(IReadOnlyList<ResponseBlock> blocks, ushort command, int selectorIndex)
private static FocasPosition ReadSelectorPosition(IReadOnlyList<ResponseBlock> blocks, ushort command, int selectorIndex)
{
var seen = 0;
foreach (var block in blocks)
{
if (block.Command != command) continue;
if (seen == selectorIndex)
return block.Payload.Length >= 4 ? ReadInt32(block.Payload, 0) : 0;
return ParsePositionBlock(block.Payload);
seen++;
}
return 0;
return new FocasPosition(0);
}
private static WireSysInfo ParseSysInfo(byte[] payload)
@@ -35,12 +35,15 @@ public sealed record WireStatus(
short Edit,
short TmMode);
/// <summary>Four-slot position quadruple for one axis: absolute / machine / relative / distance-to-go.</summary>
/// <summary>
/// Four-slot position quadruple for one axis: absolute / machine / relative / distance-to-go,
/// each carrying the scale its own <c>0x0026</c> block reported.
/// </summary>
public sealed record WireAxisPosition(
int Absolute,
int Machine,
int Relative,
int Distance);
FocasPosition Absolute,
FocasPosition Machine,
FocasPosition Relative,
FocasPosition Distance);
/// <summary>
/// Fast-poll bundle for one axis from <c>cnc_rddynamic2</c> — alarm flags, active program
@@ -181,6 +181,8 @@ public sealed class WireFocasClient : IFocasClient
ThrowIfRcNonZero(result.Rc, "cnc_rddynamic2", result.IsOk);
var d = result.Value!;
var pos = d.Axis ?? new WireAxisPosition(0, 0, 0, 0);
// Positions keep the scale their own 0x0026 block reported; the driver converts them to
// engineering units at publish (FocasPosition.ToEngineering).
return new FocasDynamicSnapshot(
AxisIndex: axisIndex,
AlarmFlags: d.Alarm,
@@ -253,24 +255,6 @@ public sealed class WireFocasClient : IFocasClient
public Task<IReadOnlyList<int>> GetSpindleMaxRpmsAsync(CancellationToken cancellationToken) =>
ReadSpindleMetricAsync((sel, ct) => _wire.ReadSpindleMaxRpmAsync(sel, ct), cancellationToken);
/// <inheritdoc />
// Reads via FocasWireClient.ReadPositionFiguresAsync; returns an empty list when the read
// fails (non-zero RC — e.g. the series lacks cnc_getfigure) or is not connected. Never
// throws — figure reads degrade to the configured PositionDecimalPlaces rather than faulting.
public async Task<IReadOnlyList<int>> GetPositionFiguresAsync(CancellationToken cancellationToken)
{
if (!_wire.IsConnected) return [];
try
{
var result = await _wire.ReadPositionFiguresAsync(cancellationToken).ConfigureAwait(false);
return result.IsOk && result.Value is { } figures ? figures : [];
}
catch (FocasWireException)
{
return [];
}
}
private static async Task<IReadOnlyList<int>> ReadSpindleMetricAsync(
Func<short, CancellationToken, Task<FocasResult<IReadOnlyList<WireSpindleMetric>>>> call,
CancellationToken cancellationToken)