'Pyst2 - How to reconnect Asterisk manager?

I'm using pyst2 to connect to the AMI (Asterisk manager interface). I have a event for shutdown, so it can close it and try to reconnect every minute.

My shutdown event:

def handle_shutdown(event, manager, hass, entry):
    _LOGGER.error("Asterisk shutting down.")

    manager.close()

    host = entry.data[CONF_HOST]
    port = entry.data[CONF_PORT]
    username = entry.data[CONF_USERNAME]
    password = entry.data[CONF_PASSWORD]

    while True:
        sleep(30)
        try:
            manager.connect(host, port)
            manager.login(username, password)
            _LOGGER.info("Succesfully reconnected.")
            break
        except asterisk.manager.ManagerException as exception:
            _LOGGER.error("Error reconnecting to Asterisk: %s", exception.args[1])

It works fine, until Asterisk started up again and it can connect. Instead of connecting I get this error: RuntimeError: threads can only be started once.

Does anybody knows how to do this correctly?

Here is my entire code.

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source