eclipse / paho.mqtt.golang

Other
2.73k stars 533 forks source link

How to update the "Will" message on "auto reconnect" #639

Closed weekaung closed 1 year ago

weekaung commented 1 year ago

Hi Everybody,

We are implementing an MQTT Sparkplug client for our projects. One of the requirement of the specification is that in the "Will" message when connecting to the MQTT server, a "bdSeq" number be provided, which needs to be incremented on every "connect". However, how do we do that when the "ClientOptions.AutoReconnect" is set to true, so that the client can automatically reconnect in case of a broken connection.

Someone came up with the idea of setting the "Will" message with the new "bdSeq" when OnConnected is triggered, which they were able to do in a "dotnet" environment. See below issue... https://github.com/dotnet/MQTTnet/issues/395

However, in the "paho.mqtt.golang" project, in the "OnConnectHandler", we only have access to the "mqtt.Client" object. Is there a way around this problem with the "paho.mqtt.golang" library, or would the team in charge of developing the code for this project be kind enough to let us be able to "update" the "will" message before the system does a "reconnect".

Thank you so much, David.

MattBrittan commented 1 year ago

The OnConnectHandler is passed the Client; this does not stop you accessing other things. For example see the way this demo uses subscribe (passing a method so the callback will have access to the struct; you can take exactly the same approach with OnConnect).

However there is probably more involved if very quick, look at the sparkplug spec is anything to go by (note this is an edit - I had misunderstood part of your question initially). Page 22 of the v3 spec states:

tck-id-topics-nbirth-bdseq-matching] This MUST match the bdSeq number provided in the MQTT CONNECT packet’s Will Message payload.

and page 24:

[tck-id-topics-ndeath-payload] The NDEATH message contains a very simple payload that MUST only include a single metric, the bdSeq number, so that the NDEATH event can be associated with the NBIRTH.

So it looks like bdSeq needs to be included in the MQTT Will Message which is part of the connect packet (already sent by the time the OnConnectHandler is called). This means you will probably need a SetReconnectingHandler too (this can change the will by calling SetWill on the options struct it is passed).

Please note that the issues section is really intended for those reporting bugs/issues; the readme suggests places to ask questions like this.

weekaung commented 1 year ago

Hi Matt,

Yes, I think implementing the SetReconnectingHandler will do the job. We did the implementation and testing and is working just as you have said.

Thank you for your excellent and timely help. David.