From 99d0a36216752dcf649aa2b3cc269339d5798164 Mon Sep 17 00:00:00 2001 From: jkerdreux-imt <jerome.kerdreux@imt-atlantique.fr> Date: Mon, 18 Nov 2024 23:24:34 +0100 Subject: [PATCH] No more Singleton I hate this singleton stuff. Now Z2MDevice have a gateway (not really nice but can be usefull) --- gateway.go | 21 +++++++-------------- z2m.go | 3 ++- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/gateway.go b/gateway.go index 6bb8dd6..b834183 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 d403d41..7ffc34b 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()) } -- GitLab