OpenSMI-Server 0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- opensmi/server/__init__.py +45 -0
- opensmi/server/_server.py +454 -0
- opensmi/server/access_control.py +257 -0
- opensmi/server/base_callable.py +137 -0
- opensmi/server/base_feasibility_check.py +18 -0
- opensmi/server/base_machine.py +90 -0
- opensmi/server/base_machinery_item.py +447 -0
- opensmi/server/base_method.py +57 -0
- opensmi/server/base_precondition_check.py +20 -0
- opensmi/server/base_skill.py +299 -0
- opensmi/server/base_startup_skill.py +111 -0
- opensmi/server/common.py +93 -0
- opensmi/server/config.py +124 -0
- opensmi/server/interfaces.py +280 -0
- opensmi/server/lock.py +347 -0
- opensmi/server/mixins/__init__.py +22 -0
- opensmi/server/mixins/lockable_mixin.py +37 -0
- opensmi/server/mixins/notification_mixins.py +78 -0
- opensmi/server/mixins/parent_mixin.py +79 -0
- opensmi/server/mixins/requirements_mixin.py +77 -0
- opensmi/server/mixins/skill_logic_mixins.py +470 -0
- opensmi/server/mixins/spatial_object_mixin.py +88 -0
- opensmi/server/mixins/ua_object_container_mixins.py +131 -0
- opensmi/server/mixins/ua_variable_container_mixins.py +294 -0
- opensmi/server/nodesets/Opc.Ua.Di.NodeSet2.xml +5719 -0
- opensmi/server/nodesets/Opc.Ua.Machinery.NodeSet2.xml +1713 -0
- opensmi/server/nodesets/Opc.Ua.RSL.NodeSet2.xml +601 -0
- opensmi/server/nodesets/Opc.Ua.SmartFactory.MachineSet.NodeSet2.xml +2886 -0
- opensmi/server/nodesets/Opc.Ua.SmartFactory.SkillSet.NodeSet2.xml +856 -0
- opensmi/server/nodesets/__init__.py +26 -0
- opensmi/server/nodesets/di.py +74 -0
- opensmi/server/nodesets/machinery.py +36 -0
- opensmi/server/nodesets/rsl.py +31 -0
- opensmi/server/nodesets/smart_factory_machine_set.py +52 -0
- opensmi/server/nodesets/smart_factory_skill_set.py +32 -0
- opensmi/server/notification.py +112 -0
- opensmi/server/protocols.py +165 -0
- opensmi/server/resource.py +104 -0
- opensmi/server/spatial_object.py +328 -0
- opensmi/server/ua_fsm.py +261 -0
- opensmi/server/ua_object.py +212 -0
- opensmi/server/ua_object_containers.py +181 -0
- opensmi/server/ua_variable.py +450 -0
- opensmi/server/ua_variable_containers.py +331 -0
- opensmi/server/user.py +154 -0
- opensmi_server-0.1.dist-info/METADATA +239 -0
- opensmi_server-0.1.dist-info/RECORD +50 -0
- opensmi_server-0.1.dist-info/WHEEL +5 -0
- opensmi_server-0.1.dist-info/licenses/LICENSES/MIT.txt +18 -0
- opensmi_server-0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 OpenSMI Contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""Server implementation of Skill-based Production using OPC-UA."""
|
|
6
|
+
|
|
7
|
+
from importlib import metadata
|
|
8
|
+
|
|
9
|
+
from opensmi.server import mixins as mixins
|
|
10
|
+
from opensmi.server._server import Server as Server
|
|
11
|
+
from opensmi.server.access_control import AccessControl as AccessControl
|
|
12
|
+
from opensmi.server.base_callable import BaseCallable as BaseCallable
|
|
13
|
+
from opensmi.server.base_machine import BaseMachine as BaseMachine
|
|
14
|
+
from opensmi.server.base_machinery_item import BaseComponent as BaseComponent
|
|
15
|
+
from opensmi.server.base_machinery_item import BaseMachineryItem as BaseMachineryItem
|
|
16
|
+
from opensmi.server.base_method import BaseMethod as BaseMethod
|
|
17
|
+
from opensmi.server.base_skill import BaseSkill as BaseSkill
|
|
18
|
+
from opensmi.server.lock import Lock as Lock
|
|
19
|
+
from opensmi.server.mixins.skill_logic_mixins import BaseSkillFinalResultData as BaseSkillFinalResultData
|
|
20
|
+
from opensmi.server.mixins.skill_logic_mixins import ContinuousSkillLogicMixin, FiniteSkillLogicMixin
|
|
21
|
+
from opensmi.server.resource import Resource as Resource
|
|
22
|
+
from opensmi.server.spatial_object import SpatialObject as SpatialObject
|
|
23
|
+
from opensmi.server.ua_fsm import UaFiniteStateMachine as UaFiniteStateMachine
|
|
24
|
+
from opensmi.server.ua_object import UaObject as UaObject
|
|
25
|
+
from opensmi.server.ua_object_containers import Components as Components
|
|
26
|
+
from opensmi.server.ua_object_containers import MethodSet as MethodSet
|
|
27
|
+
from opensmi.server.ua_object_containers import Resources as Resources
|
|
28
|
+
from opensmi.server.ua_object_containers import SkillSet as SkillSet
|
|
29
|
+
from opensmi.server.ua_variable import UaVariable as UaVariable
|
|
30
|
+
from opensmi.server.ua_variable_containers import Attributes as Attributes
|
|
31
|
+
from opensmi.server.ua_variable_containers import FinalResultData as FinalResultData
|
|
32
|
+
from opensmi.server.ua_variable_containers import Monitoring as Monitoring
|
|
33
|
+
from opensmi.server.ua_variable_containers import ParameterSet as ParameterSet
|
|
34
|
+
from opensmi.server.user import User as User
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class BaseSkillFinite(FiniteSkillLogicMixin, BaseSkill):
|
|
38
|
+
"""Abstract base class for finite skills with behavior implemented in Python."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BaseSkillContinuous(ContinuousSkillLogicMixin, BaseSkill):
|
|
42
|
+
"""Abstract base class for continuous skills with behavior implemented in Python."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
__version__ = metadata.version("OpenSMI-Server")
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 OpenSMI Contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
# Note: Due to Python import conflict, this file is named `_server.py` instead of `server.py`
|
|
8
|
+
import asyncio
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
import warnings
|
|
12
|
+
from collections.abc import AsyncGenerator, Iterator
|
|
13
|
+
from enum import IntEnum, auto
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, Self
|
|
16
|
+
|
|
17
|
+
import asyncua
|
|
18
|
+
import structlog
|
|
19
|
+
from asyncua import ua
|
|
20
|
+
from asyncua.common.node import Node
|
|
21
|
+
from asyncua.common.structures104 import new_enum
|
|
22
|
+
from asyncua.crypto.cert_gen import generate_private_key, generate_self_signed_app_certificate
|
|
23
|
+
from asyncua.server.address_space import AddressSpace
|
|
24
|
+
from asyncua.server.history_sql import HistorySQLite
|
|
25
|
+
from asyncua.server.server import Server as UaServer
|
|
26
|
+
from opensmi.core import AsyncTaskMixin, LifecycleState, setup_logging
|
|
27
|
+
from opensmi.core.base_server import BaseServer
|
|
28
|
+
from opensmi.core.lifecycle_mixin import LifecycleMixin, lifecycle
|
|
29
|
+
from opensmi.core.protocols import NamespaceProvider
|
|
30
|
+
from opensmi.core.repr_mixin import ReprStrMixin
|
|
31
|
+
from opensmi.core.ua_node_util import get_child_without_ns
|
|
32
|
+
from typing_extensions import TypeVar, override
|
|
33
|
+
|
|
34
|
+
from opensmi.server.config import HistoryOption, ServerConfiguration, UaServerConfiguration
|
|
35
|
+
from opensmi.server.nodesets import NODE_SETS, SmartFactoryMachineSetNodeIds
|
|
36
|
+
from opensmi.server.ua_object import UaObject
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from opensmi.server import BaseMachine
|
|
40
|
+
from opensmi.server.access_control import AccessControl
|
|
41
|
+
|
|
42
|
+
_MachineType = TypeVar("_MachineType", bound="BaseMachine", default="BaseMachine")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _FixedHistorySQLite(HistorySQLite):
|
|
46
|
+
@override
|
|
47
|
+
def _get_table_name(self, node_id: ua.NodeId) -> str:
|
|
48
|
+
if node_id.NodeIdType == ua.NodeIdType.String:
|
|
49
|
+
return f"{node_id.NamespaceIndex}_{node_id.Identifier}" # repr creates invalid ' character
|
|
50
|
+
return f"{node_id.NamespaceIndex}_{node_id.Identifier!r}"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _create_key_and_certificate(config: UaServerConfiguration) -> None:
|
|
54
|
+
from cryptography import x509
|
|
55
|
+
from cryptography.hazmat._oid import ExtendedKeyUsageOID
|
|
56
|
+
from cryptography.hazmat.primitives import serialization
|
|
57
|
+
|
|
58
|
+
# Generate new key
|
|
59
|
+
key = generate_private_key()
|
|
60
|
+
with open(config.private_key, "wb") as f:
|
|
61
|
+
f.write(
|
|
62
|
+
key.private_bytes(
|
|
63
|
+
encoding=serialization.Encoding.PEM,
|
|
64
|
+
format=serialization.PrivateFormat.TraditionalOpenSSL,
|
|
65
|
+
encryption_algorithm=serialization.NoEncryption(),
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# Generate new self-signed certificate based on that key
|
|
70
|
+
cert = generate_self_signed_app_certificate(
|
|
71
|
+
private_key=key,
|
|
72
|
+
common_name=config.name,
|
|
73
|
+
names={},
|
|
74
|
+
subject_alt_names=[x509.UniformResourceIdentifier(config.namespace_uri)],
|
|
75
|
+
extended=[ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH],
|
|
76
|
+
days=3650,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
with open(config.certificate, "wb") as f:
|
|
80
|
+
f.write(cert.public_bytes(serialization.Encoding.DER))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ServerState(IntEnum):
|
|
84
|
+
"""Operating states of the `Server`."""
|
|
85
|
+
|
|
86
|
+
STOPPED = auto()
|
|
87
|
+
STARTING = auto()
|
|
88
|
+
RUNNING = auto()
|
|
89
|
+
STOPPING = auto()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Server(
|
|
93
|
+
AsyncTaskMixin,
|
|
94
|
+
LifecycleMixin,
|
|
95
|
+
ReprStrMixin,
|
|
96
|
+
BaseServer[UaObject],
|
|
97
|
+
):
|
|
98
|
+
_ua_machines: Node
|
|
99
|
+
|
|
100
|
+
_access_control: AccessControl
|
|
101
|
+
_ua_server: UaServer
|
|
102
|
+
_ua_address_space: AddressSpace
|
|
103
|
+
|
|
104
|
+
def __init__(self, *, config_path: str | Path | None = None) -> None:
|
|
105
|
+
super().__init__()
|
|
106
|
+
|
|
107
|
+
self._machines: list[BaseMachine] = []
|
|
108
|
+
self._state = ServerState.STOPPED
|
|
109
|
+
self._ua_enums: dict[type[IntEnum], ua.NodeId] = {}
|
|
110
|
+
"""Maps created custom enums to OPC UA type nodes."""
|
|
111
|
+
if config_path:
|
|
112
|
+
self.load_config(config_path)
|
|
113
|
+
else:
|
|
114
|
+
self._config: ServerConfiguration = ServerConfiguration()
|
|
115
|
+
|
|
116
|
+
def load_config(self, path: str | Path) -> None:
|
|
117
|
+
"""Load configuration from given ``path``."""
|
|
118
|
+
if self.lifecycle_state != LifecycleState.NEW:
|
|
119
|
+
msg = "Cannot configure server after initialization!"
|
|
120
|
+
raise RuntimeError(msg)
|
|
121
|
+
|
|
122
|
+
from opensmi.core.config import load_dataclass
|
|
123
|
+
|
|
124
|
+
self._config = load_dataclass(ServerConfiguration, path)
|
|
125
|
+
|
|
126
|
+
@lifecycle
|
|
127
|
+
async def _life_cycle(self) -> AsyncGenerator[None]:
|
|
128
|
+
await self._init()
|
|
129
|
+
yield
|
|
130
|
+
await self._shutdown()
|
|
131
|
+
|
|
132
|
+
async def _init(self) -> None:
|
|
133
|
+
import opensmi.core
|
|
134
|
+
|
|
135
|
+
import opensmi.server
|
|
136
|
+
|
|
137
|
+
setup_logging(log_levels=self.config.logging.minimum_levels, log_format=self.config.logging.format)
|
|
138
|
+
self._logger = structlog.stdlib.get_logger("opensmi.Server")
|
|
139
|
+
self.logger.info(
|
|
140
|
+
"Initializing server...",
|
|
141
|
+
version_opensmi_server=opensmi.server.__version__,
|
|
142
|
+
version_opensmi_core=opensmi.core.__version__,
|
|
143
|
+
version_asyncua=asyncua.__version__,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
from .access_control import AccessControl, AccessControlAttributeService, AccessControlMethodService
|
|
147
|
+
|
|
148
|
+
self._access_control = AccessControl(server=self)
|
|
149
|
+
|
|
150
|
+
self._ua_server = UaServer(user_manager=self._access_control)
|
|
151
|
+
ua_iserver = self.ua_server.iserver
|
|
152
|
+
self._ua_address_space = ua_iserver.aspace
|
|
153
|
+
|
|
154
|
+
ua_iserver.method_service = AccessControlMethodService(ua_iserver.aspace)
|
|
155
|
+
ua_iserver.attribute_service = AccessControlAttributeService(aspace=ua_iserver.aspace, server=self)
|
|
156
|
+
|
|
157
|
+
await self._setup_ua_server()
|
|
158
|
+
|
|
159
|
+
# Import Nodeset (and its required nodesets)
|
|
160
|
+
await self.ua_import_nodeset(SmartFactoryMachineSetNodeIds)
|
|
161
|
+
|
|
162
|
+
self._ua_machines = await get_child_without_ns(self._ua_server.nodes.objects, display_name="Machines")
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def logger(self) -> structlog.stdlib.BoundLogger:
|
|
166
|
+
"""Return the logger instance of the server. Read-only property."""
|
|
167
|
+
return self._logger
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def access_control(self) -> AccessControl:
|
|
171
|
+
return self._access_control
|
|
172
|
+
|
|
173
|
+
async def ua_import_xml(self, path: Path) -> int:
|
|
174
|
+
"""Import XML nodeset from given ``path``. Returns the namespace index on success."""
|
|
175
|
+
time_start = time.monotonic()
|
|
176
|
+
nodes = await self.ua_server.import_xml(path) # type: ignore
|
|
177
|
+
idx = nodes[0].NamespaceIndex
|
|
178
|
+
namespace_array = await self.ua_server.get_namespace_array()
|
|
179
|
+
uri: str = namespace_array[idx]
|
|
180
|
+
self.logger.info(
|
|
181
|
+
"Imported nodes from XML node set!",
|
|
182
|
+
file_name=path.name,
|
|
183
|
+
uri=uri,
|
|
184
|
+
ns_idx=idx,
|
|
185
|
+
no_of_nodes=len(nodes),
|
|
186
|
+
elapsed=time.monotonic() - time_start,
|
|
187
|
+
)
|
|
188
|
+
return idx
|
|
189
|
+
|
|
190
|
+
async def ua_import_nodeset(self, uri: str | type[NamespaceProvider]) -> int:
|
|
191
|
+
"""Import the OPC UA XML nodeset specified by the given ``uri`` and return the namespace index.
|
|
192
|
+
|
|
193
|
+
Automatically loads all required nodesets beforehand.
|
|
194
|
+
|
|
195
|
+
:raises KeyError: If given URI is unknown.
|
|
196
|
+
"""
|
|
197
|
+
if not isinstance(uri, str):
|
|
198
|
+
uri = uri.URI
|
|
199
|
+
|
|
200
|
+
index = self._namespace_map.get(uri)
|
|
201
|
+
if index is not None:
|
|
202
|
+
return index
|
|
203
|
+
|
|
204
|
+
namespace = NODE_SETS[uri]
|
|
205
|
+
for uri in namespace.REQUIRED_URIS: # import all requirements first (transitive)
|
|
206
|
+
await self.ua_import_nodeset(uri)
|
|
207
|
+
|
|
208
|
+
index = await self.ua_import_xml(Path(__file__).parent / "nodesets" / namespace.FILE_NAME)
|
|
209
|
+
|
|
210
|
+
# update our namespace mapping
|
|
211
|
+
for ns_idx, namespace in enumerate(await self.ua_server.get_namespace_array()):
|
|
212
|
+
self._namespace_map[namespace] = ns_idx
|
|
213
|
+
|
|
214
|
+
return index
|
|
215
|
+
|
|
216
|
+
async def _setup_ua_server(self) -> None:
|
|
217
|
+
config: UaServerConfiguration = self.config.ua_server
|
|
218
|
+
# Configure server to use sqlite as history database (default is a simple memory dict)
|
|
219
|
+
if config.history_db == HistoryOption.SQLITE:
|
|
220
|
+
db_path = Path("./data/opcua_history.sql")
|
|
221
|
+
db_path.parent.mkdir(exist_ok=True)
|
|
222
|
+
self._ua_server.iserver.history_manager.set_storage(_FixedHistorySQLite(db_path)) # pyright: ignore[reportArgumentType]
|
|
223
|
+
self.logger.info("History storage via SQLite!", path=str(db_path))
|
|
224
|
+
|
|
225
|
+
if config.encryption:
|
|
226
|
+
self.logger.info("Encryption enabled!")
|
|
227
|
+
try:
|
|
228
|
+
await self._ua_server.load_certificate(config.certificate)
|
|
229
|
+
await self._ua_server.load_private_key(config.private_key)
|
|
230
|
+
self.logger.info("Loaded existing encryption key and certificate!")
|
|
231
|
+
except FileNotFoundError:
|
|
232
|
+
self.logger.info("Creating new encryption key and certificate...")
|
|
233
|
+
_create_key_and_certificate(config)
|
|
234
|
+
|
|
235
|
+
await self._ua_server.load_certificate(config.certificate)
|
|
236
|
+
await self._ua_server.load_private_key(config.private_key)
|
|
237
|
+
|
|
238
|
+
await self._ua_server.init()
|
|
239
|
+
|
|
240
|
+
if self.config.debug:
|
|
241
|
+
self.logger.warning("DEBUG mode enabled!")
|
|
242
|
+
asyncio.get_event_loop().set_debug(True)
|
|
243
|
+
warnings.simplefilter("always", ResourceWarning)
|
|
244
|
+
warnings.simplefilter("always", DeprecationWarning)
|
|
245
|
+
|
|
246
|
+
self._ua_server.set_endpoint(config.endpoint_address)
|
|
247
|
+
self._ua_server.set_server_name(config.name)
|
|
248
|
+
await self._ua_server.set_application_uri(config.namespace_uri) # always namespace index 1
|
|
249
|
+
|
|
250
|
+
# TODO? SecurityPolicy "None" shall be disabled when Encryption is available according to OPC UA spec
|
|
251
|
+
# https://profiles.opcfoundation.org/profile/762
|
|
252
|
+
if not config.encryption:
|
|
253
|
+
self._ua_server.set_security_policy([ua.SecurityPolicyType.NoSecurity])
|
|
254
|
+
self._ua_server.set_identity_tokens([ua.UserNameIdentityToken])
|
|
255
|
+
|
|
256
|
+
async def add_machine(self, machine: _MachineType) -> _MachineType:
|
|
257
|
+
"""Add given machine to the server. Will initialize the machine if not yet initialized."""
|
|
258
|
+
if not self.is_initialized:
|
|
259
|
+
await self.init()
|
|
260
|
+
|
|
261
|
+
assert machine is not None
|
|
262
|
+
|
|
263
|
+
time_start = time.monotonic()
|
|
264
|
+
if not machine.is_initialized:
|
|
265
|
+
machine.server = self # pyright: ignore[reportAttributeAccessIssue]
|
|
266
|
+
await machine.ua_create_node(self._ua_machines)
|
|
267
|
+
await machine.init()
|
|
268
|
+
|
|
269
|
+
self._machines.append(machine)
|
|
270
|
+
self.logger.info(
|
|
271
|
+
"Added machine.",
|
|
272
|
+
machine_name=machine.name,
|
|
273
|
+
elapsed=time.monotonic() - time_start,
|
|
274
|
+
)
|
|
275
|
+
return machine
|
|
276
|
+
|
|
277
|
+
@property
|
|
278
|
+
def state(self) -> ServerState:
|
|
279
|
+
"""Read-only. Return the state of the server."""
|
|
280
|
+
return self._state
|
|
281
|
+
|
|
282
|
+
@property
|
|
283
|
+
def machines(self) -> list[BaseMachine]:
|
|
284
|
+
"""Read-only. Return all machines added to the server."""
|
|
285
|
+
return list(self._machines)
|
|
286
|
+
|
|
287
|
+
@property
|
|
288
|
+
def ua_server(self) -> UaServer:
|
|
289
|
+
"""Read-only. Return the internal OPC UA server instance."""
|
|
290
|
+
return self._ua_server # exists after instantiation
|
|
291
|
+
|
|
292
|
+
@property
|
|
293
|
+
def ua_address_space(self) -> AddressSpace:
|
|
294
|
+
"""Read-only. Return the internal OPC UA address space instance."""
|
|
295
|
+
return self._ua_address_space
|
|
296
|
+
|
|
297
|
+
@property
|
|
298
|
+
def config(self) -> ServerConfiguration:
|
|
299
|
+
"""Return the server-wide configuration. Read-only property."""
|
|
300
|
+
if not hasattr(self, "_config") or self._config is None:
|
|
301
|
+
msg = "Server is not yet configured! Call configure() first."
|
|
302
|
+
raise RuntimeError(msg)
|
|
303
|
+
|
|
304
|
+
return self._config
|
|
305
|
+
|
|
306
|
+
async def _register_server(self, retry_seconds: float = 10.0):
|
|
307
|
+
lds_client = asyncua.client.client.Client(self.config.discovery.server_address)
|
|
308
|
+
while self._state == ServerState.RUNNING:
|
|
309
|
+
try:
|
|
310
|
+
await lds_client.register_server(self._ua_server)
|
|
311
|
+
except Exception:
|
|
312
|
+
try:
|
|
313
|
+
await lds_client.connect()
|
|
314
|
+
except Exception:
|
|
315
|
+
self.logger.exception(
|
|
316
|
+
f"Failed to register to discovery server, retrying in {retry_seconds} seconds.",
|
|
317
|
+
discovery_server_address=self.config.discovery.server_address,
|
|
318
|
+
)
|
|
319
|
+
await asyncio.sleep(retry_seconds)
|
|
320
|
+
|
|
321
|
+
async def start(self, blocking: bool = True) -> None:
|
|
322
|
+
"""Start the internal OPC UA server.
|
|
323
|
+
|
|
324
|
+
Server must be initialized beforehand, and must be in state `STOPPED`.
|
|
325
|
+
|
|
326
|
+
:param blocking If True, block until server shutdown or KeyboardInterrupt is caught
|
|
327
|
+
"""
|
|
328
|
+
if not self.is_initialized:
|
|
329
|
+
msg = "Server is not initialized!"
|
|
330
|
+
raise RuntimeError(msg)
|
|
331
|
+
if self.state != ServerState.STOPPED:
|
|
332
|
+
msg = "Server is not stopped!"
|
|
333
|
+
raise RuntimeError(msg)
|
|
334
|
+
|
|
335
|
+
self._state = ServerState.STARTING
|
|
336
|
+
await self._ua_server.start()
|
|
337
|
+
for endpoint in await self._ua_server.get_endpoints():
|
|
338
|
+
self.logger.info(
|
|
339
|
+
"Serving OPC UA server at:",
|
|
340
|
+
endpoint_url=endpoint.EndpointUrl,
|
|
341
|
+
security_policy_uri=endpoint.SecurityPolicyUri,
|
|
342
|
+
)
|
|
343
|
+
self._state = ServerState.RUNNING
|
|
344
|
+
|
|
345
|
+
if self.config.discovery.register:
|
|
346
|
+
self._create_task(self._register_server(), name="DiscoveryRegisterTask")
|
|
347
|
+
else:
|
|
348
|
+
self.logger.warning("Register at Discovery server is disabled!")
|
|
349
|
+
|
|
350
|
+
if blocking:
|
|
351
|
+
try:
|
|
352
|
+
await self._watchdog_loop()
|
|
353
|
+
except asyncio.CancelledError:
|
|
354
|
+
self.logger.info("Received CancelledError, exiting endless loop!")
|
|
355
|
+
except KeyboardInterrupt:
|
|
356
|
+
self.logger.info("Received KeyboardInterrupt, exiting endless loop!")
|
|
357
|
+
else:
|
|
358
|
+
self._create_task(self._watchdog_loop(), name="WatchdogTask")
|
|
359
|
+
|
|
360
|
+
async def _watchdog_loop(
|
|
361
|
+
self,
|
|
362
|
+
*,
|
|
363
|
+
interval: float = 0.2,
|
|
364
|
+
warning_threshold: float = 0.1,
|
|
365
|
+
) -> None:
|
|
366
|
+
"""Monitor how busy the event loop is and warn if it is probably too busy."""
|
|
367
|
+
loop = asyncio.get_running_loop()
|
|
368
|
+
deadline: float = loop.time() + interval
|
|
369
|
+
|
|
370
|
+
while self.running:
|
|
371
|
+
await asyncio.sleep(max(0, deadline - loop.time()))
|
|
372
|
+
|
|
373
|
+
now = loop.time()
|
|
374
|
+
lag = now - deadline
|
|
375
|
+
|
|
376
|
+
if lag >= warning_threshold:
|
|
377
|
+
self.logger.warning(
|
|
378
|
+
"Event loop lag detected",
|
|
379
|
+
lag=round(lag, 3),
|
|
380
|
+
threshold=warning_threshold,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
deadline = now + interval
|
|
384
|
+
|
|
385
|
+
async def _shutdown(self) -> None:
|
|
386
|
+
self._state = ServerState.STOPPING
|
|
387
|
+
|
|
388
|
+
for machine in self.machines:
|
|
389
|
+
self.logger.debug("Trying to call shutdown()...", machine_name=machine.name)
|
|
390
|
+
try:
|
|
391
|
+
await machine.shutdown()
|
|
392
|
+
except (Exception, asyncio.CancelledError): # shutdown() is implemented by user, might raise some exception
|
|
393
|
+
self.logger.exception("Error during machine shutdown!", machine_name=machine.name)
|
|
394
|
+
|
|
395
|
+
self.access_control.running = False
|
|
396
|
+
await self._cancel_tasks()
|
|
397
|
+
await self.ua_server.stop()
|
|
398
|
+
|
|
399
|
+
self._state = ServerState.STOPPED
|
|
400
|
+
|
|
401
|
+
@property
|
|
402
|
+
def running(self) -> bool:
|
|
403
|
+
"""Whether the server is running."""
|
|
404
|
+
return self._state == ServerState.RUNNING
|
|
405
|
+
|
|
406
|
+
@property
|
|
407
|
+
def stopped(self) -> bool:
|
|
408
|
+
"""Whether the server is stopped."""
|
|
409
|
+
return self._state == ServerState.STOPPED
|
|
410
|
+
|
|
411
|
+
async def get_enum(self, enum_type: type[IntEnum], *, option_set: bool = False) -> ua.NodeId:
|
|
412
|
+
"""Return OPC UA Node representation of given enum type."""
|
|
413
|
+
try:
|
|
414
|
+
return self._ua_enums[enum_type]
|
|
415
|
+
except KeyError:
|
|
416
|
+
ua_node = await new_enum(
|
|
417
|
+
server=self.ua_server,
|
|
418
|
+
idx=1,
|
|
419
|
+
name=enum_type.__name__, # type: ignore
|
|
420
|
+
fields=[enum_type(index).name for index in enum_type],
|
|
421
|
+
option_set=option_set,
|
|
422
|
+
)
|
|
423
|
+
self._ua_enums[enum_type] = ua_node.nodeid
|
|
424
|
+
self.logger.info("Created new enum type", name=enum_type.__name__, ua_node_id=str(ua_node))
|
|
425
|
+
return ua_node.nodeid
|
|
426
|
+
|
|
427
|
+
def __del__(self) -> None:
|
|
428
|
+
if self.lifecycle_state in (
|
|
429
|
+
LifecycleState.INITIALIZING,
|
|
430
|
+
LifecycleState.INITIALIZED,
|
|
431
|
+
LifecycleState.SHUTTING_DOWN,
|
|
432
|
+
):
|
|
433
|
+
# Note: At this point, we cannot (async) shut down properly anymore
|
|
434
|
+
# try to warn the user to prevent the same mistake next time
|
|
435
|
+
print(
|
|
436
|
+
f"Server was not properly shut down! life_cycle={self.lifecycle_state.name}",
|
|
437
|
+
file=sys.stderr,
|
|
438
|
+
flush=True,
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
async def __aenter__(self) -> Self:
|
|
442
|
+
"""Enter the asynchronous context manager; no setup required."""
|
|
443
|
+
await self.init()
|
|
444
|
+
return self
|
|
445
|
+
|
|
446
|
+
async def __aexit__(self, exc_type, exc, tb) -> None: # noqa: ANN001
|
|
447
|
+
"""Exit the asynchronous context manager and shut down the server."""
|
|
448
|
+
await self.shutdown()
|
|
449
|
+
|
|
450
|
+
@override
|
|
451
|
+
def _repr_items(self) -> Iterator[tuple[str, object]]:
|
|
452
|
+
yield from super()._repr_items()
|
|
453
|
+
yield "state", self._state.name
|
|
454
|
+
yield "life_cycle_state", self.lifecycle_state.name
|