在扭曲的应用程序中,我想通过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()现在,当连接开始时,我得到“连接”,当停止连接时,我得到“已连接”。我希望等待响应,直到连接建立或取消,并返回连接状态(已连接或已断开+可选的错误描述)。
谢谢。
发布于 2012-08-24 18:29:19
延迟响应通常是从render方法返回一个defer,然后由您正在等待的任何东西调用它。在这种情况下,我认为您需要为modbus连接设置客户端协议,以便在调用reactor.connectTCP之前以某种方式调用传递给它的延迟。
您是否已放弃使用您在上一个问题中提到的websockets?
How to asynchronously read data via modbus/TCP and send them to web
在我看来,Websockets似乎是代理浏览器和modbus服务器之间连接的一种有效方法。
发布于 2012-08-25 03:34:04
如果使用端点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)https://stackoverflow.com/questions/12106833
复制相似问题