Source code for instro.opcua.device

"""Config-driven lifecycle for a synchronous OPC UA client."""

from __future__ import annotations

import enum
import logging
import typing
from contextlib import nullcontext
from os import getenv
from pathlib import Path
from threading import Thread
from time import time_ns
from typing import TYPE_CHECKING, Literal, Self
from urllib.parse import urlsplit

import pydantic
from typing_extensions import cast

from instro.lib import Instrument
from instro.lib.config import load_config
from instro.lib.publishers import Publisher
from instro.lib.types import Measurement

from .types import AttributeId, AttributePayload, AttributeValue, DataType, RelativePath, SecurityPolicy

if TYPE_CHECKING:
    from . import IdentityToken, Node, OpcUaClient, Subscription
else:
    from ._opcua import IdentityToken, Node, OpcUaClient, Subscription

logger = logging.getLogger(__name__)

_DEFAULT_SUBSCRIPTION_POLL_INTERVAL_MS = 1000.0
_DEFAULT_SUBSCRIPTION_QUEUE_SIZE = 2
_UINT32_FIELD = pydantic.Field(strict=True, ge=0, le=2**32 - 1)


class _ConfigModel(pydantic.BaseModel):
    model_config = pydantic.ConfigDict(extra="forbid", allow_inf_nan=False)


