Python 单扭电抗器内的多个串行端口

Python 单扭电抗器内的多个串行端口,python,serial-port,twisted,Python,Serial Port,Twisted,我正在尝试使用twisted设置一个程序,以模拟发送/接收AT命令的串行设备。不同的设备打开不同数量的串行端口,并将这些端口用于不同的用途 我希望我的应用程序能够根据需要打开尽可能多的串行端口,并了解哪些串行设备正在写入接收到的数据。我不想在不同的反应器或线程上运行每个端口 有什么办法可以这样做吗 class VirtualDeviceBase(LineReceiver): def __init__(self, reactor, serial_address): [...]

我正在尝试使用twisted设置一个程序,以模拟发送/接收AT命令的串行设备。不同的设备打开不同数量的串行端口,并将这些端口用于不同的用途

我希望我的应用程序能够根据需要打开尽可能多的串行端口,并了解哪些串行设备正在写入接收到的数据。我不想在不同的反应器或线程上运行每个端口

有什么办法可以这样做吗

class VirtualDeviceBase(LineReceiver): 
    def __init__(self, reactor, serial_address):
    [...]

    def open_port(self):
        self.serial_device = SerialPort(self, serial_address, reactor)
        self.serial_device2 = SerialPort(? , serial_address, reactor)

    def dataReceived(self,data):
        [...]
我试过这个:

class VirtualDeviceBase(LineReceiver): 

    class Protocol(LineReceiver):
        def __init__(self,reactor,address):
            [...]

    def open_port(self):
        new_protocol = self.Protocol()
        self.serial_device = SerialPort(self, serial_address, reactor)
        self.serial_device2 = SerialPort(new_protocol , serial_address, reactor)

它不会抛出任何错误,但它们都不再调用DataReceived

只需实例化两个
SerialPort
s。给他们任何你喜欢的协议。他们可以共用一个反应堆。单个反应堆可以处理许多不同的事件源

from twisted.internet.protocol import Protocol
from twisted.internet.serial import SerialPort
from twisted.internet.task import react

class Echo(Protocol):
    def dataReceived(self, data):
        print("Received: {}".format(data))

def main(reactor):
    SerialPort(Echo(), "com0", reactor)
    SerialPort(Echo(), "com1", reactor)

react(main, [])

嗨,Jean,这个实现的问题是代码不知道哪个SerialPort正在调用DataReceive。没有什么可以阻止您告诉它。你想知道什么?港口的名称?将端口名作为Echo.\uuuu init\uuuu的参数,然后保存该值。