【问题标题】:Serial Communications with twisted带双绞线的串行通信
【发布时间】:2016-07-17 19:01:25
【问题描述】:

我继承了一位前雇员编写的 python/twisted 代码。

我拥有的代码(并且它有效)打开一个串行端口并接收数据 5 秒,然后以相反的顺序将其写回。代码如下:

from twisted.internet import reactor
from twisted.internet.protocol import Protocol
from twisted.internet.serialport import SerialPort
import serial
class ReverseEchoProtocol(Protocol):
    """Wait for specific amount of data.
       Regardless of success, closes connection timeout seconds after opening.
    """
    def __init__(self, port, timeout, logger):
        self._logger = logger
        self._timeout = timeout

    def connectionMade(self):
        self._logger.info('RS485 connection made.')
        reactor.callLater(self._timeout, self.transport.loseConnection, 'timeout')

    def connectionLost(self, reason):
        self._logger.info('RS485 connection lost. ' + str(reason))

    def dataReceived(self, data):
        self._logger.info('RS485 received data. ' + repr(data))
        self.transport.write(data[::-1])
        self.transport.flushOutput()

并且在 python 函数内部,上面的代码是通过这个调用启动的:

protocol = ReverseEchoProtocol(port, 5 self._logger)
try:
    port.open(protocol)
except serial.SerialException as err:
    # print/log err.message here
    return False
return True

port.open 的调用在成功打开端口后立即返回(远在 5 秒完成之前)

这就是我想要写的。从 python 函数内部,我需要启动一个串行事务。它需要等待事务完成、失败或超时。 下面是串行事务需要做的:

  1. 事务以字符串和超时值的形式传递。
  2. 串行端口已打开。未能打开会导致返回错误
  3. 字符串被写入串行端口。写入失败会返回错误
  4. 如果写入成功,则会在“超时”秒内连续读取同一端口。读取数据时(可能是多次读取),将其附加到字符串中。
  5. “timeout”秒后,返回在此期间从端口读取的所有数据的字符串(如果没有读取任何内容,则返回空字符串)。

这是我的问题....尝试修改我已有的代码,我可以编写一个新协议。在 connectionMade 中,它可以进行写入,启动读取,然后通过调用 reactor.callLater 设置超时。在 dataReceived 中,我可以将读取的数据附加到字符串中。在 connectionLost 里面我可以返回读取的字符串。

但是如何让调用 port.open 的 python 函数等到事务完成? (是否有诸如 reactor.wait 函数或 join 函数之类的东西?)另外,如果有错误(或异常),我如何将其传递(尝试块?)如何将字符串传递回python函数?

我认为我继承的代码让我很接近......我只需要回答这几个问题就可以完成任务。

【问题讨论】:

    标签: python serial-port twisted


    【解决方案1】:

    要回答您的前两个问题,您正在寻找 reactor.run() 来运行扭曲的主循环,但听起来和看起来您正在期待一个阻塞 api 并且扭曲是事件驱动的,这可能意味着您正在强制使用扭曲。您可以直接使用串行模块而无需扭曲来完成您想要完成的工作。如果您确实想通过事件驱动实现非阻塞,那么您将不得不提出更具体的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      相关资源
      最近更新 更多