summaryrefslogtreecommitdiff
path: root/cache.go
blob: 31c8ba5029039dae9ac533755c106029caf5dcf3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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)
			var payload []byte
			if state == true {
				payload = []byte("open")
			} else {
				payload = []byte("closed")
			}
			_ = c.Client.Publish(topic, QOS, RETAINED, payload)
		}
		c.States[id] = state
	}
}