如何实现 Modbus 寄存器的读写操作,支持多个设备并发访问?
解读
国内工业物联网项目普遍要求“单台边缘网关对接几十台 PLC/仪表,毫秒级轮询,不能掉线”。面试官抛出这道题,想确认三件事:
- 你能否把“阻塞的串口/Modbus TCP 指令”转成 Twisted 的非阻塞模型;
- 能否用一条 Reactor 线程同时伺候多设备,而不是给每台设备开一个线程;
- 能否把“请求-响应”映射成 Deferred,方便上层业务代码同步/异步复用。
答不到“单线程并发”和“Deferred 链式回调”两个关键词,基本会被判“只懂 pymodbus 同步写法”。
知识点
- Reactor 模式:select/epoll 统一监听多路串口(ttyUSB*)或多路 TCP 套接字,单线程内完成调度。
- Twisted 协议栈:Protocol/Factory 负责“字节流 ↔ 帧”解析;Modbus 帧格式固定(MBAP + PDU),需自己实现 FrameReceiver。
- Deferred:把“发指令→等响应→超时异常”封装成 Deferred,上层用 inlineCallbacks 写同步风格。
- 连接池:用 CyclicCounter 轮询设备,配合 Cooperator 把“大循环”拆成“每轮只发一条指令”的生成器,避免饿死其他 fd。
- 串口支持:pyserial-asyncio 的 twisted 适配层(SerialPort 对象)在 Linux 下同样走 epoll,Windows 下走 iocp,国内 armhf/aarch64 网关亲测可行。
- 异常处理:Modbus 异常码 0x83/0x86 要映射为特定 Exception,确保 Deferred errback 被触发,业务层能感知“从站忙”。
- 零第三方:Twisted 本体不带 Modbus,但实现一个最小协议解析器 <150 行即可,不引入 pymodbus,符合“零依赖”传统。
答案
给出可直接落地的最小可运行骨架,突出“单线程并发 + Deferred”:
from twisted.internet import reactor, defer, task
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet.serialport import SerialPort
from twisted.internet.endpoints import TCP4ClientEndpoint
import struct, time, logging
# ---------- 协议解析 ----------
class ModbusFrameReceiver(Protocol):
"""同时支持 TCP 与 RTU 的帧解析,面试现场写 TCP 版即可"""
def __init__(self):
self._buf = b''
self._pending = {} # tid -> Deferred
def dataReceived(self, data):
self._buf += data
while True:
if len(self._buf) < 7: # MBAP 头 7 字节
return
tid, pid, ln, uid = struct.unpack('>HHHB', self._buf[:7])
if pid != 0: # 非法 MBAP
self._buf = self._buf[1:]; continue
if len(self._buf) < 7 + ln - 1: return
frame = self._buf[7: 7 + ln - 1]
self._buf = self._buf[7 + ln - 1:]
d = self._pending.pop(tid, None)
if d:
if frame[1] & 0x80: # 异常响应
d.errback(ModbusException(frame[2]))
else:
d.callback(frame)
def send_pdu(self, pdu):
tid = self.factory.next_tid()
mbap = struct.pack('>HHHB', tid, 0, len(pdu) + 1, self.factory.uid)
self.transport.write(mbap + pdu)
d = defer.Deferred()
self._pending[tid] = d
reactor.callLater(2, self._timeout, tid) # 2 秒超时
return d
def _timeout(self, tid):
d = self._pending.pop(tid, None)
if d: d.errback(TimeoutError())
class ModbusException(Exception): pass
class TimeoutError(Exception): pass
# ---------- 工厂 ----------
class ModbusClientFactory(ClientFactory):
protocol = ModbusFrameReceiver
tid_counter = 0
def __init__(self, host, port, uid):
self.host, self.port, self.uid = host, port, uid
self.ready = defer.Deferred()
def buildProtocol(self, addr):
p = super().buildProtocol(addr)
self.ready.callback(p)
return p
def next_tid(self):
self.tid_counter = (self.tid_counter + 1) & 0xFFFF
return self.tid_counter
def clientConnectionLost(self, connector, reason):
logging.warning('lost %s:%s', self.host, self.port)
connector.connect() # 自动重连
def clientConnectionFailed(self, connector, reason):
logging.error('fail %s:%s', self.host, self.port)
self.ready = defer.Deferred()
reactor.callLater(3, connector.connect)
# ---------- 业务 API ----------
@defer.inlineCallbacks
def read_holding_register(factory, addr, count):
proto = yield factory.ready
pdu = struct.pack('>BBHH', 0x03, addr, count) # 功能码 03
resp = yield proto.send_pdu(pdu)
values = struct.unpack('>' + 'H' * count, resp[2:])
defer.returnValue(values)
@defer.inlineCallbacks
def write_single_register(factory, addr, value):
proto = yield factory.ready
pdu = struct.pack('>BBH', 0x06, addr, value)
yield proto.send_pdu(pdu)
# ---------- 多设备并发 ----------
def create_client(host, port, uid):
f = ModbusClientFactory(host, port, uid)
TCP4ClientEndpoint(reactor, host, port).connect(f)
return f
coop = task.Cooperator()
@defer.inlineCallbacks
def poll_loop(factory, dev_id):
while True:
try:
regs = yield read_holding_register(factory, 0, 10)
logging.info('dev %s regs %s', dev_id, regs)
except Exception as e:
logging.error('dev %s err %s', dev_id, e)
yield task.deferLater(reactor, 0.5, lambda: None) # 500 ms 轮询
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s')
# 模拟 3 台 PLC
factories = [create_client('192.168.1.1', 502, 1),
create_client('192.168.1.2', 502, 2),
create_client('192.168.1.3', 502, 3)]
# 用 Cooperator 把轮询拆成生成器,单线程并发
for idx, f in enumerate(factories):
coop.coiterate(poll_loop(f, idx+1))
reactor.run()
运行效果:单线程内 3 条 TCP 连接并行收发,互不阻塞;每条指令返回一个 Deferred,上层用 yield 写同步味道;超时、重连、异常全部走 errback,符合 Twisted 哲学。
拓展思考
- 串口场景:把
TCP4ClientEndpoint换成SerialPort(ModbusFrameReceiver(), '/dev/ttyUSB0', reactor, baudrate=9600),帧解析去掉 MBAP、改用 3.5 字符空闲判断,即可兼容 RTU。 - 高并发:若设备 >200 台,可把
poll_loop改成“批量读”——一次发 20 条指令,再批量解析,减少系统调用。 - 安全:国内很多 PLC 明文传输,可在 Twisted 上再包一层 TLS,工厂只需把
ModbusClientFactory换成twisted.internet.ssl.ClientTLSOptions,零业务代码改动。 - 测试:用 Twisted Trial 框架 mock 时间片,可在 10 ms 内跑完 1000 条“请求-响应”用例,CI 集成时极快。