在扭曲的应用程序中,我想通过ajax POST启动/停止tcp连接(到modbus)。我有一个标题为"连接"或"断开连接"的按钮,具体取决于连接状态。
现在我的代码看起来像:
class ConnectHandler(Resource):
modbus_connection = None
def try_disconnect(self):
log.msg('Disconnecting...')
try:
self.modbus_connection.disconnect()
except:
log.err()
return self.modbus_connection.state
def try_connect(self):
try:
framer = ModbusFramer(ClientDecoder())
reader = DataReader()
factory = ModbusFactory(framer, reader) # inherits from ClientFactory
self.modbus_connection = reactor.connectTCP(ip, 502, factory)
except:
log.err()
return str(self.modbus_connection.state)
def render_POST(self, request):
if self.modbus_connection and
self.modbus_connection.state == 'connected':
return self.try_disconnect()
else:
return self.try_connect()
现在,当连接开始时,我得到"连接",当连接停止时,我获得"连接"。我想等待响应,直到连接建立或取消,并返回连接状态(连接或断开连接+可选的错误描述)。
谢谢。
延迟响应通常是从render
方法返回一个defer
,然后无论您在等待什么,都会调用该方法。在这种情况下,我认为您需要为modbus连接设置客户端协议,以便在调用reactor.connectTCP
之前调用您以某种方式传递给它的defer。
你是否已经放弃使用你在上一个问题中提到的网络套接字
如何通过modbus/TCP异步读取数据并将其发送到web
在我看来,Websockets是一种有效的方法,本质上可以代理浏览器和modbus服务器之间的连接。
如果您使用端点API,那么一旦建立了连接并且创建并连接了该协议实例,您将得到一个延迟返回,该延迟返回将触发连接的协议实例:
from twisted.internet.endpoints import TCP4ClientEndpoint
e = TCP4ClientEndpoint(reactor, ip, 502)
d = e.connect(factory)
def connected(protocol):
print 'Connection established, yay.'
# Use `protocol` here some more if you want,
# finish the response to the request, etc
d.addCallback(connected)