From 853e3fd5f2b4e622d4e35c0e3c2fad6c358cb8ae Mon Sep 17 00:00:00 2001 From: xengineering Date: Sat, 20 Dec 2025 13:00:52 +0100 Subject: Add cache implementation This avoids frequent MQTT messages containing the same state. --- cache.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 cache.go (limited to 'cache.go') diff --git a/cache.go b/cache.go new file mode 100644 index 0000000..081621d --- /dev/null +++ b/cache.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + "log" + + mqtt "github.com/eclipse/paho.mqtt.golang" +) + +type States map[string]bool + +type Cache struct { + Client mqtt.Client + States map[string]bool +} + +func NewCache(client mqtt.Client) Cache { + var cache Cache + + cache.Client = client + cache.States = make(States) + + return cache +} + +func (c *Cache) Update(states States) { + if c.States == nil { + log.Fatal("Cache states is nil.") + } + + if states == nil { + log.Fatal("Given states is nil.") + } + + for id, state := range states { + cached, known := c.States[id] + if !known || cached != state { + topic := fmt.Sprintf("%s/contact/%s/state", TOPIC_PREFIX, id) + payload := []byte(fmt.Sprintf("%t", state)) + _ = c.Client.Publish(topic, QOS, RETAINED, payload) + } + c.States[id] = state + } +} -- cgit v1.2.3-70-g09d2