From c3b9a689bb0fbb6986259f373213ad4240abef65 Mon Sep 17 00:00:00 2001 From: Plamen Todorov Date: Tue, 8 Oct 2019 09:34:31 +0300 Subject: [PATCH] Use uuid as mqtt clientId Use crypto/random to generate unique mqtt client id. The tile38 prefix makes the connections easily identifiable in the mqtt broker logs. --- internal/endpoint/mqtt.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/internal/endpoint/mqtt.go b/internal/endpoint/mqtt.go index 3bd6431f..f4184725 100644 --- a/internal/endpoint/mqtt.go +++ b/internal/endpoint/mqtt.go @@ -3,12 +3,14 @@ package endpoint import ( "crypto/tls" "crypto/x509" + "crypto/rand" "fmt" "io/ioutil" "sync" "time" paho "github.com/eclipse/paho.mqtt.golang" + "github.com/tidwall/tile38/internal/log" ) const ( @@ -83,9 +85,16 @@ func (conn *MQTTConn) Send(msg string) error { } ops = ops.SetTLSConfig(&config) } - nano := time.Now().UnixNano() - clientID := fmt.Sprintf("tile38_%x", nano) //the id of connected clients should be unique - ops = ops.SetClientID(clientID).AddBroker(uri) + //generate UUID for the client-id. + b := make([]byte, 16) + _, err := rand.Read(b) + if err != nil { + log.Debugf("Failed to generate guid for the mqtt client. The endpoint will not work") + return err; + } + uuid := fmt.Sprintf("tile38-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) + + ops = ops.SetClientID(uuid).AddBroker(uri) c := paho.NewClient(ops) if token := c.Connect(); token.Wait() && token.Error() != nil {