如何实现 OPC UA 的订阅和通知机制?

解读

国内工业 4.0、智能制造项目普遍要求“毫秒级”数据上云,OPC UA 的订阅/通知(Sub/Mon)正是核心能力。面试官问“Twisted 里怎么做”,不是考你会不会调 freeopcua 的 create_subscription(),而是考三件事:

  1. 能否把 OPC UA 的异步语义无损嫁接到 Twisted 的 Reactor 上;
  2. 能否用 Deferred/inlineCallbacks 把“订阅-回调-重连”写成可维护的协程;
  3. 能否在单线程内扛住 1 万点、每秒 10 k 条通知的 C10K 场景,而不阻塞 PLC 扫描周期。

一句话:让 OPC UA 的“发布-订阅”变成 Twisted 的“事件源”,还要保证工业级可靠。

知识点

  1. OPC UA 订阅模型

    • Subscription:会话级容器,生命周期由 Client 维护,Server 分配 Id。
    • MonitoredItem:订阅下的“点位”,可设采样间隔、队列长度、过滤运算符。
    • Publish/NotificationMessage:Server 主动推,Client 必须按期回 PublishRequest,否则 Server 把“心跳”当 keep-alive。
  2. Twisted 事件源抽象

    • 任何“外部事件”都可封装成 twisted.internet.interfaces.IPushProducer,把数据推给 Reactor。
    • Deferred 链可以当“异步管道”,但高频场景下最好用 “fire-and-forget” 的回调,避免链过长。
  3. 协议级对接

    • freeopcua 的 asyncio 层与 Twisted 的协程调度器不兼容,需要把 asyncio 的 call_soon_threadsafe 桥接到 reactor.callFromThread。
    • 由于 OPC UA 二进制协议跑在 TCP 上,可直接复用 Twisted Protocol,把 freeopcua.uaprotocol 的 MessageChunk 解析器塞到 dataReceived 里,实现零拷贝。
  4. 反压与流控

    • 当 Notification 速率 > 消费速率时,需通过 producer.pauseProducing() 让 Server 暂缓采样,避免 PLC 侧缓存溢出。
    • 利用 Twisted 的 CooperativeTask 把批量通知拆成 1 ms 切片,防止单条长回调霸占 Reactor。
  5. 重连与会话恢复

    • OPC UA 的 Session 恢复需要 Client 重新提交 SubscriptionId;Twisted 端用 ReconnectingClientFactory 并在 buildProtocol 里把旧 Subscription 重新 attach,实现“断链不断订阅”。
  6. 工业级坑

    • 国内现场经常遇到“秒级断网”+“毫秒级恢复”,必须把 PublishRequest 的 timeout 设成 1.5 倍采样周期,否则 Server 会误判 Client 离线,直接删 Subscription。
    • 某些国产 PLC 的 Server 实现不标准,Notification 里不带 PublishTime,需要 Client 侧打时间戳,Twisted 用 reactor.seconds() 保证单调时钟。

答案

以下给出可直接落地的“最小可验证方案”(MVU),兼顾面试“能说清楚”与“能写代码”。

  1. 协议桥接层
from twisted.internet import reactor, protocol, defer, task
from twisted.internet.interfaces import IPushProducer
from zope.interface import implementer
from freeopcua import Client, ua
import queue, threading

class UaProtocol(protocol.Protocol):
    def __init__(self, ua_client):
        self.ua_client = ua_client
        self._buffer = b''

    def dataReceived(self, data):
        self._buffer += data
        while True:
            chunk, self._buffer = ua.MessageChunk.parse(self._buffer)
            if chunk is None:
                break
            # 把二进制帧抛给 ua_client 的异步解析器
            reactor.callFromThread(self.ua_client._process_chunk, chunk)
  1. 订阅管理器
