package main import ( "embed" "encoding/json" "errors" "fmt" "html/template" "log" "net/http" "os" "strconv" "strings" "sync" "time" ) //go:embed static/* var indexHTML embed.FS type store struct { mu sync.RWMutex value int updatedAt time.Time history []sample } const maxHistoryPoints = 10000 type sample struct { at time.Time value int } func (s *store) get() int { s.mu.RLock() defer s.mu.RUnlock() return s.value } func (s *store) set(v int) { s.mu.Lock() s.value = v now := time.Now() s.updatedAt = now s.history = append(s.history, sample{at: now, value: v}) s.trimHistoryLocked(now) s.mu.Unlock() } func (s *store) trimHistoryLocked(now time.Time) { cutoff := now.Add(-12 * time.Hour) keep := s.history[:0] for _, point := range s.history { if point.at.After(cutoff) { keep = append(keep, point) } } if len(keep) > maxHistoryPoints { keep = keep[len(keep)-maxHistoryPoints:] } s.history = keep } func (s *store) snapshot() (int, time.Time, []sample) { s.mu.RLock() defer s.mu.RUnlock() history := append([]sample(nil), s.history...) return s.value, s.updatedAt, history } func main() { secret := os.Getenv("WRITE_SECRET") addr := os.Getenv("ADDR") chartMax := 0 if cfg, err := loadConfig("config.json"); err != nil { if !errors.Is(err, os.ErrNotExist) { log.Fatalf("load config: %v", err) } } else { if secret == "" { secret = cfg.WriteSecret } if addr == "" { addr = cfg.Addr } if cfg.ChartMaxWatts > 0 { chartMax = cfg.ChartMaxWatts } } if secret == "" { log.Fatal("WRITE_SECRET is required") } if addr == "" { addr = ":8080" } app := &server{ secret: secret, chartMax: chartMax, store: &store{}, } log.Printf("listening on %s", addr) log.Fatal(http.ListenAndServe(addr, app.routes())) } type server struct { secret string chartMax int store *store } type config struct { WriteSecret string `json:"write_secret"` Addr string `json:"addr"` ChartMaxWatts int `json:"chart_max_watts"` } func loadConfig(path string) (config, error) { data, err := os.ReadFile(path) if err != nil { return config{}, err } var cfg config if err := json.Unmarshal(data, &cfg); err != nil { return config{}, err } return cfg, nil } func (s *server) routes() http.Handler { mux := http.NewServeMux() mux.HandleFunc("/", s.handleIndex) mux.HandleFunc("/favicon.svg", s.handleFavicon) mux.HandleFunc("/write", s.handleWrite) return mux } func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } page, err := template.New("index.html").ParseFS(indexHTML, "static/index.html") if err != nil { http.Error(w, "template error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") watts, updatedAt, history := s.store.snapshot() updatedLabel := "not updated yet" if !updatedAt.IsZero() { updatedLabel = updatedAt.Format("02.01.2006 15:04:05") } if err := page.Execute(w, map[string]any{ "Watts": formatGermanNumber(watts), "UpdatedAt": updatedLabel, "HistoryChart": buildHistoryChart(history, s.chartMax), }); err != nil { http.Error(w, "render error", http.StatusInternalServerError) } } func formatGermanNumber(n int) string { s := strconv.Itoa(n) if len(s) <= 3 { return s } neg := false if s[0] == '-' { neg = true s = s[1:] } var b strings.Builder if neg { b.WriteByte('-') } rem := len(s) % 3 if rem == 0 { rem = 3 } b.WriteString(s[:rem]) for i := rem; i < len(s); i += 3 { b.WriteByte('.') b.WriteString(s[i : i+3]) } return b.String() } func buildHistoryChart(history []sample, maxWatts int) template.HTML { const ( width = 640 height = 220 padL = 72 padR = 18 padT = 18 padB = 42 ) if len(history) == 0 { return template.HTML(`No power history yet`) } minV, maxV := 0, history[0].value if maxWatts > 0 { maxV = maxWatts } start := history[0].at end := history[len(history)-1].at for _, point := range history[1:] { if maxWatts <= 0 && point.value > maxV { maxV = point.value } if point.at.Before(start) { start = point.at } if point.at.After(end) { end = point.at } } if maxV <= 0 { maxV = 1 } span := end.Sub(start) if span <= 0 { span = time.Minute } plotW := float64(width - padL - padR) plotH := float64(height - padT - padB) points := make([]string, 0, len(history)) var lastX, lastY float64 for _, point := range history { x := float64(padL) + plotW*point.at.Sub(start).Seconds()/span.Seconds() y := float64(height-padB) - plotH*(float64(point.value-minV)/float64(maxV-minV)) if y < float64(padT) { y = float64(padT) } if y > float64(height-padB) { y = float64(height - padB) } points = append(points, fmt.Sprintf("%.1f,%.1f", x, y)) lastX, lastY = x, y } midV := minV + (maxV-minV)/2 midT := start.Add(span / 2) x0 := float64(padL) x1 := float64(width - padR) yTop := float64(padT) yMid := float64(padT) + plotH/2 yBottom := float64(height - padB) var b strings.Builder b.WriteString(``) b.WriteString(``) b.WriteString(``) fmt.Fprintf(&b, ``, x0, yTop, x1) fmt.Fprintf(&b, ``, x0, yMid, x1) fmt.Fprintf(&b, ``, x0, yBottom, x1) fmt.Fprintf(&b, ``, x0, yTop, yBottom) fmt.Fprintf(&b, ``, x0+(plotW/2), yTop, yBottom) fmt.Fprintf(&b, ``, x1, yTop, yBottom) b.WriteString(``) b.WriteString(``) fmt.Fprintf(&b, `%s W`, x0-10, int(yTop)+14, formatGermanNumber(maxV)) fmt.Fprintf(&b, `%s W`, x0-10, int(yMid)+14, formatGermanNumber(midV)) fmt.Fprintf(&b, `0 W`, x0-10, int(yBottom)+14) fmt.Fprintf(&b, `%s`, x0, int(height)-10, start.Format("15:04")) fmt.Fprintf(&b, `%s`, x0+(plotW/2), int(height)-10, midT.Format("15:04")) fmt.Fprintf(&b, `%s`, x1, int(height)-10, end.Format("15:04")) b.WriteString(``) fmt.Fprintf(&b, ``, strings.Join(points, " ")) fmt.Fprintf(&b, ``, lastX, lastY) b.WriteString(``) return template.HTML(b.String()) } const faviconSVG = ` ` func (s *server) handleFavicon(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/favicon.svg" { http.NotFound(w, r) return } w.Header().Set("Content-Type", "image/svg+xml") _, _ = w.Write([]byte(faviconSVG)) } func (s *server) handleWrite(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } if got := r.Header.Get("X-Secret"); got == "" || got != s.secret { http.Error(w, "unauthorized", http.StatusUnauthorized) return } value, err := parseWatts(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } s.store.set(value) w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"watts": value}) } func parseWatts(r *http.Request) (int, error) { contentType := r.Header.Get("Content-Type") if strings.Contains(contentType, "application/json") { var payload struct { Watts *int `json:"watts"` } if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { return 0, errors.New("invalid json") } if payload.Watts == nil { return 0, errors.New("missing watts") } return *payload.Watts, nil } if err := r.ParseForm(); err != nil { return 0, errors.New("invalid form data") } if v := r.FormValue("watts"); v != "" { return strconv.Atoi(v) } return 0, errors.New("missing watts") }