2012-08-24 4 views
1

꼬인 응용 프로그램에서 ajax POST를 통해 (modbus로) TCP 연결을 시작/중지하고 싶습니다. 연결 상태에 따라 연결 또는 연결 끊기 버튼이 하나 있습니다.ajax에 의해 꼬인 TCP 연결을 시작/중지하고 연결 상태를 얻으십시오.

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() 

지금 내가 연결을 중지 할 때 연결이 '연결'시작 할 때 '연결'얻을 : 같은

지금 내 코드 보인다. 연결이 설정되거나 폐지 될 때까지 응답 대기하고 연결 상태 (연결 또는 연결 해제 + 선택적 오류 설명)를 반환합니다.

감사합니다.

답변

1

응답 지연은 대개 대기중인 항목에 의해 호출 한 render 메서드에서 defer을 반환하는 문제입니다. 이 경우 어떻게하면 reactor.connectTCP을 호출하기 전에 Modbus 연결을 위해 클라이언트 프로토콜을 설정해야합니다.

이전 질문에서 언급 한 웹 소켓 사용을 포기한 적이 있습니까?
How to asynchronously read data via modbus/TCP and send them to web

웹 소켓은 브라우저와 modbus 서버 간의 연결을 프록시 처리하는 효과적인 방법처럼 생각됩니다. 대신 엔드 포인트 API를 사용하는 경우

+0

감사합니다 . 아니, 나는 웹 소켓을 포기하지 않았다. 그냥 modbus IP 주소 옵션을 추가하고 듣기 기능을 시작/정지하고 싶습니다 :). 좋은 시작을위한 간단한 코드를 작성하고 싶습니다만, 귀하의 코드 중 일부를 사용했습니다. 감사합니다 ... – marcinpz

1

, 당신은 연결 프로토콜 인스턴스 화재는 일단 연결이 설정된 것을 다시 이연거야 및 해당 프로토콜 인스턴스가 만들어졌습니다 및 연결 :

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)