通过twisted finger教程,看到了SO问题:
但是,我还不能编写一个可以从多个串行端口读写的twisted程序,尤其是当协议涉及到读取一条或多条线并相应地向设备写回数据时。在
我要做的是为2个调制解调器打开2对(即总共4个)串行端口。与调制解调器的通信使用Hayes AT命令集。虽然大多数与调制解调器的命令/响应交换是通过命令端口进行的,但是对于每个调制解调器,只有很少的诊断信息是通过诊断端口提供的。诊断信息应导致修改状态机(设备状态、连接状态)。在
以下是我所理解的潜在方法的大致框架程序(基于单端口示例):
class CommandProtocol(LineOnlyReceiver):
def connectionMade(self):
log.msg("Connected to command port")
def lineReceived(self, line):
print repr(line)
processCommandLine(line)
class DiagnosticProtocol(LineOnlyReceiver):
def connectionMade(self):
log.msg("Connected to diag port")
def lineReceived(self, line):
print repr(line)
processDiagnosticLine(line)
...
# modem1 ports
cmdPort[0] = SerialPort(CommandProtocol, "/dev/ttyUSB0", reactor, 115200)
diagPort[0] = SerialPort(DiagnosticProtocol, "/dev/ttyUSB1", reactor, 115200)
# modem2 ports
cmdPort[1] = SerialPort(CommandProtocol, "/dev/ttyUSB3", reactor, 115200)
diagPort[1] = SerialPort(DiagnosticProtocol, "/dev/ttyUSB4", reactor, 115200)
但是,对于如何做到以下几点,我不知所措:
请注意示例代码
我看不到你在将类注册到reactor之前实例化它们。我想那会失败得很惨。下面是我运行代码的一个类似片段:
就像如何将串行处理程序注册到Twisted中一样,也可以为标准io注册处理程序,例如:
^{pr2}$在正常使用中,每个连接实例都将有自己的状态机(封装在与连接一起注册到reactor中的类的实例中)。在
作为程序员,您可以选择如何连接类的状态,但通常是通过将引用推送到伙伴类。在
下面,这个答案包含可运行的代码,这些代码将说明如何在状态机/接口之间连接数据。这在SO:Persistent connection in twisted
如果你所说的“应用程序”是指“你的扭曲代码”,那么答案绝对是肯定的!在
典型的Twisted应用程序是一系列状态机,都有一些非常好定义的接口。我开始Twisted的冒险之旅,打算用两个状态机(串行机和键盘)编写一个应用程序,但当我适应Twisted的工作时,我意识到增加额外的接口和状态机是很简单的(通过tx库的所有奇妙之处)。在一个下午的时间里,我添加了一个粗略的web接口,一个websocket接口,然后在两者之上都添加了SSL,甚至还添加了SSH调试接口。一旦开始运行,添加接口和状态机就变得很简单了。在
在许多(全部?)在这种情况下,twisted模型是一个状态机将驻留在一个实例类中,该类绑定到一个连接上,并且已经注册到(一个且只有一个)主事件循环中。在
对于派生出新状态机的连接类型(比如http连接),您可以注册一个工厂类/状态机以及侦听连接,这两个连接一起为每个新连接启用派生新类/状态机的应用程序。Twisted应用程序在大规模运行时,通常会有10个甚至100个数千个并发状态实例。在
如果你想把不同的协议和状态粘在一起(。。。所有这些都在您选择的事件循环中(select/epoll/kqueue/etc))
下面是可运行的示例代码,它应该说明其中的许多要点。请阅读
def main()
之前的注释,了解有关代码的更多背景信息:经过研究,我没有一个简单的答案。我仍然怀疑下面的逻辑将接近解决方案,但我没有运气找到今天实现这一点的代码。在
我的猜测是有一个合理的方法来判断是否发生了USB事件,以及是否添加了串行设备。但我怀疑是否有一个好的方法来确定它是否是你的串行设备之一,更不用说它是你的命令或诊断接口(除非你的硬件可以控制设备的USB ID)
事件会在串行端口出错时触发(至少从我在linux上的经验来看),但我不确定USB插头将如何/在何处注册。在
其他可能对您有用的链接
Utilities for talking to a GSM modem over USB via AT commands
:https://github.com/smn/txgsm的扭曲实现相关问题 更多 >
编程相关推荐