class SubscriptionManager:
    def __init__(self, ua_client):
        self.ua_client = ua_client
        self.sub_map = {}          # sub_id -> Subscription
        self.deferreds = {}        # sub_id -> Deferred

    @defer.inlineCallbacks
    def create_subscription(self, period=100, count=1000):
        sub = ua.CreateSubscriptionParameters()
        sub.RequestedPublishingInterval = period
        sub.RequestedMaxKeepAliveCount = count
        sub.Priority = 10
        response = yield self.ua_client.create_subscription(sub)
        sub_id = response.SubscriptionId
        # 把 Server 的 publish 循环注册成 Twisted 事件源
        producer = UaNotificationProducer(self.ua_client, sub_id)
        reactor.callLater(0, producer.start)
        self.sub_map[sub_id] = producer
        defer.returnValue(sub_id)
  1. 通知生产者(符合 IPushProducer)
@implementer(IPushProducer)
class UaNotificationProducer:
    def __init__(self, ua_client, sub_id):
        self.ua_client = ua_client
        self.sub_id = sub_id
        self.consumer = None
        self.paused = False
        self._task = None

    def start(self):
        self._task = task.LoopingCall(self._publish_cycle)
        self._task.start(0.1)   # 100 ms 检查一次

    def _publish_cycle(self):
        if self.paused:
            return
        # 发 PublishRequest,异步收 Notification
        d = self.ua_client.publish([self.sub_id])
        d.addCallback(self._on_notification)

    def _on_notification, notification):
        if self.consumer:
            self.consumer.write(notification)

    def pauseProducing(self):
        self.paused = True

    def resumeProducing(self):
        self.paused = False

    def stopProducing(self):
        if self._task:
            self._task.stop()
  1. 使用示例
@defer.inlineCallbacks
def main():
    from twisted.internet.endpoints import TCP4ClientEndpoint
    endpoint = TCP4ClientEndpoint(reactor, "192.168.1.100", 4840)
    proto = yield endpoint.connect(UaProtocolFactory())
    mgr = SubscriptionManager(proto.ua_client)
    sub_id = yield mgr.create_subscription(period=50)   # 50 ms
    # 监听 1000 个温度节点
    for node_id in node_list:
        yield mgr.add_monitored_item(sub_id, node_id, sampling=50, queue=10)
    # 把通知打到 Kafka/Redis,此处省略
    yield defer.Deferred()  # 保持长连接

if __name__ == '__main__':
    reactor.callWhenRunning(main)
    reactor.run()

关键话术(面试背诵版)
“我把 OPC UA 的 Publish 循环封装成 Twisted 的 IPushProducer,利用 LoopingCall 做 100 ms 心跳,既满足 OPC UA 规范里‘Client 必须按期发 PublishRequest’,又把 Notification 转成 Reactor 的普通 write 事件,天然享受 Twisted 的反压机制;当现场网络抖动时,ReconnectingClientFactory 在 3 次指数退避后重连,重连成功后自动 restore 旧 SubscriptionId,PLC 侧无感知,生产数据零丢失。”

拓展思考

  1. 多 Reactor 分片
    单核跑到 C10K 后,CPU 软中断成为瓶颈。可在 4 核 ARM 网关上起 4 个 Twisted 进程,每个进程负责一段 node_id hash 区间,共享一个 etcd 做 Subscription 路由表,实现“无锁水平扩展”。

  2. 与 MQTT 桥接
    国内很多 MES 只认 MQTT。可在 NotificationProducer 里把消息直接转成 Protobuf,通过 Twisted 的 MQTT client(txmqtt)推送到 EMQX,整条链路 <5 ms。

  3. 安全合规
    等保 2.0 要求传输层加密。OPC UA 的 SecurityPolicy 基本模式是 SignAndEncrypt,但证书轮换周期 1 年。Twisted 侧可用 twisted.internet.ssl.Certificate 动态热更新,配合 SNI 把不同产线证书隔离开,满足“一机一证”。

  4. 实时性调优
    Linux 默认时钟粒度 1 ms,可把 sysctl -w kernel.hz=1000 + twisted.internet.epollreactor 打开 EPOLLET 边缘触发,把 Notification 延迟压到 200 µs 级,足以替代传统 OPC DA 的“毫秒轮询”。