adds a dynamic part in the client id

This commit is contained in:
Holger Cremer
2018-01-16 21:38:07 +01:00
parent f2b992096a
commit ea72bc33da
2 changed files with 36 additions and 3 deletions

View File

@@ -12,7 +12,7 @@ import (
log "github.com/sirupsen/logrus"
)
const CLIENT_ID = "spaceDevices2"
const CLIENT_ID = "spaceDevicesGo"
var mqttLogger = log.WithField("where", "mqtt")
@@ -21,6 +21,7 @@ type MqttHandler struct {
newDataChan chan []byte
sessionTopic string
devicesTopic string
}
//func init() {
@@ -63,12 +64,13 @@ func NewMqttHandler(conf conf.MqttConf) *MqttHandler {
}
opts.SetTLSConfig(tlsConf)
opts.SetClientID(CLIENT_ID)
opts.SetClientID(CLIENT_ID + GenerateRandomString(4))
opts.SetAutoReconnect(true)
opts.SetKeepAlive(10 * time.Second)
opts.SetMaxReconnectInterval(5 * time.Minute)
opts.SetWill(conf.DevicesTopic, emptyPeopleAndDevices(), 0, true)
handler := MqttHandler{newDataChan: make(chan []byte), devicesTopic: conf.DevicesTopic, sessionTopic: conf.SessionTopic}
opts.SetOnConnectHandler(handler.onConnect)
opts.SetConnectionLostHandler(handler.onConnectionLost)
@@ -98,7 +100,7 @@ func (h *MqttHandler) SendPeopleAndDevices(data PeopleAndDevices) {
token := h.client.Publish(h.devicesTopic, 0, true, string(bytes))
ok := token.WaitTimeout(time.Duration(time.Second * 10))
if !ok {
mqttLogger.Warn("Error sending devices to:", h.devicesTopic)
mqttLogger.WithError(token.Error()).WithField("topic", h.devicesTopic).Warn("Error sending devices.")
return
}
}

31
mqtt/utils.go Normal file
View File

@@ -0,0 +1,31 @@
package mqtt
import (
"crypto/rand"
"github.com/sirupsen/logrus"
"encoding/base64"
)
// https://elithrar.github.io/article/generating-secure-random-numbers-crypto-rand/
// GenerateRandomBytes returns securely generated random bytes.
// It will fail with a fatal log if the system's secure random
// number generator fails to function correctly
func GenerateRandomBytes(n int) []byte {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
// Note that err == nil only if we read len(b) bytes.
logrus.Fatal("Could not read random bytes")
}
return b
}
// GenerateRandomString returns a URL-safe, base64 encoded
// securely generated random string.
// It will fail with a fatal log if the system's secure random
// number generator fails to function correctly
func GenerateRandomString(s int) string {
b := GenerateRandomBytes(s)
return base64.URLEncoding.EncodeToString(b)
}