UCPS_WS26-27/UCPSMain/main.go

272 lines
7.1 KiB
Go

// Local heating server.
//
// - Serves index.html to browsers on the same network.
// - Keeps all values in memory (lost when the server stops).
// - GET /api/state -> everything the website needs (JSON)
// - POST /api/update -> website changes settings (JSON, partial updates)
// - GET /api/arduino -> Arduino sends its data as query parameters and
// gets its orders back as plain text
//
// Run: go run .
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"strconv"
"sync"
"time"
)
const (
listenAddr = ":8080" // all network interfaces, port 8080
onlineTimeout = 15 * time.Second // Arduino counts as offline after this
minTemp = 5.0
maxTemp = 30.0
)
// Confirmed group value (what "Automatic" mode uses).
type Confirmed struct {
A float64 `json:"a"`
B float64 `json:"b"`
Soll float64 `json:"soll"`
}
// Settings that the website changes.
type Settings struct {
Mode string `json:"mode"` // "auto" or "manual"
Mine [2]float64 `json:"mine"` // my own wish range
Others [][2]float64 `json:"others"`
Confirmed Confirmed `json:"confirmed"`
SelfTemp float64 `json:"selfTemp"` // manual target
}
// What the website receives.
type View struct {
Settings
Target float64 `json:"target"` // value the Arduino is told to hold
Indoor *float64 `json:"indoor"` // null while the Arduino is offline
Heating bool `json:"heating"`
Online bool `json:"online"`
}
type Server struct {
mu sync.Mutex
s Settings
// live data from the Arduino
indoor float64
haveIndoor bool
heating bool
lastSeen time.Time
}
func newServer() *Server {
return &Server{
s: Settings{
Mode: "auto",
Mine: [2]float64{18, 22},
Others: [][2]float64{{20, 24}, {21, 21}, {20, 22}},
// Result of the group aggregation for the default ranges above.
Confirmed: Confirmed{A: 21, B: 21, Soll: 21},
SelfTemp: 21,
},
}
}
// target returns the temperature the heating should hold. Caller holds the lock.
func (sv *Server) target() float64 {
if sv.s.Mode == "manual" {
return sv.s.SelfTemp
}
return sv.s.Confirmed.Soll
}
// view builds the JSON for the website. Caller holds the lock.
func (sv *Server) view() View {
online := !sv.lastSeen.IsZero() && time.Since(sv.lastSeen) < onlineTimeout
v := View{
Settings: sv.s,
Target: sv.target(),
Heating: online && sv.heating,
Online: online,
}
if online && sv.haveIndoor {
t := sv.indoor
v.Indoor = &t
}
return v
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func validTemp(t float64) bool { return t >= minTemp && t <= maxTemp }
// ---------- Website ----------
func (sv *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Cache-Control", "no-store")
http.ServeFile(w, r, "index.html") // read from disk: edit + refresh, no restart
}
func (sv *Server) handleState(w http.ResponseWriter, r *http.Request) {
sv.mu.Lock()
v := sv.view()
sv.mu.Unlock()
writeJSON(w, http.StatusOK, v)
}
// Every field is optional: only the fields that are sent are changed.
type update struct {
Mode *string `json:"mode"`
Mine *[2]float64 `json:"mine"`
SelfTemp *float64 `json:"selfTemp"`
Confirmed *Confirmed `json:"confirmed"`
}
func (sv *Server) handleUpdate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 4096)
var u update
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
// Validate everything first, then apply.
if u.Mode != nil && *u.Mode != "auto" && *u.Mode != "manual" {
http.Error(w, "mode must be auto or manual", http.StatusBadRequest)
return
}
if u.Mine != nil && (!validTemp(u.Mine[0]) || !validTemp(u.Mine[1]) || u.Mine[0] > u.Mine[1]) {
http.Error(w, "invalid range", http.StatusBadRequest)
return
}
if u.SelfTemp != nil && !validTemp(*u.SelfTemp) {
http.Error(w, "invalid temperature", http.StatusBadRequest)
return
}
if u.Confirmed != nil && (!validTemp(u.Confirmed.A) || !validTemp(u.Confirmed.B) ||
!validTemp(u.Confirmed.Soll) || u.Confirmed.A > u.Confirmed.B) {
http.Error(w, "invalid confirmed value", http.StatusBadRequest)
return
}
sv.mu.Lock()
if u.Mode != nil {
sv.s.Mode = *u.Mode
}
if u.Mine != nil {
sv.s.Mine = *u.Mine
}
if u.SelfTemp != nil {
sv.s.SelfTemp = *u.SelfTemp
}
if u.Confirmed != nil {
sv.s.Confirmed = *u.Confirmed
}
v := sv.view()
log.Printf("web: update -> mode=%s target=%.1f", v.Mode, v.Target)
sv.mu.Unlock()
writeJSON(w, http.StatusOK, v)
}
// ---------- Arduino ----------
// GET /api/arduino?temp=21.5&heat=1
//
// temp: indoor temperature (omitted if the sensor has no valid value)
// heat: 1 if the Arduino currently wants to heat, else 0
//
// Response (plain text): mode=A;target=21.00
func (sv *Server) handleArduino(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
sv.mu.Lock()
// ParseFloat also accepts "nan"; the range check rejects it.
if t, err := strconv.ParseFloat(q.Get("temp"), 64); err == nil && t > -40 && t < 80 {
sv.indoor, sv.haveIndoor = t, true
} else {
sv.haveIndoor = false
}
sv.heating = q.Get("heat") == "1"
sv.lastSeen = time.Now()
letter := "A"
if sv.s.Mode == "manual" {
letter = "M"
}
target := sv.target()
log.Printf("arduino: indoor=%.1f (valid=%v) heat=%v -> mode=%s target=%.2f",
sv.indoor, sv.haveIndoor, sv.heating, letter, target)
sv.mu.Unlock()
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Cache-Control", "no-store")
fmt.Fprintf(w, "mode=%s;target=%.2f\n", letter, target)
}
// ---------- Start ----------
func printAddresses() {
ifaces, err := net.Interfaces()
if err != nil {
return
}
fmt.Println("Heating server is running. Addresses of this PC (adapter name in brackets):")
for _, ifc := range ifaces {
if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 {
continue
}
addrs, err := ifc.Addrs()
if err != nil {
continue
}
for _, a := range addrs {
ipnet, ok := a.(*net.IPNet)
if !ok || ipnet.IP.To4() == nil || ipnet.IP.IsLinkLocalUnicast() {
continue // skip IPv6 and 169.254.x.x (adapter without a real connection)
}
fmt.Printf(" http://%s%s [%s]\n", ipnet.IP, listenAddr, ifc.Name)
}
}
fmt.Println("Use the address of your Wi-Fi adapter (connected to the phone hotspot) as SERVER_IP in the Arduino sketch.")
}
func main() {
sv := newServer()
mux := http.NewServeMux()
mux.HandleFunc("/", sv.handleIndex)
mux.HandleFunc("/api/state", sv.handleState)
mux.HandleFunc("/api/update", sv.handleUpdate)
mux.HandleFunc("/api/arduino", sv.handleArduino)
srv := &http.Server{
Addr: listenAddr,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
printAddresses()
log.Fatal(srv.ListenAndServe())
}