[docs] class OpcUaAnonymousAuth(_ConfigModel): """Connect without a user identity.""" mode: Literal["anonymous"] = "anonymous"
[docs] class OpcUaUsernameAuth(_ConfigModel): """Read a username identity's password from the environment at open time.""" mode: Literal["username"] = "username" username: str = pydantic.Field(min_length=1) password_env: str = pydantic.Field(min_length=1)
[docs] class OpcUaConnectionConfig(_ConfigModel): """Endpoint, user identity, and application security settings.""" endpoint_url: str authentication: OpcUaAnonymousAuth | OpcUaUsernameAuth = pydantic.Field( default_factory=OpcUaAnonymousAuth, discriminator="mode" ) security_mode: Literal["None", "Sign", "SignAndEncrypt"] = "None" security_policy: str = "None" pki_dir: Path | None = None certificate_path: Path | None = None private_key_path: Path | None = None request_timeout_s: float | None = pydantic.Field(default=None, gt=0, strict=True) @pydantic.field_validator("endpoint_url") @classmethod def _validate_endpoint(cls, value: str) -> str: endpoint = urlsplit(value) if endpoint.scheme != "opc.tcp" or not endpoint.hostname: raise ValueError("Expected an opc.tcp endpoint with a hostname") if endpoint.port == 0: raise ValueError("Endpoint port must be positive") return value @pydantic.model_validator(mode="after") def _validate_security(self) -> Self: unsecured = SecurityPolicy(self.security_policy) == SecurityPolicy.NONE if unsecured != (self.security_mode == "None"): raise ValueError("Use the None security policy and mode together") if isinstance(self.authentication, OpcUaUsernameAuth) and self.security_mode != "SignAndEncrypt": raise ValueError("Username authentication requires SignAndEncrypt") if (self.certificate_path is None) != (self.private_key_path is None): raise ValueError("Supply the application certificate and private key together") return self
class SamplingStrategy(enum.StrEnum): """The sampling method for the value of a node.""" SUBSCRIPTION = "subscription" POLL = "poll" class OpcUaSubscriptionConfig(_ConfigModel): """Monitor the Value attribute of all nodes configured on the device. All intervals are in milliseconds. If ``publishing_interval_ms`` is unset, it uses ``sampling_interval_ms``. A nonpositive publishing interval requests the fastest supported publishing interval. ``poll_interval_ms`` defaults to 1000 milliseconds for nodes with no recent notification. Set it to ``None`` to disable fallback reads. The device requests a queue of two notifications per monitored item by default. """ kind: Literal[SamplingStrategy.SUBSCRIPTION] = SamplingStrategy.SUBSCRIPTION sampling_interval_ms: float = pydantic.Field(strict=True) publishing_interval_ms: float | None = pydantic.Field(default=None, strict=True) poll_interval_ms: float | None = pydantic.Field(default=_DEFAULT_SUBSCRIPTION_POLL_INTERVAL_MS, gt=0, strict=True) lifetime_count: typing.Annotated[int, _UINT32_FIELD] | None = None max_keep_alive_count: typing.Annotated[int, _UINT32_FIELD] | None = None max_notifications_per_publish: typing.Annotated[int, _UINT32_FIELD] | None = None priority: int | None = pydantic.Field(default=None, strict=True, ge=0, le=255) publishing_enabled: bool | None = None queue_size: typing.Annotated[int, _UINT32_FIELD] = _DEFAULT_SUBSCRIPTION_QUEUE_SIZE discard_oldest: bool | None = None class OpcUaPollConfig(_ConfigModel): """Poll server for the value of an attribute of all nodes specified. Not implemented, for now. """ kind: Literal[SamplingStrategy.POLL] = SamplingStrategy.POLL
[docs] class OpcUaDeviceConfig(_ConfigModel): """Connection, named browse paths, and optional subscription settings.""" connection: OpcUaConnectionConfig nodes: dict[str, str] = pydantic.Field(default_factory=dict) sampling: OpcUaSubscriptionConfig | OpcUaPollConfig | None = pydantic.Field(default=None, discriminator="kind") @pydantic.field_validator("nodes") @classmethod def _validate_paths(cls, nodes: dict[str, str]) -> dict[str, str]: for name, path in nodes.items(): try: elements = RelativePath.parse(path).elements except ValueError as exc: raise ValueError(f"Invalid browse path for {name!r}: {exc}") from exc if not elements: raise ValueError(f"Node {name!r} needs a nonempty browse path") return nodes @pydantic.model_validator(mode="after") def _validate_sampling_nodes(self) -> Self: if self.sampling is not None and not self.nodes: raise ValueError("Sampling requires at least one configured node") return self
def _connect(config: OpcUaConnectionConfig) -> OpcUaClient: auth = config.authentication identity = None if isinstance(auth, OpcUaUsernameAuth): password = getenv(auth.password_env) if password is None: raise RuntimeError(f"Environment variable {auth.password_env!r} is unset") identity = IdentityToken.user_name(auth.username, password) return OpcUaClient.connect( config.endpoint_url, identity=identity, security_mode=config.security_mode, security_policy=config.security_policy, pki_dir=config.pki_dir, certificate_path=config.certificate_path, private_key_path=config.private_key_path, request_timeout_s=config.request_timeout_s, ) def _publishable_scalar(value: object) -> bool | int | float | str: if not isinstance(value, (int, float, str)): raise TypeError("OPC UA publication requires a boolean, integer, float, or string") if isinstance(value, int) and value != float(value): raise ValueError("OPC UA publication cannot represent this integer exactly as a float") return value
[docs] class OpcUaDevice(Instrument): """Own a configured OPC UA client and publish samples from a configured subscription.""" def __init__( self, name: str, config: OpcUaDeviceConfig | dict[str, object] | Path | str, publishers: list[Publisher] | None = None, *, autostart: bool = False, ) -> None: """Validate a config and initialize the device. Args: name (str): Instrument name. config (OpcUaDeviceConfig | dict[str, object] | Path | str): Config model, mapping, or JSON file path. publishers (list[Publisher] | None): Publishers owned by the instrument. autostart (bool): Open the connection and start any configured subscription during construction. Examples: >>> with OpcUaDevice("line_1", "line_1.json") as device: ... sample = device.client.get_node("/Objects/2:Setpoint").value """ # A caller can mutate a Pydantic model or its nested fields after validation. self._config = load_config( config.model_dump() if isinstance(config, OpcUaDeviceConfig) else config, OpcUaDeviceConfig ) self._client: OpcUaClient | None = None self._sampling: tuple[Subscription, Thread] | None = None super().__init__(name, publishers=publishers) if autostart: self.open() @property def client(self) -> OpcUaClient: """Return the client for the open device. Raises: RuntimeError: The device has not opened or has closed. """ if self._client is None: raise RuntimeError("Call open() before accessing the OPC UA client") return self._client
[docs] def open(self) -> None: """Connect and start publishing data, if configured. Browse paths are resolved in configuration order, with translation requests split as needed to fit the client's decoded array limit. """ if self._client is not None: if self._sampling is None or self._sampling[1].is_alive(): return subscription, _ = self._sampling client = self._client self._client = self._sampling = None try: with client: subscription.close() except Exception: logger.warning("Failed to clean up the stopped OPC UA session for %s", self.name, exc_info=True) options = self._config.sampling if isinstance(options, OpcUaPollConfig): raise NotImplementedError("Standalone OPC UA polling is not implemented") client = _connect(self._config.connection) try: nodes = client._resolve_nodes(self._config.nodes.values()) self._client = client if options is not None: self._start_subscription(client, nodes, options) except BaseException: self._client = None # The native context preserves the binding exception if disconnect also fails. with client: raise
def _start_subscription(self, client: OpcUaClient, nodes: list[Node], options: OpcUaSubscriptionConfig) -> None: publishing_interval_ms = options.publishing_interval_ms if publishing_interval_ms is None: publishing_interval_ms = options.sampling_interval_ms subscription = client.subscribe( nodes, publishing_interval_ms, poll_interval_ms=options.poll_interval_ms, **options.model_dump(exclude={"kind", "publishing_interval_ms", "poll_interval_ms"}, exclude_none=True), ) worker = None try: worker = Thread( target=self._publish_subscription, args=(subscription,), name=f"{self.name}-opcua", daemon=True ) worker.start() except BaseException: try: with subscription: raise finally: if worker is not None and worker.ident is not None: worker.join() self._sampling = (subscription, cast(Thread, worker)) def _publish_subscription(self, subscription: Subscription) -> None: try: for node, sample in subscription: try: self.publish(self._sample_measurement(node, sample)) except Exception: logger.exception("Failed to publish an OPC UA sample for %s", node.browse_path.relative_path) except Exception: logger.exception("OPC UA subscription for %s stopped", self.name) else: if self._client is not None: logger.error("OPC UA subscription for %s stopped unexpectedly", self.name) def _sample_measurement(self, node: Node, sample: AttributeValue[AttributePayload]) -> Measurement: if not sample.status.is_good: raise ValueError(f"Cannot publish OPC UA sample with status {sample.status.name()}") value = _publishable_scalar(sample.value) timestamp = sample.source_unix_timestamp if timestamp is None: timestamp = sample.server_unix_timestamp if timestamp is None: timestamp = time_ns() return self._package_measurement(str(node.browse_path.relative_path), value, timestamp)
[docs] def read(self, node_or_path: str | RelativePath | Node) -> Measurement: """Read a node's Value attribute and publish one measurement. Use the source timestamp when available, then the server timestamp, then the local receipt time. Args: node_or_path (str | RelativePath | Node): Rooted browse path or node from this client. Returns: Measurement: The published sample with a Unix timestamp in nanoseconds. Raises: ValueError: The node belongs to another client, the sample has non-Good quality, or the integer value would lose precision. TypeError: The sample value cannot be published as a scalar. """ node = self.client._resolve_node(node_or_path) measurement = self._sample_measurement(node, node.value) self.publish(measurement) return measurement
[docs] def write( self, node_or_path: str | RelativePath | Node, value: bool | int | float | str, *, dtype: DataType | None = None ) -> None: """Publish a command and write the node's Value attribute. Publication records intent before submission. A rejected write still raises, and a publisher error prevents submission. Args: node_or_path (str | RelativePath | Node): Rooted browse path or node from this client. value (bool | int | float | str): Scalar value to write and publish. dtype (DataType | None): Wire type override for the write. Raises: ValueError: The node belongs to another client or the integer value would lose precision. TypeError: The value cannot be published as a scalar. OpcUaError: The server rejects the write or the session fails. """ value = _publishable_scalar(value) node = self.client._resolve_node(node_or_path) channel = f"{node.browse_path.relative_path}.cmd" self.publish(self._package_command(channel, value, time_ns())) node.set_attribute(AttributeId.VALUE, value, dtype=dtype)
[docs] def close(self) -> None: """Drain subscription samples, close publishers, and disconnect the client.""" client, self._client = self._client, None sampling, self._sampling = self._sampling, None with client if client is not None else nullcontext(): try: if sampling is not None: subscription, worker = sampling try: subscription.close() finally: worker.join() finally: super().close()
def __enter__(self) -> Self: """Open and return this device.""" self.open() return self