stlehmann / Flask-MQTT

Flask Extension for the MQTT protocol
MIT License
207 stars 71 forks source link

some problem with asyncio #185

Open Hpeox opened 1 month ago

Hpeox commented 1 month ago

I just try to return the rc from handle_connect using asyncio, but failed the code:

@app.route('/connect/', methods=['POST','GET'])
async def make_connect():
    rc_status=-1
    connect_future = asyncio.Future()
    data = request.get_json()['data']
    print(data)
    app.config['MQTT_BROKER_URL'] = data['host']
    app.config['MQTT_BROKER_PORT'] = int(data['port'])
    if data['usr'] != '':
        app.config['MQTT_USERNAME'] = data['usr']
        app.config['MQTT_PASSWORD'] = data['password']
    app.config['MQTT_KEEPALIVE'] = 60
    app.config['MQTT_TLS_ENABLED'] = False
    print(connect_future.done())
    mqtt.init_app(app)

    @mqtt.on_connect()
    def handle_connect(client, userdata, flags, rc):
        if rc == 0:
            print('Connected successfully')
        # print(rc)
        print(connect_future.done())
        connect_future.set_result(rc)
        print(connect_future.done())

    result = await connect_future
    rc_status = result
    return {
        'rc_status':rc_status
    }

the output in terminal:

{'host': '127.0.0.1', 'port': '1883', 'usr': '', 'password': ''}
False
Connected successfully
False
True

so i think the connect_future is correctly set but something wrong happened also i can't use ctrl-C to terminate the flask app correctly