summaryrefslogtreecommitdiffstats
path: root/server/chart.go
blob: 1f20d3cdb24c3c92e8541b9b1519e8236b8268f1 (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
package main

import (
	"log"
	"net/http"
	"fmt"
	"time"
	"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
	}

	var series []chart.Series
	for room, record := range h.building {
		var x []time.Time
		var y []float64
		c := make(chan Entry[Humidity])
		record.get <- c
		for e := range c {
			x = append(x, e.t)
			y = append(y, float64(e.v))
		}
		series = append(series, chart.TimeSeries{
			Name: string(room),
			XValues: x,
			YValues: y,
		})
	}

	graph := chart.Chart{
		Background: chart.Style{
			Padding: chart.Box{Top: 20, Left: 20},
		},
		Series: series,
	}
	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)
	}
}