micropython / micropython-lib

Core Python libraries ported to MicroPython
Other
2.3k stars 981 forks source link

It's "offline" after 10+ seconds, use umqtt.simple #824

Closed edgexie closed 3 months ago

edgexie commented 3 months ago

I try umqtt.simple to connect my raspberry with MQTT. But I found it's offline after 10+ seconds, and then I receive the error code in webrepl. Has anyone had the same problem?

The main snippets is:

def main(server=MQTT_SERVER_EMQX):
    # 连接WiFi
    connect_wifi()
    c = MQTTClient(generate_client_id(), server, keepalive=10)
    c.set_last_will(topic=b"esp8266/will", msg='offline', retain=True)
    c.set_callback(lambda topic, msg: sub_cb(topic, msg, c))
    # c.set_callback(sub_cb)

    res = c.connect(clean_session=False)
    if (res != 128):
        print('当前连接的MQTT服务器是:' + server)

        c.publish(b'esp8266/will', msg='online', retain=True)
        c.publish(b'led/status', msg=getLedStatus(), retain=True)

        c.subscribe(b'led/ctl')
        while True:
            if True:
                # Blocking wait for message
                c.wait_msg()
            else:
                # Non-blocking wait for message
                c.check_msg()
                # Then need to sleep to avoid 100% CPU usage (in a real
                # app other useful actions would be performed instead)
                time.sleep(1)

        c.disconnect()

if __name__ == "__main__":
    main()

image

felixdoerre commented 3 months ago

You are using keepalive=10. This means that you ask the server to disconnect you, if it does not receive a c.ping() in that timeframe. Either set keepalive=None, or ensure c.ping() is called at least every 10 seconds.

Also, please don't paste code as screenshot, but use backticks.

edgexie commented 3 months ago

You are using keepalive=10. This means that you ask the server to disconnect you, if it does not receive a c.ping() in that timeframe. Either set keepalive=None, or ensure c.ping() is called at least every 10 seconds.

Also, please don't paste code as screenshot, but use backticks.

HI , thx for your help, I change the screen shot code to snippets code.

In your help, you mean I need to code for the ping by myself? Doesn't MQTT automatically send pings?

felixdoerre commented 3 months ago

Yes, that's exactly what I mean. The micropython mqtt-client will not send ping packets automatically. The keepalive-parameter just configures what you want the server to expect. You have to call c.ping() yourself.

edgexie commented 3 months ago

thank you, It's awesome. I hope a offical demo use keepalive-parameter 🤕