summaryrefslogtreecommitdiffstats
path: root/server/chart.go
blob: b6c0471910f0b2fe462f3591eb1126095cdeff1b (plain) (blame)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main

import (
	"log"
	"net/http"
	"fmt"
	"time"
	"sync"
	"slices"
	"strings"
	"github.com/wcharczuk/go-chart/v2"
)

type ChartHandler struct {
	building Building
}

func (h ChartHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Println(r.Method, r.URL)

	if r.Method != http.MethodGet {
		w.WriteHeader(http.StatusMethodNotAllowed)
		fmt.Fprintf(w, "invalid method: '%s'", r.Method)
		return
	}

	graph := chart.Chart{
		Background: chart.Style{
			Padding: chart.Box{Top: 20, Left: 20},
		},
		Series: buildSortedSeries(h.building),
	}
	graph.Elements = []chart.Renderable{
		chart.Legend(&graph),
	}

	w.Header().Set("Content-Type", "image/png")
	if err := graph.Render(chart.PNG, w); err != nil {
		log.Println(err)
	}
}

// Build a time series for each humidity record in the building.
// The returned series' are sorted by room name.
func buildSortedSeries(building Building) []chart.Series {
	seriesChan := make(chan chart.TimeSeries)
	sortedSeriesChan := make(chan []chart.Series)
	go sortSeriesByName(seriesChan, sortedSeriesChan)

	var wg sync.WaitGroup
	for room, record := range building {
		entries := make(chan Entry[Humidity])
		record.get <- entries
		wg.Add(1)
		go func() {
			buildSeries(room, entries, seriesChan)
			wg.Done()
		}()
	}
	wg.Wait()
	close(seriesChan)
	return <-sortedSeriesChan
}

// Sort a sequence of series' by name.
func sortSeriesByName(in <-chan chart.TimeSeries, out chan<- []chart.Series) {
	series := make([]chart.Series, 0)
	cmp := func(a chart.Series, b chart.TimeSeries) int {
		return strings.Compare(a.GetName(), b.GetName())
	}

	// Insertion sort.
	for s := range in {
		i, _ := slices.BinarySearchFunc(series, s, cmp)
		series = slices.Insert(series, i, chart.Series(s))
	}

	out <- series
	close(out)
}

// Build a time series from a sequence of record entries.
func buildSeries(room RoomID, in <-chan Entry[Humidity], out chan<- chart.TimeSeries) {
	var x []time.Time
	var y []float64

	for e := range in {
		x = append(x, e.t)
		y = append(y, float64(e.v))
	}
	out <- chart.TimeSeries{
		Name: string(room),
		XValues: x,
		YValues: y,
	}
}