mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-20 00:31:32 +08:00
e61ad4b306
# Description Part 16 §B.3 places `HasSubStateMachine` on the parent **state** node, but the fluent builder attached it to the state-machine **root** because `FluentFiniteStateMachineState` never materialized state nodes at all. Investigating #3821 showed the gap was wider than the reference placement: 1. **No state nodes existed.** The NodeId written into `CurrentState/Id` — `new NodeId(stateId, ElementNamespaceIndex)` — was **dangling**: no node with that id was in the address space. 2. **`AvailableStates` was never populated**, so `GetAvailableStatesAsync` returned empty against a fluent-built server. 3. **The whole client discovery chain was therefore dead.** `ObserveEffectiveStateAsync` enumerates `AvailableStates` and browses `HasSubStateMachine` from each state node — it found nothing. The client side was already spec-correct; only the server deviated. 4. **`HasSubStateMachine` is non-hierarchical** (a subtype of `NonHierarchicalReferences`, `i=32`). Using it as the sub-SM's `BaseInstanceState.ReferenceTypeId` left the sub-SM unreachable from a hierarchical browse of the machine. ## What changed **Element nodes are materialized.** Definition-mode machines now create one `StateType` node per declared state and one `TransitionType` node per declared transition — each a `HasComponent` child carrying `StateNumber` / `TransitionNumber`, with the §B.4 `FromState` / `ToState` / `HasEffect` references and `HasCause` added by `WithCause`. `AvailableStates`, `AvailableTransitions` and `LastTransition` are populated, so `CurrentState/Id` and `LastTransition/Id` resolve to real, browsable nodes. NodeIds are per-instance, so several machines built from one definition coexist. **`HasSubStateMachine` moved to the state node**, with the inverse `SubStateMachineOf`, and the sub-SM is attached as a `HasComponent` child (fixing 4). **Core gains element-id mapping hooks.** `GetCurrentStateId` / `UpdateStateVariable` / `UpdateTransitionVariable` hard-coded the numeric form and were non-virtual, so a subclass could not redirect them. They now route through `public virtual` `GetStateNodeId` / `GetStateId` / `GetTransitionNodeId` / `GetTransitionId`, whose defaults reproduce the previous `(elementId, ElementNamespaceIndex)` convention **exactly** — every stack-shipped and generator-emitted machine is unaffected, and there is a regression test asserting that. **Generated machines report their model namespace.** The generator now emits an `ElementNamespaceUri` override on `FiniteStateMachineType` subtypes, taken from the nearest type that actually *declares* state children — a subtype that only adds behaviour inherits its elements, and their namespace, from its base. **Ordering and validation fixes.** `WithSubStateMachine` and `WithInitialState` are now order-independent (previously, attaching a sub-SM before setting the initial state left the child suspended until the parent left and re-entered the state — silently). `WithSubStateMachine` validates `parentStateId`, and the builder rejects duplicate element browse names, since element NodeIds are now derived from them. ## A defect this surfaced Code that assembles nodes with the generated `CreateInstanceOf<Type>` factories never calls `NodeState.CreateAsPredefinedNode`, so `OnBeforeCreate` / `OnAfterCreate` are skipped for the entire subtree — and `OnAfterCreate` is the only place a state machine resolves its element namespace. It is also where `ConditionState` binds its `Enable` / `Disable` / `AddComment` handlers and `AlarmConditionState` binds the shelving methods, so the impact is broader than state machines. This PR fixes only the two call sites it depends on — DI's `SoftwareUpdateFacetWiring` and Robotics' `RoboticsOperationBuilder`. **The repository-wide audit is deliberately left out of scope and tracked in #4320** (24 files call these factories; none completed the lifecycle). The Robotics regression had no test coverage at all, so an assertion on `CurrentState/Id` was added and verified to fail without the fix. ## Breaking changes - Sub-state machines are **no longer browsable from the state-machine root**. Callers passing a machine's `ObjectId` to `GetSubStateMachineAsync` must pass a state NodeId instead — from `GetAvailableStatesAsync` or a snapshot's `CurrentStateId`. - `CurrentState/Id` for fluent machines changes from the numeric form to the materialized node's id. Code reading a numeric id out of it should call `FiniteStateMachineState.GetStateId` rather than parsing the identifier. - Generated machines qualify `CurrentState/Id` / `LastTransition/Id` with their companion-spec namespace instead of the OPC UA one. Documented in `docs/WhatsNewIn2.0.md` and `docs/StateMachines.md`. ## Notes for reviewers - Adding `virtual` to the `FiniteStateMachineState` members is a binary (not source) breaking change — assumed acceptable on the 2.0 line, but worth confirming against the compatibility policy. - Address-space cost is one node plus one property per declared state and transition, per machine instance; called out in the docs for servers instantiating many machines. - `AvailableTransitions` is modelled as a `HasComponent` `BaseDataVariable` (matching the standard NodeSet and what the client's browse path expects), not a Property. ## Related Issues - Fixes #3821 - Surfaced #4320 (node create lifecycle audit — not addressed here) ## Checklist - [ ] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [x] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [x] I have added all necessary documentation. - [x] I have verified that my changes do not introduce (new) build or analyzer warnings. - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [ ] I have addressed **all** PR feedback received. ### Test runs (net10.0) | Suite | Result | |---|---| | `Opc.Ua.Server.Tests` (full) | 4734 passed, 5 skipped | | `Opc.Ua.SourceGeneration.Core.Tests` | 3780 passed | | `Opc.Ua.SourceGeneration.Tests` | 132 passed | | `Opc.Ua.SourceGeneration.Stack.Tests` | 94 passed | | `Opc.Ua.Types.Tests` | 8763 passed | | `Opc.Ua.Robotics.Tests` | 540 passed | | `Opc.Ua.Robotics.Intent.Tests` | 22 passed | | `Opc.Ua.Di.Tests` | 424 passed | | `Opc.Ua.ISA95.Tests` | 136 passed | | `Opc.Ua.Aas.Tests` | 670 passed | | `Opc.Ua.Positioning.Tests` | 69 passed | | `Opc.Ua.Client.Tests` (StateMachines) | 36 passed | Only net10.0 was run locally; the .NET Framework leg is left to CI, hence the unchecked box above. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
293 lines
12 KiB
C#
293 lines
12 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Server.StateMachines;
|
|
|
|
namespace Opc.Ua.Server.Tests.StateMachines
|
|
{
|
|
/// <summary>
|
|
/// Unit tests for the <c>TransitionType</c> nodes that
|
|
/// <see cref="FluentFiniteStateMachineState"/> materializes for its
|
|
/// declared transitions — the Part 16 §4.4.11 counterpart to the
|
|
/// <c>StateType</c> nodes, which makes <c>LastTransition/Id</c>
|
|
/// resolve to a real node and populates <c>AvailableTransitions</c>.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("Server")]
|
|
[Category("StateMachines")]
|
|
[Parallelizable]
|
|
public sealed class StateMachineBuilderTransitionNodeTests
|
|
{
|
|
private ServerSystemContext m_context = null!;
|
|
|
|
[SetUp]
|
|
public void SetUp()
|
|
{
|
|
m_context = StateMachineTestFixtures.CreateContext();
|
|
}
|
|
|
|
[Test]
|
|
public void EveryDeclaredTransitionGetsATransitionTypeNode()
|
|
{
|
|
FluentFiniteStateMachineState sm = Build().StateMachine;
|
|
|
|
var offToOn = (BaseObjectState)GetChild(sm, "OffToOn");
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(offToOn.TypeDefinitionId,
|
|
Is.EqualTo(ObjectTypeIds.TransitionType));
|
|
Assert.That(offToOn.ReferenceTypeId,
|
|
Is.EqualTo(ReferenceTypeIds.HasComponent));
|
|
Assert.That(GetChild(sm, "OnToOff"), Is.Not.Null);
|
|
});
|
|
}
|
|
|
|
[Test]
|
|
public void TransitionNodeCarriesTransitionNumberProperty()
|
|
{
|
|
FluentFiniteStateMachineState sm = Build().StateMachine;
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(TransitionNumber(sm, "OffToOn"), Is.EqualTo(10u));
|
|
Assert.That(TransitionNumber(sm, "OnToOff"), Is.EqualTo(20u));
|
|
});
|
|
}
|
|
|
|
[Test]
|
|
public void TransitionNodeLinksItsFromAndToStates()
|
|
{
|
|
FluentFiniteStateMachineState sm = Build().StateMachine;
|
|
|
|
BaseInstanceState offToOn = GetChild(sm, "OffToOn");
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(Targets(offToOn, ReferenceTypeIds.FromState),
|
|
Is.EqualTo(new[] { GetChild(sm, "Off").NodeId }));
|
|
Assert.That(Targets(offToOn, ReferenceTypeIds.ToState),
|
|
Is.EqualTo(new[] { GetChild(sm, "On").NodeId }));
|
|
});
|
|
}
|
|
|
|
[Test]
|
|
public void StateNodesCarryTheInverseFromAndToStateReferences()
|
|
{
|
|
FluentFiniteStateMachineState sm = Build().StateMachine;
|
|
|
|
// Inverse-browsing FromState/ToState from a state node is
|
|
// how a §4.4.11 client discovers the state's transitions.
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(
|
|
InverseTargets(GetChild(sm, "Off"), ReferenceTypeIds.FromState),
|
|
Is.EqualTo(new[] { GetChild(sm, "OffToOn").NodeId }));
|
|
Assert.That(
|
|
InverseTargets(GetChild(sm, "On"), ReferenceTypeIds.ToState),
|
|
Is.EqualTo(new[] { GetChild(sm, "OffToOn").NodeId }));
|
|
});
|
|
}
|
|
|
|
private NodeId[] InverseTargets(BaseInstanceState node, NodeId referenceTypeId)
|
|
{
|
|
var references = new List<IReference>();
|
|
node.GetReferences(m_context, references, referenceTypeId, true);
|
|
return [.. references.Select(r =>
|
|
ExpandedNodeId.ToNodeId(r.TargetId, m_context.NamespaceUris))];
|
|
}
|
|
|
|
[Test]
|
|
public void HasEffectFollowsTheTransitionDeclaration()
|
|
{
|
|
FluentFiniteStateMachineState sm = StateMachineTestFixtures
|
|
.NewBuilder(m_context)
|
|
.AddState(1, "Off", isInitial: true)
|
|
.AddState(2, "On")
|
|
.AddTransition(10, "OffToOn", from: 1, to: 2)
|
|
.AddTransition(20, "OnToOff", from: 2, to: 1, hasEffect: false)
|
|
.StateMachine;
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(
|
|
Targets(GetChild(sm, "OffToOn"), ReferenceTypeIds.HasEffect),
|
|
Is.EqualTo(new[] { ObjectTypeIds.TransitionEventType }));
|
|
Assert.That(
|
|
Targets(GetChild(sm, "OnToOff"), ReferenceTypeIds.HasEffect),
|
|
Is.Empty);
|
|
});
|
|
}
|
|
|
|
[Test]
|
|
public void LastTransitionIsMaterializedAlongsideTheTransitions()
|
|
{
|
|
FluentFiniteStateMachineState sm = Build().StateMachine;
|
|
|
|
// Optional on FiniteStateMachineType, so nothing creates it
|
|
// by default — but without it the base class has nowhere to
|
|
// record a transition and clients have nothing to observe.
|
|
Assert.That(sm.LastTransition, Is.Not.Null);
|
|
Assert.That(sm.LastTransition!.BrowseName,
|
|
Is.EqualTo(new QualifiedName(BrowseNames.LastTransition)));
|
|
}
|
|
|
|
[Test]
|
|
public void LastTransitionIdResolvesToTheMaterializedNode()
|
|
{
|
|
FluentFiniteStateMachineState sm = Build()
|
|
.WithInitialState(1)
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, 10, 0, default, []);
|
|
|
|
Assert.That(sm.LastTransition!.Id!.Value,
|
|
Is.EqualTo(GetChild(sm, "OffToOn").NodeId));
|
|
}
|
|
|
|
[Test]
|
|
public void GetTransitionIdRoundTripsThroughGetTransitionNodeId()
|
|
{
|
|
FluentFiniteStateMachineState sm = Build().StateMachine;
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(sm.GetTransitionId(sm.GetTransitionNodeId(10)),
|
|
Is.EqualTo(10u));
|
|
Assert.That(sm.GetTransitionId(sm.GetTransitionNodeId(20)),
|
|
Is.EqualTo(20u));
|
|
Assert.That(sm.GetTransitionId(new NodeId("nonsense", 1)), Is.Zero);
|
|
});
|
|
}
|
|
|
|
[Test]
|
|
public void AvailableTransitionsListsTheMaterializedTransitionNodes()
|
|
{
|
|
FluentFiniteStateMachineState sm = Build().StateMachine;
|
|
|
|
Assert.That(sm.AvailableTransitions, Is.Not.Null);
|
|
NodeId[] published = [.. sm.AvailableTransitions!.Value];
|
|
|
|
Assert.That(published, Is.EqualTo(new[]
|
|
{
|
|
GetChild(sm, "OffToOn").NodeId,
|
|
GetChild(sm, "OnToOff").NodeId
|
|
}));
|
|
|
|
// The standard NodeSet models AvailableTransitions as a
|
|
// HasComponent BaseDataVariable, and that is the reference
|
|
// type GetAvailableTransitionsAsync translates the path with.
|
|
Assert.That(sm.AvailableTransitions.ReferenceTypeId,
|
|
Is.EqualTo(ReferenceTypeIds.HasComponent));
|
|
Assert.That(sm.AvailableTransitions.BrowseName,
|
|
Is.EqualTo(new QualifiedName(BrowseNames.AvailableTransitions)));
|
|
}
|
|
|
|
[Test]
|
|
public void WithCauseLinksTheMethodToEveryTransitionItTriggers()
|
|
{
|
|
var methodNodeId = new NodeId(7001u, 1);
|
|
|
|
StateMachineBuilder<FluentFiniteStateMachineState> builder = Build();
|
|
FluentFiniteStateMachineState sm = builder.StateMachine;
|
|
|
|
// A cause method has to be a child of the machine before
|
|
// WithCause can resolve it.
|
|
var start = new MethodState(sm)
|
|
{
|
|
ReferenceTypeId = ReferenceTypeIds.HasComponent,
|
|
NodeId = methodNodeId,
|
|
BrowseName = new QualifiedName("Start", 1),
|
|
DisplayName = new LocalizedText("Start"),
|
|
Executable = true,
|
|
UserExecutable = true
|
|
};
|
|
sm.AddChild(start);
|
|
|
|
builder.WithCause(methodNodeId);
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(Targets(GetChild(sm, "OffToOn"), ReferenceTypeIds.HasCause),
|
|
Is.EqualTo(new[] { methodNodeId }));
|
|
// The cause only maps to transition 10.
|
|
Assert.That(Targets(GetChild(sm, "OnToOff"), ReferenceTypeIds.HasCause),
|
|
Is.Empty);
|
|
|
|
// ... and the method carries the inverse edge, so
|
|
// inverse-browsing HasCause from the method finds the
|
|
// transition it triggers.
|
|
var inverse = new List<IReference>();
|
|
start.GetReferences(
|
|
m_context, inverse, ReferenceTypeIds.HasCause, true);
|
|
Assert.That(inverse, Has.Count.EqualTo(1));
|
|
Assert.That(inverse[0].TargetId,
|
|
Is.EqualTo((ExpandedNodeId)GetChild(sm, "OffToOn").NodeId));
|
|
});
|
|
}
|
|
|
|
private StateMachineBuilder<FluentFiniteStateMachineState> Build()
|
|
{
|
|
return StateMachineTestFixtures.NewBuilder(m_context)
|
|
.AddState(1, "Off", isInitial: true)
|
|
.AddState(2, "On")
|
|
.AddTransition(10, "OffToOn", from: 1, to: 2)
|
|
.AddTransition(20, "OnToOff", from: 2, to: 1)
|
|
.OnCause(7001, from: 1, transition: 10);
|
|
}
|
|
|
|
private BaseInstanceState GetChild(NodeState parent, string browseName)
|
|
{
|
|
var children = new List<BaseInstanceState>();
|
|
parent.GetChildren(m_context, children);
|
|
return children.Find(c => c.BrowseName.Name == browseName)!;
|
|
}
|
|
|
|
private NodeId[] Targets(BaseInstanceState node, NodeId referenceTypeId)
|
|
{
|
|
var references = new List<IReference>();
|
|
node.GetReferences(m_context, references, referenceTypeId, false);
|
|
return [.. references.Select(r =>
|
|
ExpandedNodeId.ToNodeId(r.TargetId, m_context.NamespaceUris))];
|
|
}
|
|
|
|
private uint TransitionNumber(NodeState sm, string transitionBrowseName)
|
|
{
|
|
var properties = new List<BaseInstanceState>();
|
|
GetChild(sm, transitionBrowseName).GetChildren(m_context, properties);
|
|
var number = (PropertyState<uint>)properties
|
|
.First(p => p.BrowseName.Name == BrowseNames.TransitionNumber);
|
|
return number.Value;
|
|
}
|
|
}
|
|
}
|