连接mqtt broker过程中出现rc为14
on_disconnect callback rc = 14

需要注意的是,mqtt重连会导致订阅失效。

This is because you get a fresh session by default when you reconnect
(because you have clean_session=True), so you have no active
subscriptions.

Move the call to client.subscribe('topic') to inside the on_connect
callback then it will resubscribe when it reconnects.

上面虽然说的是paho,但mosquitto其实也是一样的。在mosquitto_new(const char id,bool clean_session,void obj)中,

clean_session    
set to true to instruct the broker to clean all messages and subscriptions on disconnect, false to instruct it to keep them.  See the man page mqtt(7) for more details.  Note that a client will never discard its own outgoing messages on disconnect.  Calling mosquitto_connect or mosquitto_reconnect will cause the messages to be resent.  Use mosquitto_reinitialise to reset a client to its original state.  Must be set to true if the id parameter is NULL.

如果id为空,则clean_session为true。

所以每次连接成功后,需要重新订阅,即在on_connect()中mosquitto_subscribe

on_connect
a callback function in the following form: void callback(struct mosquitto mosq, void obj, int rc)
Callback Parameters
mosq the mosquitto instance making the callback.
obj the user data provided in mosquitto_new
rc the return code of the connection response. The values are defined by the MQTT protocol version in use. For MQTT v5.0, look at section 3.2.2.2 Connect Reason code: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html For MQTT v3.1.1, look at section 3.2.2.3 Connect Return code: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html
mosquitto_subscribe
Subscribe to a topic.

It is valid to use this function for clients using all MQTT protocol versions. If you need to set MQTT v5 SUBSCRIBE properties, use mosquitto_subscribe_v5 instead.

Parameters
mosq a valid mosquitto instance.
mid a pointer to an int. If not NULL, the function will set this to the message id of this particular message. This can be then used with the subscribe callback to determine when the message has been sent.
sub the subscription pattern.
qos the requested Quality of Service for this subscription.

本文链接地址:https://const.net.cn/215.html

标签: mqtt

添加新评论