Skip to content

Commit eaac59b

Browse files
authored
Merge pull request #586 from ptsneves/disconnect-refactor
Disconnect refactor (reordering flow to improve readability)
2 parents 2d3b04d + ac29fdf commit eaac59b

File tree

1 file changed

+19
-24
lines changed

1 file changed

+19
-24
lines changed

client.go

+19-24
Original file line numberDiff line numberDiff line change
@@ -452,35 +452,30 @@ func (c *client) attemptConnection() (net.Conn, byte, bool, error) {
452452
// reusing the `client` may lead to panics. If you want to reconnect when the connection drops then use
453453
// `SetAutoReconnect` and/or `SetConnectRetry`options instead of implementing this yourself.
454454
func (c *client) Disconnect(quiesce uint) {
455-
status := atomic.LoadUint32(&c.status)
456-
if status == connected {
457-
DEBUG.Println(CLI, "disconnecting")
458-
c.setConnected(disconnected)
455+
defer c.disconnect()
459456

460-
dm := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket)
461-
dt := newToken(packets.Disconnect)
462-
disconnectSent := false
463-
select {
464-
case c.oboundP <- &PacketAndToken{p: dm, t: dt}:
465-
disconnectSent = true
466-
case <-c.commsStopped:
467-
WARN.Println("Disconnect packet could not be sent because comms stopped")
468-
case <-time.After(time.Duration(quiesce) * time.Millisecond):
469-
WARN.Println("Disconnect packet not sent due to timeout")
470-
}
457+
status := atomic.LoadUint32(&c.status)
458+
c.setConnected(disconnected)
471459

472-
// wait for work to finish, or quiesce time consumed
473-
if disconnectSent {
474-
DEBUG.Println(CLI, "calling WaitTimeout")
475-
dt.WaitTimeout(time.Duration(quiesce) * time.Millisecond)
476-
DEBUG.Println(CLI, "WaitTimeout done")
477-
}
478-
} else {
460+
if status != connected {
479461
WARN.Println(CLI, "Disconnect() called but not connected (disconnected/reconnecting)")
480-
c.setConnected(disconnected)
462+
return
481463
}
482464

483-
c.disconnect()
465+
DEBUG.Println(CLI, "disconnecting")
466+
dm := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket)
467+
dt := newToken(packets.Disconnect)
468+
select {
469+
case c.oboundP <- &PacketAndToken{p: dm, t: dt}:
470+
// wait for work to finish, or quiesce time consumed
471+
DEBUG.Println(CLI, "calling WaitTimeout")
472+
dt.WaitTimeout(time.Duration(quiesce) * time.Millisecond)
473+
DEBUG.Println(CLI, "WaitTimeout done")
474+
case <-c.commsStopped:
475+
WARN.Println("Disconnect packet could not be sent because comms stopped")
476+
case <-time.After(time.Duration(quiesce) * time.Millisecond):
477+
WARN.Println("Disconnect packet not sent due to timeout")
478+
}
484479
}
485480

486481
// forceDisconnect will end the connection with the mqtt broker immediately (used for tests only)

0 commit comments

Comments
 (0)