具有扭曲的串行通信

问题描述 投票:1回答:1

我继承了前雇员写的python /扭曲代码。

我拥有的代码(并且可以正常工作)打开一个串行端口并接收数据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. 在“超时”秒后,将返回在此时间内从端口读取的所有数据的字符串(如果未读取任何内容,则返回空字符串。)>
  6. 这是我的问题。...尝试改编我已有的代码,我可以编写一个新协议。在connectionMade

中,它可以执行写操作,启动读取操作,然后通过调用reactor.callLater设置超时。在dataReceived内部,我可以将读取的数据附加到字符串中。在connectionLost内部,我可以返回读取的字符串。

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

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

我继承了前雇员编写的python / twisted代码。我拥有的代码(并且可以运行)打开一个串行端口并接收数据5秒钟,然后以相反的顺序将其写回。在这里...

python serial-port twisted
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.