-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.go
71 lines (58 loc) · 1.95 KB
/
generator.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"bytes"
"image"
"image/png"
"log/slog"
"sync"
"time"
)
// ImageGenerator generates images for the set width and height, using its generateImage function
type ImageGenerator struct {
sync.RWMutex
width int
height int
buffer *bytes.Buffer
lastUpdate time.Time
generateImage func(width, height int, temperature, lastModified string) (image.Image, error)
}
// NewImageGenerator creates a new display with the specified width and height, initializing the display buffer.
func NewImageGenerator(width, height int, generateImage func(width, height int, temperature, lastModified string) (image.Image, error)) *ImageGenerator {
return &ImageGenerator{
width: width,
height: height,
buffer: bytes.NewBuffer([]byte{}),
generateImage: generateImage,
}
}
// GetImageBytes returns the image data as a byte slice by reading from the display buffer.
// It will be blocked while a call to [ImageGenerator.Refresh] finishes
func (ig *ImageGenerator) GetImageBytes() []byte {
ig.RLock()
defer ig.RUnlock()
return ig.buffer.Bytes()
}
// NeedsUpdate checks if the last update time is before the provided time for comparison.
func (ig *ImageGenerator) NeedsUpdate(check time.Time) bool {
ig.RLock()
defer ig.RUnlock()
return ig.lastUpdate.Before(check)
}
// Refresh generates a new image based on the provided SensorDataMessage
// It updates the display buffer with the new image and sets the last update time
func (ig *ImageGenerator) Refresh(last *SensorDataMessage) error {
ig.Lock()
defer ig.Unlock()
slog.Debug("Refreshing image", "temperature", last.Temperature.String(), "date_time", last.MessageDate.String())
img, err := ig.generateImage(ig.width, ig.height, last.Temperature.String(), last.MessageDate.String())
if err != nil {
return err
}
ig.buffer.Reset()
err = png.Encode(ig.buffer, img)
if err != nil {
return err
}
ig.lastUpdate = time.Time(last.MessageDate)
return nil
}