# Description Follow-up to the AutoID companion (#4825). Two changes to where the AutoID server places its readers: 1. **`IAutoIdReaderBuilder.WithParent` is made conformant with OPC 10000-100 4.9.** Until now it placed a reader below another node *instead of* `DeviceSet`, and the docs suggested "a component of a machine" as the use case. A machine in the Machinery `Machines` folder is not reachable from `DeviceSet`, so such a reader could not be located from `DeviceSet`, which DI 4.9 requires for every `ComponentType` instance (every AutoID device type derives from DI `DeviceType`). Now the reader is still placed below the parent (`HasComponent`, unchanged), and: - when `DeviceSet` already reaches the parent through hierarchical references (for example another reader, or any device it organizes), nothing else is added: the reader is a component of a composed device and DI 4.9 wants "only the root instance" referenced from `DeviceSet`; - otherwise `DeviceSet` also organizes the reader (`Organizes`, both directions), so it stays locatable. 2. **New opt-in `IAutoIdReaderBuilder.AsComponentOf(BaseObjectState machine)`**, available only when AutoID is composed with Machinery (`AddAutoIdToMachinery`, or a DI owner that loads the Machinery model). It makes the reader an identifiable component of the machine per OPC 40001-1 11: - the reader is placed below the machine's `Components` add-in (`HasComponent`, as `MachineComponentsType` declares for `<Component>`); - it gets the `2:Identification` add-in (`HasAddIn`) typed `MachineryComponentIdentificationType`, which holds no copies: it references the reader's own DI nameplate properties with `HasProperty` (`Manufacturer`, `SerialNumber`, and those of `Model`, `ManufacturerUri`, `ProductCode`, `HardwareRevision`, `SoftwareRevision`, `DeviceRevision`, `DeviceClass`, `ProductInstanceUri` that are set, plus `AssetId`/`ComponentName` when published; `DeviceManual` and `RevisionCounter` are left out as 40001-1 10.2 recommends); - the reader stays a device: the same `DeviceSet` rule as for `WithParent` applies with `Components` as the parent, so in the usual case (a machine in `Machines` that `DeviceSet` does not reach) `DeviceSet` organizes it directly. It is not added to `Machines`. - Checked before anything is registered, each failing with `Bad_ConfigurationError` and a message naming the way out: the server has no Machinery model (names `AddAutoIdToMachinery`), the machine is not a node of the AutoID owner, the machine has no `Components` add-in (names `WithComponents`), or the reader nameplate lacks `Manufacturer` and/or `SerialNumber` (mandatory in `MachineryItemIdentificationType`). `WithParent` and `AsComponentOf` exclude each other (`InvalidOperationException`). Default behaviour is unchanged: a reader built without `WithParent`/`AsComponentOf` is organized by `DeviceSet` and not added to `Machines`. Rollback on failure covers the new references: a failed build removes the `DeviceSet` reference, the component and its add-in, so the name can be used again. ## Specification basis | Statement | Source | | --- | --- | | "The DeviceSet Object is the starting point to locate Devices. It shall either directly or indirectly reference all instances of a subtype of ComponentType with a Hierarchical Reference. For complex Devices that are composed of various components that are also Devices, only the root instance shall be referenced from the DeviceSet Object. The components of such complex Devices shall be locatable by following Hierarchical References from the root instance." | OPC 10000-100 (DI) 1.05.0, 4.9 | | AutoID device types are "Subtype of DeviceType defined in OPC 10000-100". OPC 30010 does not mention `DeviceSet`, Machinery or `Machines`. | OPC 30010 (AutoID) 1.01, 6.1 Table 7 | | "Each Machine providing this building block provides the Components Object, which directly references all identifiable components of a Machine." / "Note: That does not preclude that a Machine is organizing its components in various other hierarchies as well." | OPC 40001-1 (Machinery) 1.04.2, 11.1 | | "The MachineComponentsType provides HasComponent References to all identifiable components of a Machine"; Table 27: `0:HasComponent Object <Component> 0:BaseObjectType OP`; Table 28: `<Component> 0:HasAddIn Object 2:Identification MachineryItemIdentificationType M`; "As all identifiable components shall contain the Identification Object". | OPC 40001-1 1.04.2, 11.2 | | `MachineryItemIdentificationType`: `2:Manufacturer` M, `2:SerialNumber` M, all other members O. | OPC 40001-1 1.04.2, 8.3 Table 16 | | `MachineryComponentIdentificationType` is the component subtype of `MachineryItemIdentificationType` (adds `2:DeviceRevision`); "It is not recommended to use the optional Properties 2:RevisionCounter and 2:DeviceManual"; a missing component `2:ProductInstanceUri` "shall be omitted". | OPC 40001-1 1.04.2, 10.2 | | "it is recommended to keep this approach and let several References lead to the same Node, rather than duplicating the Node" / Robotics example: identification Properties "are only referenced from the Identification functional group". | OPC 40001-1 1.04.2, 7.3 and Annex B.2 (informative) | | "It is expected that domain-specific companion specifications using this specification will define what assets of the domain in what usage are considered to be Machines or components of Machines." | OPC 40001-1 1.04.2, 11.1 (Note) | | Organizes "can be used to span multiple hierarchies"; more than one hierarchical path to a Node is allowed. | OPC 10000-3 1.05, 7.11, 7.5 | **SDK decisions** (not specified by OPC 30010, which predates Machinery): - A reader is never added to `Machines`: no specification classifies an AutoID device as a machine (40001-1 11.1 leaves that to the domain specifications, AutoID is silent). - A reader becomes a component of a machine only when the application asks for it (`AsComponentOf`). - `WithParent` keeps its parent and adds the `DeviceSet` reference rather than rejecting parents outside `DeviceSet` (see below). - The component `Identification` references the reader's nameplate instead of copying it. - AutoID does not add Machinery conformance units; the Machinery owner advertises them for what its builders created. ### Why `WithParent` adds a reference instead of rejecting DI 4.9 asks for reachability, not for a particular parent, and OPC 10000-3 allows several hierarchical paths to one node. Adding `Organizes` from `DeviceSet` satisfies the "shall" while keeping the parent the application asked for, and it is the same reference type `DeviceSet` already uses for every reader (and the DI node manager for every device). Rejecting such parents with `Bad_ConfigurationError` would break existing callers that hang a reader below a machine or folder. When `DeviceSet` already reaches the parent, no reference is added, so the "only the root instance" rule of 4.9 holds for composed devices. Reachability is decided once when the reader is built, by following the forward hierarchical references of the owner's nodes. ### Why `AsComponentOf` keeps the reader referenced from `DeviceSet` Machinery does not require machines to be in `DeviceSet` (the stock builders put them in `Machines` only), so a reader that is only below `Components` would again be unreachable from `DeviceSet`. The same reachability rule as for `WithParent` applies: if the machine is itself reachable from `DeviceSet` (for example a machine that is also a DI device organized by `DeviceSet`), the reader is reached through it and gets no direct reference, otherwise `DeviceSet` organizes it. ### Shape of `AsComponentOf` It takes the machine's `BaseObjectState`, like `WithParent(NodeState)` and `IMachineryBuildContext.BindMachine(TState, ...)`; with the stock builders that is `IMachineHandle<TState>.State`. It requires the machine's `Components` add-in to exist (`IMachineBuilder.WithComponents`, or a companion-declared one bound with `WithComponents(components, ...)`) instead of creating one, so the Machinery builders stay the only place that creates Machinery building blocks (`MachineryBuildingBlocks` organization, facets). The reader's NodeState parent is the `Components` object, so the DI node manager attaches it with `HasComponent` and the existing registration and rollback code applies unchanged. ## Behaviour change for existing callers - `WithParent(parent)` with a parent that `DeviceSet` does not reach (for example a machine in `Machines`, or an application folder): the reader is now *also* browsable from `DeviceSet` (one extra `Organizes` reference, both directions), and an `AutoIdClient.EnumerateReadersAsync()` (which browses `DeviceSet`) now finds it. Its parent, NodeId and `HasComponent` reference are unchanged. - `WithParent(parent)` with a parent `DeviceSet` reaches (for example another reader): unchanged. - Default placement: unchanged. - `IAutoIdReaderBuilder` gains a member. The interface is implemented only inside the package (instances come from `AutoIdRuntime.Reader`), and the package is new in 2.0. ## Changes - `src/Opc.Ua.AutoID.Server/AutoIdReaderPlacement.cs` (new, internal): `DeviceSet` lookup, the reachability check, the `Organizes` reference and its removal, `Components` resolution and validation, the nameplate check, and the `Identification` add-in. - `src/Opc.Ua.AutoID.Server/AutoIdRuntime.cs`: the builder's nameplate delegate runs once (validated before anything is registered, then copied into the DI builder); `AsComponentOf` resolves `Components` as the parent before the device is created; after registration the add-in is added and the `DeviceSet` reference kept; rollback removes the reference. - `src/Opc.Ua.AutoID.Server/Builders/IAutoIdReaderBuilder.cs`, `AutoIdReaderBuilder.cs`: `AsComponentOf`, mutual exclusion with `WithParent`, XML docs stating the exact behaviour. - `docs/AutoID.md`: new "Placement" subsection under "Hosting readers" (what DI 4.9 and Machinery 11 require, what is an SDK decision, a table per builder call, an example), the composition table rows for readers and `Machines`, the test fixture table. `src/Opc.Ua.AutoID.Server/NugetREADME.md`: a short paragraph. - Tests (below). ## Tests - `AutoIdReaderLifecycleTests` (stand-alone owner): `ReadersCanHangBelowAnExplicitParentAsync` now also asserts that `DeviceSet` does not organize a reader below another reader; `AReaderBelowAParentOutsideTheDeviceSetIsStillOrganizedByItAsync`; `AFailedCreationBelowAnOutsideParentLeavesNoDeviceSetReferenceAsync` (rollback); `AStandaloneReaderCannotBeAComponentOfAMachineAsync` (`Bad_ConfigurationError` naming `AddAutoIdToMachinery`); argument checks for `AsComponentOf(null)` and both call orders of `WithParent`/`AsComponentOf`. - `AutoIdCompositionTests` (Machinery owner, in process): `AReaderBecomesAComponentOfAMachineAndStaysADeviceAsync` (parent is `Components`, `HasComponent`, `DeviceSet` organizes it, `Machines` does not, `Identification` with `HasAddIn` and the component type, `HasProperty` to the reader's own `Manufacturer`/`SerialNumber`/`Model` nodes, no `DeviceManual`, owned subtree); `AComponentNeedsAMachineWithComponentsAndRegistersNothingOtherwiseAsync`; `AComponentNeedsTheMandatoryIdentificationAsync`; `AComponentNeedsAMachineOfTheOwnerAsync`; `AFailedComponentCreationIsRolledBackAsync`. - `AutoIdPlacementEndToEndTests` (new, hosted Machinery + AutoID over a real session): a default reader, a reader below that reader, a reader `AsComponentOf` a machine and a reader `WithParent` the machine. Browsing `DeviceSet` finds the three roots and not the nested reader, the outer reader reaches the nested one; `MachineryClient.DiscoverMachinesAsync` returns only the machine and `Machines` contains no reader; `MachineryClient.EnumerateComponentsAsync` lists only the component reader, `ReadIdentificationAsync` reads `Manufacturer`, `SerialNumber`, `ProductCode` through the add-in, which is `HasAddIn`-referenced and typed `MachineryComponentIdentificationType` and whose `HasProperty` targets are the reader's own nameplate nodes; `AutoIdClient.EnumerateReadersAsync` finds the three roots. - The existing default assertions (`TheReadersShareTheDeviceSetWithThePumpAndStayOutOfTheMachinesFolderAsync`, `TheMachineryAndPumpsClientsStillFindTheirInstancesAsync`, `ComposedReadersLiveBelowTheSharedDeviceSetAsync`) are unchanged. - Fail-without: with the runtime wiring reverted to master (builder surface kept so the tests compile), 10 of the new tests fail: all `AsComponentOf` cases, both `WithParent` cases outside `DeviceSet` and the three session tests that look for the component or the extra `DeviceSet` reference. Removing only the rollback of the `DeviceSet` reference makes both rollback tests fail. `NoReaderBecomesAMachineAsync` and the existing default tests pass with and without the change, as intended. Local results (macOS arm64, SDK 10.0.402, head `238ed9b69` on master `9bfc780e1`; the same three commits are now based on master `ac24123dd` as `c6d70909b`, no AutoID file changed in between): `Opc.Ua.AutoID.Tests` net10.0 318/318 passed; `Opc.Ua.AutoID.Server` all TFMs and the test project with `CustomTestTarget=net48` build with 0 warnings, 0 errors (net48 tests run on Windows CI; there is no mono host here). `dotnet format whitespace/style/analyzers --verify-no-changes` on the changed files: no new findings beyond the conventions of the surrounding test files. ## Commits 1. `fix(autoid): keep every reader reachable from DeviceSet` 2. `feat(autoid): make a reader a component of a machine` 3. `docs(autoid): document where readers are placed` The branch is based on OPCFoundation/master `ac24123dd` (#4852, the last master commit with a green build). Fork CI was not repeated on this head: earlier fork runs of this branch failed only in test projects outside this PR (the master build was broken by the NUnit 5 migration #4840 and fixed in #4852; master is currently broken again in `Opc.Ua.Core.Tests` by #4849). The upstream checks of this PR test it against the current master. ## Related Issues - Follow-up to #4825 (tracking issue #4824). - #4823 (open) edits prose in other paragraphs of `docs/AutoID.md` (table of contents, the DI-owner paragraph, providers). This PR adds a subsection and changes two rows of the composition table and one row of the test table; no hunk overlaps. The table of contents is deliberately not touched here because #4823 adds the subsection entries for "Hosting readers"; the "Placement" entry can be added there or after both are merged. ## Checklist - [x] 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. (Local build of the changed projects: 0 warnings, 0 errors.) - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. (Locally the AutoID test project on net10.0; net48 is built but runs only on Windows CI.) - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. (Pending the upstream checks; see the CI note above.) - [x] I have addressed **all** PR feedback received. --------- Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
32 KiB
AutoID Devices
The AutoID packages implement OPC 30010 OPC UA for AutoID Devices (release 1.01, 2020-06-18): RFID readers, OCR readers, optical (barcode) readers and verifiers, and real-time locating systems (RTLS), with their scan results, tag access methods and diagnostics events.
| Package | What it adds |
|---|---|
Opc.Ua.AutoID |
The information model: node states, DataTypes, identifiers, encodeables and client proxies |
Opc.Ua.AutoID.Server |
Reader hosting on the Device Integration node manager, a provider contract for the reader hardware, the OPC 30010 methods and events, simulated readers |
Opc.Ua.AutoID.Client |
Reader discovery, typed scan and tag calls, device snapshots and an asynchronous stream of events |
Opc.Ua.Mcp.AutoID |
Nine bounded MCP tools; no tool changes a tag |
The AutoID sample runs a simulated RFID reader end to end.
Contents
- Model and dependencies
- What the model package contains
- Loading the model
- Scan data and scan results
- Hosting readers
- Providers
- Behavior of the methods
- Events
- Conformance
- Client
- MCP tools
- Sample
- Specification notes
- Provenance
Model and dependencies
| Item | Value |
|---|---|
| Package | OPCFoundation.NetStandard.Opc.Ua.AutoID |
| Model URI | http://opcfoundation.org/UA/AutoID/ |
| Model version | 1.01, published 2020-06-18 |
| Required models | OPC UA 1.03, Device Integration 1.01 (lower bounds) |
| Generated CLR namespace | Opc.Ua.AutoID |
| Source | UA-Nodeset latest/AutoID |
AutoIdDeviceType derives from the DI DeviceType, so the package references
Opc.Ua.Di and loads the DI model the stack ships, which is newer than the
required 1.01.
What the model package contains
- The device types
AutoIdDeviceType(abstract),RfidReaderDeviceType,OcrReaderDeviceType,OpticalReaderDeviceType,OpticalVerifierDeviceTypeandRtlsDeviceType, with their methods (Scan,ScanStart,ScanStop,ReadTag,WriteTag,WriteTagID,KillTag,LockTag,SetTagPassword,GetLocation, ...) as typed method states. - The event types
AutoIdScanEventTypewith one subtype per reader kind,AutoIdDiagnosticsEventType,AutoIdAccessEventType,RfidAccessEventType,AutoIdLogEntryEventTypeandAutoIdPresenceEventType. - The DataTypes: the
ScanDataandLocationunions, the abstractScanResultwithRfidScanResult,OcrScanResult,OpticalScanResult,OpticalVerifierScanResultandRtlsLocationResult, the access resultsAccessResultandRfidAccessResult,ScanSettings,RfidSighting,ScanDataEpc, the coordinate structures and six enumerations. AutoIdModel(model identity,GetNamespaceUris()) and theAddAutoIdTypeSystemregistration overloads.
The scan event subtypes and RfidAccessEventType narrow the DataType of their
ScanResult or AccessResult property to a structure subtype. The generated
states expose the property with that type, for example
RfidScanEventState.ScanResult is a
PropertyState<ArrayOf<RfidScanResult>>.
Loading the model
using Opc.Ua;
using Opc.Ua.AutoID;
// Encodeables (DI and AutoID); the caller commits the builder.
messageContext.Factory.Builder.AddAutoIdTypeSystem().Commit();
// Type nodes for a node manager's predefined nodes.
var predefinedNodes = new NodeStateCollection();
predefinedNodes.AddAutoIdTypeSystem(systemContext);
// Typed node states for instances of the AutoID types.
nodeStateFactory.AddAutoIdTypeSystem();
AddAutoIdTypeSystem loads DI before AutoID, registers missing namespaces and
skips roots that are already present, so it can be combined with other models
that also load DI.
Scan data and scan results
ScanData is a union: SwitchField selects the ByteString, String,
Epc or Custom arm. The scan and access results have optional fields;
set the corresponding bits in EncodingMask to send them.
var result = new RfidScanResult
{
CodeType = "EPC",
ScanData = new ScanData
{
SwitchField = ScanDataFields.Epc,
Epc = new ScanDataEpc { PC = 0x3000, UId = ByteString.From(epc) }
},
Timestamp = DateTimeUtc.Now,
Sighting = [new RfidSighting { Antenna = 1, Strength = -52 }]
};
The NodeSet defines binary and XML encodings; JSON uses the DataType NodeIds.
Hosting readers
A server has one Device Integration DeviceSet, and exactly one node manager
owns the DI namespace. Readers are therefore hosted in one of two ways:
AddAutoIdregisters a node manager of its own that loads the DI and AutoID models and creates one device per reader belowDeviceSet. Use it when AutoID is the only DI-based companion of the server.AddAutoIdToMachineryloads the AutoID model into the Machinery node manager ofAddMachinery, which then owns DI for every companion of the server; the readers are created in that manager, below the sameDeviceSetas the machines, pumps or scales. See Coexisting with a server that already owns DI.
using Microsoft.Extensions.DependencyInjection;
using Opc.Ua.AutoID.Server;
services.AddOpcUa()
.AddServer(options => { /* application name, endpoints, PKI */ })
.AddAutoId(options => options.MaximumScanDuration = TimeSpan.FromSeconds(10))
.ConfigureAutoId(async context =>
{
AutoIdReader reader = await context.Runtime
.Reader(new QualifiedName("DockDoor1", context.Manager.InstanceNamespaceIndex), hardware)
.WithDeviceInfo("Dock door antenna portal")
.WithDeviceLocationName("Dock 1, gate A")
.WithAntennaNames([new AntennaNameIdPair { AntennaId = 1, AntennaName = "Left post" }])
.WithIdentification(nameplate => nameplate.SerialNumber = "R100-0001")
.BuildAsync(context.CancellationToken);
});
Reader(...) returns a builder; nothing is registered before BuildAsync.
The builder materialises exactly the components the provider supports (a reader
without a Scan provider has no Scan method), registers the device, makes it
an event notifier and attaches the provider. A failure at any step is rolled
back, so the browse name can be used again, a provider the build owns
(OwnsProvider()) is disposed, and concurrent builds of one name admit exactly
one. Disposing the runtime (the node manager does so on shutdown)
stops every reader's scans, detaches its provider and, for a provider the reader
owns (OwnsProvider()), disposes it.
AutoIdServerOptions bounds what a client can ask for:
| Option | Default | Effect |
|---|---|---|
MaximumScanDuration |
30 s | A synchronous Scan asking for more is Bad_InvalidArgument; a provider that does not return in time is cancelled and the call fails with Bad_Timeout |
MaximumTagReadLength |
65536 | A longer ReadTag is Bad_InvalidArgument |
MaximumScanResults |
1000 | More results fail the scan with Bad_ResponseTooLarge instead of being truncated |
PublishAccessEvents |
true |
Whether commands that reach a tag raise access events |
AdditionalNamespaceUris |
none | Extra namespaces to register |
The readers keep their scan state (Idle_0, Scanning_2, Busy_3, Error_1)
in DeviceStatus. AutoIdReader.SetFaultedAsync(true) reports Error_1: new
scans then return DEVICE_NOT_READY_17 and an active asynchronous scan stops.
SetDeviceLocation moves the DeviceLocation of a mobile reader.
Coexisting with a server that already owns DI
AddAutoId claims the Device Integration address space like AddOpcUaDi,
AddMachinery, AddPumps or AddScales, so registering it together with
another DI owner, in either order, throws InvalidOperationException while the
services are registered; the message names the current owner and the
composition API. The check is what keeps the address space consistent: two DI
owners would each load their own copy of DeviceSet, the server would route
DeviceSet to the first one, and readers created in the second one would not
be browsable.
To host readers next to machines, call AddAutoIdToMachinery after
AddMachinery and create the readers with ConfigureAutoIdFor<TNodeManager>.
Other Machinery-based companions compose into the same owner:
using Microsoft.Extensions.DependencyInjection;
using Opc.Ua;
using Opc.Ua.AutoID.Server;
using Opc.Ua.Machinery.Server;
services.AddOpcUa()
.AddServer(options => { /* application name, endpoints, PKI */ })
.AddMachinery(options =>
{
options.Parts = MachineryParts.BuildingBlocks;
options.InstanceNamespaceUri = "urn:acme:plant:instances";
})
.AddPumpsToMachinery() // optional, any *ToMachinery companion
.AddAutoIdToMachinery(options => options.MaximumScanDuration = TimeSpan.FromSeconds(10))
.ConfigureMachinery(async (machinery, ct) =>
{
await machinery.AddMachine(new QualifiedName("Press1", machinery.InstanceNamespaceIndex))
.WithIdentification(id =>
{
id.Manufacturer = new LocalizedText("Acme");
id.SerialNumber = "PR-1";
id.ProductInstanceUri = "urn:acme:press:1";
})
.BuildAsync(ct);
})
.ConfigureAutoIdFor<MachineryNodeManager>(async (context, ct) =>
{
AutoIdReader reader = await context.Runtime
.Reader(new QualifiedName("PressInfeed", context.Runtime.InstanceNamespaceIndex), hardware)
.WithDeviceInfo("Infeed portal of Press1")
.BuildAsync(ct);
});
| Item | In the composed server |
|---|---|
| Node managers | The MachineryNodeManager alone; no AutoIdNodeManager is created |
Device Integration model, DeviceSet |
Loaded once by the Machinery owner's core model provider |
| AutoID model | Added to the owner by AutoIdMachineryModelProvider, with AdditionalNamespaceUris |
| Readers | Below the owner's DeviceSet (Organizes), NodeIds in MachineryServerOptions.InstanceNamespaceUri; take browse names from context.Runtime.InstanceNamespaceIndex. WithParent and AsComponentOf place a reader elsewhere and keep it reachable from DeviceSet, see Placement |
Machines folder |
Readers are devices, not machines, and are not added to it; AsComponentOf makes one a component of a machine |
| Methods, events, providers | As in the stand-alone server; the readers are event notifiers of the owner |
| Conformance | The runtime contributes the AutoID units and facets to the owner, which publishes them with the DI and Machinery ones |
| Lifetime | The owner disposes the runtime on shutdown: scans stop, providers detach, owned providers are disposed |
Successive ConfigureAutoIdFor<MachineryNodeManager> delegates run in
registration order in the Machinery configuration pipeline, before its builder
is sealed, and share one AutoIdRuntime; context.Manager is the Machinery
owner. ConfigureAutoIdFor<AutoIdNodeManager> works with AddAutoId and
receives the stand-alone runtime, so configuration code can be shared by both
hosting paths. Opc.Ua.AutoID.Server references Opc.Ua.Machinery.Server for
this; a stand-alone server still loads only the DI and AutoID models.
Placement
OPC 30010 does not say where readers live in the address space; the rules come from the specifications it builds on.
| Rule | Source |
|---|---|
"The DeviceSet Object is the starting point to locate Devices. It shall either directly or indirectly reference all instances of a subtype of ComponentType with a Hierarchical Reference." Every AutoID device type derives from DI DeviceType, a ComponentType. |
OPC 10000-100 1.05.0 4.9; OPC 30010 6.1 |
| "For complex Devices that are composed of various components that are also Devices, only the root instance shall be referenced from the DeviceSet Object." | OPC 10000-100 1.05.0 4.9 |
The Components object of a machine "directly references all identifiable components of a Machine", with HasComponent, and each component carries the 2:Identification add-in (HasAddIn) whose Manufacturer and SerialNumber are mandatory. |
OPC 40001-1 1.04.2 11.1, 11.2 (Tables 27, 28), 8.3 |
Machinery and DI place no requirement on each other: a machine need not be in DeviceSet, and a device need not be in Machines. |
OPC 40001-1 1.04.2, OPC 10000-100 1.05.0 |
The SDK applies them as follows:
| Builder call | Where the reader is | Reference from DeviceSet |
|---|---|---|
| none (default) | Below DeviceSet |
Organizes |
WithParent(parent), DeviceSet reaches parent (for example another reader) |
Below parent (HasComponent) |
None: the reader is a component of a composed device whose root DeviceSet references |
WithParent(parent), DeviceSet does not reach parent |
Below parent (HasComponent) |
Organizes, added by the runtime |
AsComponentOf(machine) |
Below the machine's Components (HasComponent), with an Identification add-in |
As for WithParent with the Components object as parent: usually Organizes, because a machine in Machines is not necessarily reachable from DeviceSet |
Whether DeviceSet reaches the parent is decided when the reader is built, by
following the forward hierarchical references of the owner's nodes. A child
attached by a non-hierarchical reference, such as a condition by HasCondition,
is no path from DeviceSet.
Where OPC 30010 is silent, these are SDK decisions: a reader is not added to the
Machines folder, because no specification classifies an AutoID device as a
machine (OPC 40001-1 11.1 leaves that to the domain specifications), and a
reader is a component of a machine only when the application asks for it.
AsComponentOf needs AutoID composed into the Machinery owner
(AddAutoIdToMachinery or a DI owner that loads the Machinery model) and a
machine of that owner that publishes the Components add-in, here built with
WithComponents. The runtime takes the add-in the machine's
MachineryBuildingBlocks folder references with HasAddIn (OPC 40001-1 7.1),
so a container a companion model declares and WithComponents(existing, ...)
binds is found below whatever parent and with whatever browse name it keeps; a
machine without that folder offers its MachineComponentsType child:
IMachineHandle<BaseObjectState>? press = null;
builder
.ConfigureMachinery(async (machinery, ct) =>
press = await machinery.AddMachine(new QualifiedName("Press1", machinery.InstanceNamespaceIndex))
.WithIdentification(id =>
{
id.Manufacturer = new LocalizedText("Acme");
id.SerialNumber = "PR-1";
id.ProductInstanceUri = "urn:acme:press:1";
})
.WithComponents(_ => { })
.BuildAsync(ct))
.ConfigureAutoIdFor<MachineryNodeManager>(async (context, ct) =>
await context.Runtime
.Reader(new QualifiedName("PressInfeed", context.Runtime.InstanceNamespaceIndex), hardware)
.AsComponentOf(press!.State)
.WithIdentification(nameplate =>
{
nameplate.Manufacturer = new LocalizedText("Acme");
nameplate.SerialNumber = "R100-0001";
})
.BuildAsync(ct));
The reader gets the 2:Identification add-in typed
MachineryComponentIdentificationType. It holds no copies: it references the
reader's own DI nameplate properties with HasProperty. This follows the
approach of OPC 40001-1 7.3 ("let several References lead to the same Node,
rather than duplicating the Node") and of the Robotics example in Annex B.2,
whose identification Properties "are only referenced from the Identification
functional group". It references
Manufacturer, SerialNumber and those of Model, ManufacturerUri,
ProductCode, HardwareRevision, SoftwareRevision, DeviceRevision,
DeviceClass and ProductInstanceUri that are set, plus AssetId and
ComponentName when the reader publishes them; DeviceManual and
RevisionCounter are left out as OPC 40001-1 10.2 recommends. A missing
Manufacturer or SerialNumber, a machine of another node manager, a machine
without Components or with more than one, or a server without the Machinery
model fail the build with
Bad_ConfigurationError before anything is registered. WithParent and
AsComponentOf exclude each other. The runtime does not add Machinery
conformance units; the Machinery owner advertises them for what its builders
created.
Direct composition and lifetime
Without dependency injection, pass new AutoIdMachineryModelProvider() together
with new MachineryModelProvider(MachineryParts.BuildingBlocks) to the
MachineryNodeManager constructor; providers are dependency-ordered even if
supplied in another order. Once the address space is created:
AutoIdRuntime autoId = owner.CreateAutoIdRuntime();
AutoIdReader reader = await autoId.CreateReaderAsync(
new QualifiedName("PressInfeed", autoId.InstanceNamespaceIndex), hardware, ct);
The first CreateAutoIdRuntime(options) call selects the options; later calls
return the same runtime, and on an AutoIdNodeManager it returns its Runtime.
The stand-alone AutoIdNodeManager is built from the same pieces: a Device
Integration owner that loads DI and then AutoIdMachineryModelProvider.
Any other Device Integration owner composes AutoID the same way, as with
Pumps or Scales: an application-owned DiNodeManager subclass loads the model in
its LoadPredefinedNodesAsync with nodes.AddAutoIdTypeSystem(context), which
keeps DI nodes that are already present, calls CreateAutoIdRuntime() (or is
configured through ConfigureAutoIdFor<TOwner>), and disposes the runtime
through DisposeMachineryResourcesAsync() from its asynchronous disposal.
AddAutoIdToMachinery is the registration shortcut for the stock owner's
model-provider pipeline; the plain AddOpcUaDi owner loads only DI and has no
such pipeline, so a server built on it uses the subclass route.
Providers
A reader is the OPC UA face of a hardware provider. The base contract
IAutoIdReaderProvider (kind, attach, detach) is enough for a device that scans
on its own (OPC 30010 6.1.1 option 3): the provider reports through the
IAutoIdReaderSink it receives when attached. Capabilities are added by
implementing more interfaces:
| Interface | Methods it enables |
|---|---|
IAutoIdScanProvider |
Scan |
IAutoIdAsyncScanProvider |
ScanStart, ScanStop |
IAutoIdRfidProvider (SupportedOperations) |
ReadTag, WriteTag, WriteTagID, KillTag, LockTag, SetTagPassword, each only when listed |
IAutoIdRtlsProvider |
GetLocation, GetSupportedLocationTypes |
The sink pushes ReportScanAsync (scan event and LastScanData),
CompleteScanAsync (a termination condition ended the asynchronous scan),
ReportPresenceAsync, ReportLogEntryAsync and ReportAccessAsync. Provider
calls are made without any runtime lock held, scans never overlap on one reader,
and the sink throws ObjectDisposedException after the reader was disposed.
Four simulated providers ship in the package and back the tests and the sample:
InMemoryRfidReaderProvider (an EPC Gen2 reader with memory banks, passwords,
locks and kill), InMemoryScanReaderProvider (OCR and optical),
InMemoryOpticalVerifierProvider and InMemoryRtlsProvider. Their scan cycle
defaults to one second (CycleInterval), so an unbounded ScanStart raises at
most one scan event per second; pass a cycleInterval to the constructor for
another pace. InMemoryRtlsProvider stores each object's location in the type it
was registered with. A locationConverter translates it into the other supported
types, for example from the local coordinate system the system was configured
with (OPC 30010 9.3.4) into WGS84:
// A site whose local origin is at 48 N 11 E, X pointing east and Y north, in metres.
var rtls = new InMemoryRtlsProvider(locationConverter: (location, type) =>
type == LocationTypeEnumeration.WGS84 && location.SwitchField == LocationFields.Local
? new Location
{
SwitchField = LocationFields.WGS84,
WGS84 = new WGS84Coordinate
{
N_S_Hemisphere = "N",
Latitude = 48.0 + (location.Local.Y / 111_320.0),
E_W_Hemisphere = "E",
Longitude = 11.0 + (location.Local.X / 74_600.0)
}
}
: null);
Without a converter, or when it returns null, GetLocation for another type
answers Bad_InvalidState.
Behavior of the methods
| Method | Result codes and semantics |
|---|---|
Scan (6.1.3.4) |
Bad_InvalidArgument for an infinite scan (duration 0, cycles 0, no DataAvailable), a negative or non-finite value, an undefined location type or a duration above the limit; Bad_InvalidState while another scan is active. The first result becomes LastScanData/LastScanTimestamp with one source timestamp |
ScanStart (6.1.3.5) |
Infinite settings allowed; Bad_InvalidState while a scan is active. The scan stops through ScanStop, when the provider completes it, when the starting session closes, or at shutdown |
ScanStop (6.1.3.6) |
Bad_InvalidState when no scan is active; any session may stop a scan |
ReadTag, WriteTag, WriteTagID, KillTag, LockTag, SetTagPassword |
A malformed identifier, empty code type, over-long read or undefined enumeration is Bad_InvalidArgument. Everything the tag decides (PASSWORD_ERROR_4, OUT_OF_RANGE_ERROR_7, ...) is returned in Status with a good call result |
GetDeviceLocation (6.1.3.7) |
Available when a location is configured. Same mapping as GetLocation: an undefined location type is Bad_InvalidArgument, a location that is not available in the requested type Bad_InvalidState. 6.1.3.7 lists only the Call Service codes of OPC 10000-4 5.12.2, where Bad_NotSupported would mean the method is not supported for the object; 5.12.2.4 allows reusing a code with the same canonical meaning |
GetLocation, GetSupportedLocationTypes (6.6.3) |
The result carries the location in the requested type. An unsupported location type is Bad_InvalidArgument, an unknown object Bad_NotFound, and a supported type the object's location is not available in Bad_InvalidState (6.6.3.2: not available, for example due to the configuration) |
A method the provider does not support is not instantiated; calling it fails with the stack's status for an unpublished method.
Events
Scan results are raised as the scan event of the reader kind
(RfidScanEventType, OcrScanEventType, OpticalScanEventType,
OpticalVerifierScanEventType, RtlsLocationEventType) with DeviceName and
the typed ScanResult array. AutoIdPresenceEventType and
AutoIdLogEntryEventType come from the sink. Commands that reached an
identifier (a scan with results, and each tag command except those answering
NO_IDENTIFIER_8, MULTIPLE_IDENTIFIERS_9, NOT_SUPPORTED_BY_DEVICE_15,
DEVICE_NOT_READY_17, INVALID_CONFIGURATION_18 or DEVICE_FAULT_20) raise
RfidAccessEventType on RFID readers and AutoIdAccessEventType otherwise, with
Client, Command and the access results. Client names the client
application that originated the command (OPC 30010 6.1.3.3 and 7.10): the
application name of the client description the session was created with, else
its application URI, else OPC UA client. The results of an asynchronous scan
name the client that called ScanStart; scans the device reports on its own name
AutoID device.
Generic ReadTag and WriteTag access events do not automatically broadcast tag
memory. The injected RFID provider may also implement IAutoIdRfidAccessEventPolicy
to approve an entire (codeType, region, offset, length) byte range as non-secret
telemetry. Missing, rejected or failing classifications omit both RWData and
CodeTypeRWData, including their encoding-mask bits; identifiers and command
metadata remain available. Unsuccessful operations and empty results omit data.
EPC Gen2 reserved-bank ranges overlapping password bytes 0 through 7 are always
omitted, even if a policy approves them. The in-memory EPC provider approves
ordinary banks 1 through 3 and never approves the reserved bank.
This projection does not redact an authorized caller's direct ReadTag result,
change provider arguments, or disable access events. Password-management commands
never include passwords in their access events. Applications whose existing RFID
providers need ordinary memory in events must opt in through this provider policy;
only approve known layouts and never credential-bearing or unclassified memory.
Conformance
The runtime contributes the OPC 30010 conformance units and server facets (Tables 82 to 85) of the readers it hosts; a facet is advertised only when a reader implements all its mandatory units.
| Unit | Implemented when |
|---|---|
AutoID DeviceType |
A reader exists |
AutoID Simple Sync Access |
A reader exists (LastScanData is updated by every scan) |
AutoID Sync Access |
A reader has a Scan method |
AutoID Async Access |
A reader exists (scan events) |
AutoID Async Access Control |
A reader has ScanStart and ScanStop |
The Simple Sync, Base Sync and Base Async facets are advertised
accordingly. AutoID Simple Sync Access Control (the ScanActive variable and
the ScanSettings function group) and AutoID Device Parameters (the
RuntimeParameters group) are not implemented, so the Full AutoID Server Facet
is never advertised. DeviceInfo, DeviceLocation, DeviceLocationName and
AntennaNames are published when configured.
Client
Opc.Ua.AutoID.Client wraps the generated ObjectType proxies:
using Opc.Ua.AutoID.Client;
AutoIdClient autoId = session.AutoId(telemetry); // or AddAutoIdClient() in DI
await foreach (AutoIdReaderEntry reader in autoId.EnumerateReadersAsync())
{
AutoIdDeviceSnapshot device = await autoId.ReadDeviceAsync(reader);
AutoIdScanResponse scan = await autoId.ScanAsync(
reader, new ScanSettings { Duration = 1000, DataAvailable = true });
}
await foreach (AutoIdScanEventTypeRecord e in
autoId.ObserveScanEventsAsync(session.DefaultStreaming, reader, ct))
{
// e.ScanResult holds RfidScanResult, OcrScanResult, ... instances
}
Discovery finds the devices whose type derives from one of the five concrete
reader types. A browse the server rejects throws ServiceResultException rather
than yielding an empty list, a rejected method call throws with the server's
status, and every asynchronous member honours cancellation. The status a device
reports for a tag command is returned as data. AutoIdReadOptions narrows
the Read of ReadDeviceAsync: Default reads everything the device publishes,
StatusOnly reads DeviceStatus and DeviceName. Every ReadDeviceAsync call
costs one Browse of the children of the device (and BrowseNext only when the
server pages the result) and one Read, whatever the options. The snapshot
carries the NodeIds of DeviceStatus, LastScanData, LastScanTimestamp and
DeviceLocation and the browse names of the methods the device publishes, taken
from that browse. RefreshDeviceAsync takes such a snapshot and reads
DeviceStatus, LastScanData, LastScanTimestamp and DeviceLocation again
through these NodeIds: one Read of up to four variables and no Browse. The client
keeps no state, so a poller reads once and then refreshes the snapshot:
| Call | Network cost |
|---|---|
ReadDeviceAsync(reader) |
One Browse, one Read of every published variable |
ReadDeviceAsync(reader, AutoIdReadOptions.StatusOnly) |
One Browse, one Read of two variables |
RefreshDeviceAsync(snapshot) |
One Read of up to four variables, no Browse |
AutoIdDeviceSnapshot device = await autoId.ReadDeviceAsync(reader, AutoIdReadOptions.StatusOnly);
if (device.HasMethod(BrowseNames.ScanStart))
{
// monitor device.DeviceStatusId and device.LastScanDataId, then start the scan
}
device = await autoId.RefreshDeviceAsync(device); // poll without browsing
RefreshDeviceAsync copies every other member of the snapshot, including
Methods, and does not check the snapshot against the server. When the snapshot
no longer matches the device (the device or one of its variables was deleted, or
the server assigned other NodeIds after a restart), the status of the Read
surfaces: a bad status for DeviceStatus, for example BadNodeIdUnknown, is
thrown as ServiceResultException, and a bad status for LastScanData is
returned in LastScanStatus with a null value. The caller then reads the device
again with ReadDeviceAsync, which also picks up optional variables and methods
published after the snapshot was taken.
Observe*Async methods (scan, access, presence and log entry events) take a
streaming subscription the caller owns; the monitored item lives as long as the
enumeration.
MCP tools
AddOpcUaMcpAutoId() and WithOpcUaAutoIdTools(McpToolProfile.AutoId) (profile
autoid) add autoid_list_readers, autoid_read_device, autoid_scan,
autoid_scan_start, autoid_scan_stop, autoid_observe_scan_events,
autoid_read_tag, autoid_get_supported_location_types and
autoid_get_location. No tool writes, locks or kills a tag or carries a
password. See the MCP server guide.
Sample
samples/AutoID contains AutoIdServer, a dock door with
a simulated RFID portal whose pallets enter and leave the antenna field, and
AutoIdClient, which discovers the reader, scans, reads and writes tag memory
and prints the scan and presence events. Test-AutoIdSamplePair.ps1 runs both
and checks the output.
Specification notes
- OPC 30010 6.1.3.16 prescribes the
AutoIdModelVersionstring"1.00"although the released model is 1.01; the server publishes"1.00". - The NodeSet orders the
GetLocationarguments identifier, location type, code type; the specification text orders them identifier, code type, location type. The generated proxy and the server follow the NodeSet. - The NodeSet declares the
Scanmethod ofOpticalVerifierDeviceTypewithWGS84Coordinateresults where OPC 30010 6.4.3.1 namesOpticalVerifierScanResult. The method cannot be served consistently, so a verifier does not publishScan; it reports throughScanStartand scan events, andAutoIdClient.ScanAsyncrefuses a verifier. - The
GetUnitsmethod ofRtlsDeviceTypedeclares no output argument; it is not published.
Provenance
src/Opc.Ua.AutoID/Model holds the unmodified NodeSet and identifier table
from UA-Nodeset revision 9f6c7660b94af24d32c4248d4b13bf60adab0301;
provenance.json records the source URLs and SHA-256 hashes. The published
identifier table predates model 1.01 and lacks 67 NodeSet declarations, so
Opc.Ua.AutoID.Derived.NodeIds.csv is generated from it with
tools/nodesets/derive-identifier-table.py and used as the source generator's
drift guard. NodeIds always come from the NodeSet.
The AutoID tests pin the file hashes, compare the generated identifiers with the NodeSet and the identifier table, load the model with DI, and round-trip the DataTypes through the binary, JSON and XML encodings.
| Fixture | Covers |
|---|---|
AutoIdHostingTests |
AddAutoId registration, DI ownership, options, node manager and client factories |
AutoIdCompositionTests |
Stock Machinery owner, ordered providers, DI loaded once, instance ownership, rollback, cancellation, runtime disposal, a second DI owner rejected |
AutoIdMachineryCompositionEndToEndTests |
Machinery, Pumps and AutoID in one hosted server, read back by the AutoID, Machinery and Pumps clients over a real session, with the published profiles and conformance units |
AutoIdPlacementEndToEndTests |
Reader placement over a real session: every reader reachable from DeviceSet, only roots organized by it, a reader as a component of a machine with its Identification, no reader in Machines |
AutoIdReaderEndToEndTests |
The stand-alone server driven by AutoIdClient over a real session |