Search code examples
pythonwebsockettornado

Access tornado websocket class method from another class


I'm new to stack overflow, because I regularly found here what I've been looking for. But this time, I don't know how to handle it. I set up a tornado websocket server and would like to access the websocket thread out of another class, but unfortunately, the websocket class requires three different arguments and isn't accessable the usual way.

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):      
        self.loop()

    def on_message(self, message):
        #do something

    def on_close(self):
        #do something else

    def loop(self):
        pass

    def toggle(self):
        #execute

class EventHandler: 
    def __init__(self):
        self.listener()

    def listener(self):        
        def callback(channel):
            wsHandler = WebSocketHandler()
            wsHandler.toggle()

        GPIO.add_event_detect(channel, GPIO.RISING, callback = callback, bouncetime = 1000)

def main():
    EventHandler()

    application = tornado.web.Application([
        (r"/", WebSocketHandler),
    ])
    server = tornado.httpserver.HTTPServer(application)
    server.listen(8888)
    io_loop = tornado.ioloop.IOLoop.current()
    io_loop.start()

if __name__ == "__main__":
    main()

The reason why I have multiple classes is that the server should listen to input events, even if there is no client connected. But I have to transfer the input data via websocket, if there is one. I read about the add_callback method, but I'm not sure whether it's a useful way.

I'm glad about any solution. Thanks a lot!


Solution

  • Alright, I used connections = [] (instead of connections = set(), because it's accessible through indexing) outside the WebsocketHandler. To add client connections on open to the list I use connections.append(self), to remove them on close connections.remove(self).

    Calling the method:

    if len(connections) > 0:
        connections[0].toggle()