跳到主要内容

Session 会话 — OpcUaSession

OpcUaSession 是 Client 主类, 一个实例对应一个 OPC UA Session. 所有访问 (read / write / browse / subscribe / call / history) 都从这个对象出发.

DarraOpcUa 是 OpcUaSession 的兼容别名 (DarraOpcUa = OpcUaSession), 二者等价.

子页跳转

公共属性​

类别属性类型访问说明
连接endpoint_urlstrR构造时指定的 endpoint URL
security_modeMessageSecurityModeR安全模式 (NONE / Sign / SignAndEncrypt)
状态stateSessionStateR当前会话状态 (Disconnected / Connecting / Connected / Reconnecting / Closing / Failed)
is_connectedboolR是否已连接 (= state == SessionState.Connected)
handleintRC 层 native session handle (internal)
子对象nodesNodeCollectionRLazy Load 节点访问器
namespacesNamespaceCollectionR命名空间 URI ↔ Index 互转
事件eventsOpcUaEventsR会话级事件集合: state_changed / connected / disconnected / reconnecting / reconnected / keep_alive / communication_error / subscription_lost / node_removed / node_access_denied / node_type_changed / session_lost / server_state_changed / subscription_restored / any (每个都是 List[Callable], 用 .append 注册)
配置keep_alive_interval_msintRWKeepAlive 心跳周期 (默认 10000 ms, <= 0 = 禁用)
auto_publishboolRW启停后台 Publish 线程 (属性初值 False; 构造参数 auto_publish_on_connect 默认 True, connect() 里自动置 True)

公共方法​

连接管理​

  • connect() — 建立连接 (Hello → SecureChannel → Session → Activate)
  • disconnect() — 主动断开, 实例可重连
  • dispose() / close() — 停心跳 + 关闭 native session + 释放栈引用 (with 退出时自动调 dispose)

心跳与发布​

  • publish(timeout_ms = 2000) — 手动触发一次 Publish, 返回 StatusCode (一般无需调用)

读 / 写​

浏览​

订阅​

方法调用​

历史​

控制​

  • cancel(request_handle) — 取消会话上未完成的请求, 返回服务端实际取消的请求数 (int)

Safe 变体 (永不抛异常)​

高级浏览 / 子区间​

  • browse_filtered(nid, node_class_filter, direction, reference_type_id, include_subtypes) — 带方向 + 引用类型过滤 (当前退化为 browse + 客户端 NodeClass 过滤)
  • read_range(node_id, range_, attribute) / write_range(node_id, range_, value, attribute) — 子数组读写 (NumericRange); 整段时转发 read / write, 非整段当前抛 NotImplementedError

历史流式​

服务端信息​

报警与条件​

  • acknowledge / confirm / add_comment / enable_condition / disable_condition / condition_refresh / condition_refresh2 / one_shot_shelve / timed_shelve / unshelve — 见 报警与确认

完整示例​

from darra_opcua import OpcUaSession, OpcUaVariant   # 模块名 darra_opcua
import time

with OpcUaSession("opc.tcp://localhost:4840") as ua:
ua.events.connected.append(
lambda e: print(f"Connected to {e.endpoint_url}"))
ua.events.disconnected.append(
lambda e: print(f"Disconnected: {e.message}"))
ua.connect()

# 读
with ua.read("ns=2;s=Temperature") as dv:
print(f"T = {dv.value} °C")

# 写
st = ua.write("ns=2;s=Setpoint", OpcUaVariant().set_double(42.0))
print(f"Write status = {st.name}")

# 订阅
with ua.create_subscription(500) as sub:
sub.data_changed.append(
lambda e: print(f"{e.node_id} = {e.value_string} ({e.status.name})"))
sub.add_node("ns=2;s=Counter")

# 方法
outputs = ua.call(
"ns=2;s=Calc", "ns=2;s=Calc.Add",
[OpcUaVariant().set_int32(3), OpcUaVariant().set_int32(4)])
for v in outputs:
with v:
print(f"sum = {v.as_int32}")

time.sleep(60)

下一步​