Compare commits

...

2 Commits

Author SHA1 Message Date
c2ce10fe15 Print out ClientID 2026-02-02 14:13:17 +07:00
7f298edf60 Fix ClientID 2026-02-02 13:42:10 +07:00

View File

@@ -7,7 +7,8 @@ import (
"os"
"strings"
"time"
"crypto/rand"
"strconv"
"math/rand"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/go-redis/redis/v8"
@@ -39,7 +40,7 @@ func main() {
rdb := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", redisHost, redisPort),
Password: redisPassword,
DB: atoi(redisDB),
DB: parseInt(redisDB),
})
// Ping to verify connection
@@ -53,6 +54,7 @@ func main() {
opts.SetUsername(mqttUser)
opts.SetPassword(mqttPass)
opts.SetClientID(fmt.Sprintf("mqtt_presence_redis_go_%s", randomString()))
// clientID variable removed; use opts.ClientID directly
// Handlers
opts.SetDefaultPublishHandler(func(client mqtt.Client, msg mqtt.Message) {
@@ -63,7 +65,7 @@ func main() {
if token := c.Subscribe(mqttTopicPresence, 0, nil); token.Wait() && token.Error() != nil {
log.Fatalf("Failed to subscribe: %v", token.Error())
}
log.Printf("Connected to MQTT broker %s:%s, subscribed to %s", mqttHost, mqttPort, mqttTopicPresence)
log.Printf("Connected to MQTT broker %s:%s, subscribed to %s, client ID: %s", mqttHost, mqttPort, mqttTopicPresence, opts.ClientID)
}
// Create and start client
@@ -102,7 +104,7 @@ func handleMessage(ctx context.Context, rdb *redis.Client, msg mqtt.Message) {
return
}
if err := rdb.SetEX(ctx, key, data, time.Duration(atoi(redisSetEX))*time.Second).Err(); err != nil {
if err := rdb.SetEX(ctx, key, data, time.Duration(parseInt(redisSetEX))*time.Second).Err(); err != nil {
log.Printf("Failed to set Redis key: %v", err)
}
}
@@ -114,11 +116,20 @@ func getEnv(key, defaultVal string) string {
return defaultVal
}
func randomString() string {
b := make([]byte, 4)
if _, err := rand.Read(b); err != nil {
log.Printf("Failed to generate random string: %v", err)
return ""
func parseInt(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
log.Printf("Failed to parse int from %s: %v", s, err)
return 0
}
return hex.EncodeToString(b)
return i
}
func randomString() string {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, 10)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}