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.
This commit is contained in:
Plamen Todorov 2019-10-08 09:34:31 +03:00
parent fb2aef2ce6
commit c3b9a689bb

View File

@ -3,12 +3,14 @@ package endpoint
import ( import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"crypto/rand"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"sync" "sync"
"time" "time"
paho "github.com/eclipse/paho.mqtt.golang" paho "github.com/eclipse/paho.mqtt.golang"
"github.com/tidwall/tile38/internal/log"
) )
const ( const (
@ -83,9 +85,16 @@ func (conn *MQTTConn) Send(msg string) error {
} }
ops = ops.SetTLSConfig(&config) ops = ops.SetTLSConfig(&config)
} }
nano := time.Now().UnixNano() //generate UUID for the client-id.
clientID := fmt.Sprintf("tile38_%x", nano) //the id of connected clients should be unique b := make([]byte, 16)
ops = ops.SetClientID(clientID).AddBroker(uri) _, 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) c := paho.NewClient(ops)
if token := c.Connect(); token.Wait() && token.Error() != nil { if token := c.Connect(); token.Wait() && token.Error() != nil {