diff --git a/client.go b/client.go index b8ca30bb..01d48f7f 100644 --- a/client.go +++ b/client.go @@ -55,6 +55,9 @@ type Client interface { // IsConnected returns a bool signifying whether // the client is connected or not. IsConnected() bool + // IsConnectionOpen return a bool signifying wether the client has an active + // connection to mqtt broker, i.e not in disconnected or reconnect mode + IsConnectionOpen() bool // Connect will create a connection to the message broker, by default // it will attempt to connect at v3.1.1 and auto retry at v3.1 if that // fails @@ -163,6 +166,21 @@ func (c *client) IsConnected() bool { } } +// IsConnectionOpen return a bool signifying whether the client has an active +// connection to mqtt broker, i.e not in disconnected or reconnect mode +func (c *client) IsConnectionOpen() bool { + c.RLock() + defer c.RUnlock() + status := atomic.LoadUint32(&c.status) + switch { + case status == connected: + return true + default: + return false + } +} + + func (c *client) connectionStatus() uint32 { c.RLock() defer c.RUnlock() diff --git a/unit_client_test.go b/unit_client_test.go index 0a57c6b8..104037e0 100644 --- a/unit_client_test.go +++ b/unit_client_test.go @@ -77,3 +77,31 @@ func Test_NewClient_optionsReader(t *testing.T) { } } + +func Test_isConnection(t *testing.T) { + ops := NewClientOptions() + c := NewClient(ops) + + c.(*client).setConnected(connected) + if !c.IsConnectionOpen() { + t.Fail() + } +} + +func Test_isConnectionOpenNegative(t *testing.T) { + ops := NewClientOptions() + c := NewClient(ops) + + c.(*client).setConnected(reconnecting) + if c.IsConnectionOpen() { + t.Fail() + } + c.(*client).setConnected(connecting) + if c.IsConnectionOpen() { + t.Fail() + } + c.(*client).setConnected(disconnected) + if c.IsConnectionOpen() { + t.Fail() + } +} \ No newline at end of file