diff --git a/gateway.go b/gateway.go index 6bb8dd6477480449bdaa4a92d91c1cc63cbaa68b..b83418388836f76098bdb5189483c28a97666434 100644 --- a/gateway.go +++ b/gateway.go @@ -4,7 +4,6 @@ import ( "encoding/json" "log/slog" "slices" - "sync" MQTT "github.com/eclipse/paho.mqtt.golang" "gitlab.imt-atlantique.fr/xaal/code/go/core/xaal" @@ -17,20 +16,8 @@ type Gateway struct { config *Config } -var ( - instance *Gateway - once sync.Once -) - -func GetGW() *Gateway { - once.Do(func() { - instance = &Gateway{devices: make(map[string]*Z2MDevice)} - }) - return instance -} - func NewGW(cfg *Config, eng *xaal.Engine) *Gateway { - gw := GetGW() + gw := &Gateway{devices: make(map[string]*Z2MDevice)} gw.config = cfg gw.client = mqttSetup(cfg, gw.mqttPublishHander) // NOTE: Wondering if we can setup engine before @@ -44,6 +31,12 @@ func (gw *Gateway) GetZDevice(name string) *Z2MDevice { func (gw *Gateway) AddZDevice(zDev *Z2MDevice) { gw.devices[zDev.FriendlyName] = zDev + zDev.Gateway = gw +} + +func (gw *Gateway) RemoveZDevice(zDev *Z2MDevice) { + zDev.Gateway = nil + delete(gw.devices, zDev.FriendlyName) } func (gw *Gateway) GetZDevices() map[string]*Z2MDevice { diff --git a/z2m.go b/z2m.go index d403d414477db1e78723cb9b2315b423a3175f62..7ffc34b4d2c627b4ce4280357a34454109e00d00 100644 --- a/z2m.go +++ b/z2m.go @@ -35,6 +35,7 @@ type Z2MDevice struct { SwBuildID string `json:"software_build_id"` FriendlyName string `json:"friendly_name"` XAALDevices []XAALDeviceInterface + Gateway *Gateway } type Expose struct { @@ -137,7 +138,7 @@ func (zDev *Z2MDevice) setupXAALDevices(gw *Gateway) { func (zDev *Z2MDevice) Publish(topic string, payload interface{}) { topic = zDev.getTopic() + "/" + topic slog.Debug("Sending", "topic", topic, "payload", payload) - client := GetGW().client + client := zDev.Gateway.client if token := client.Publish(topic, 0, false, payload); token.Wait() && token.Error() != nil { slog.Error("PUBLISH Error", ":", token.Error()) }