From bc72b239c757cfd21925f772768314f05b537e78 Mon Sep 17 00:00:00 2001
From: jkerdreux-imt <jerome.kerdreux@imt-atlantique.fr>
Date: Wed, 20 Nov 2024 16:21:47 +0100
Subject: [PATCH] Fix mqqtTopic global

I guess I missed a push on git.. so back port this missing stuff.
---
 config.go  | 1 -
 gateway.go | 2 +-
 z2m.go     | 4 +++-
 3 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/config.go b/config.go
index 4e2e92b..e849548 100644
--- a/config.go
+++ b/config.go
@@ -10,7 +10,6 @@ import (
 )
 
 var (
-	mqttTopic     = "zigbee2mqtt"
 	mqttClientID  = "z2m-" + uuid.New().String()
 	ignoredTopics = []string{
 		"bridge/groups",
diff --git a/gateway.go b/gateway.go
index 198ada6..f44ce43 100644
--- a/gateway.go
+++ b/gateway.go
@@ -34,8 +34,8 @@ func (gw *Gateway) AddZDevice(zDev *Z2MDevice) {
 		slog.Debug("Adding device", "dev", dev.String())
 		gw.Engine.AddDevice(dev)
 	}
-	gw.Devices[zDev.FriendlyName] = zDev
 	zDev.Gateway = gw
+	gw.Devices[zDev.FriendlyName] = zDev
 }
 
 func (gw *Gateway) RemoveZDevice(zDev *Z2MDevice) {
diff --git a/z2m.go b/z2m.go
index c8fab24..86926fe 100644
--- a/z2m.go
+++ b/z2m.go
@@ -61,7 +61,7 @@ type Feature struct {
 
 // returns the topic for the device
 func (zDev *Z2MDevice) getTopic() string {
-	return mqttTopic + "/" + zDev.FriendlyName
+	return zDev.Gateway.Config.topic + "/" + zDev.FriendlyName
 }
 
 // return the expose with the given name
@@ -90,6 +90,8 @@ func (zDev *Z2MDevice) HandleMessage(msg mqtt.Message) {
 
 // creates new xAAL devices from a bridge device
 func (zDev *Z2MDevice) FindXAALDevices(gw *Gateway) {
+	// There is a trick here. We call FindXAALDevices w/ gw argument, but the Gateway is only set
+	// in the AddZDevice method. This is not mandatory but avoid to have Gateway at random place
 	baseAddr := gw.Config.baseAddr
 	ieeeAddr, _ := hexStringToInteger(zDev.IeeeAddress)
 	baseAddr, _ = baseAddr.Add(int64(ieeeAddr))
-- 
GitLab