97 lines
2.6 KiB
Go
97 lines
2.6 KiB
Go
package web
|
|
|
|
import (
|
|
"encoding/json"
|
|
"html/template"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
type RelaisData struct {
|
|
ID int `json:"id"`
|
|
Name string `json:"name"`
|
|
State bool `json:"state"`
|
|
}
|
|
|
|
type StatusResponse struct {
|
|
V1 float64 `json:"v1"`
|
|
V2 float64 `json:"v2"`
|
|
V3 float64 `json:"v3"`
|
|
V4 float64 `json:"v4"`
|
|
V5 float64 `json:"v5"`
|
|
Names []string `json:"names"` // Neu: Sendet die Namen als Array mit
|
|
Relais []RelaisData `json:"relais"`
|
|
Version string `json:"version"`
|
|
BuildDate string `json:"build_date"`
|
|
}
|
|
|
|
type Server struct {
|
|
port string
|
|
readVoltFunc func(channel int) float64
|
|
toggleFunc func(id int)
|
|
getRelais func() []RelaisData
|
|
versionFunc func() (string, string)
|
|
getNamesFunc func() []string // Neu hinzugefügt
|
|
}
|
|
|
|
func NewServer(port string, readVolt func(int) float64, toggle func(int), getRelais func() []RelaisData, getVersion func() (string, string), getNames func() []string) *Server {
|
|
return &Server{
|
|
port: port,
|
|
readVoltFunc: readVolt,
|
|
toggleFunc: toggle,
|
|
getRelais: getRelais,
|
|
versionFunc: getVersion,
|
|
getNamesFunc: getNames, // Neu hinzugefügt
|
|
}
|
|
}
|
|
|
|
func (s *Server) Start(certFile, keyFile string) error {
|
|
http.HandleFunc("/", s.handleIndex)
|
|
http.HandleFunc("/api/status", s.handleAPIStatus)
|
|
http.HandleFunc("/api/toggle", s.handleAPIToggle)
|
|
return http.ListenAndServeTLS(s.port, certFile, keyFile, nil)
|
|
}
|
|
|
|
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
|
ver, date := s.versionFunc()
|
|
tmpl, err := template.ParseFiles("web/static/index.html")
|
|
if err != nil {
|
|
http.Error(w, "Template nicht gefunden: "+err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
data := StatusResponse{
|
|
Names: s.getNamesFunc(), // Namen für das erste Rendern bereitstellen
|
|
Relais: s.getRelais(),
|
|
Version: ver,
|
|
BuildDate: date,
|
|
}
|
|
tmpl.Execute(w, data)
|
|
}
|
|
|
|
func (s *Server) handleAPIStatus(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
ver, date := s.versionFunc()
|
|
resp := StatusResponse{
|
|
V1: s.readVoltFunc(0),
|
|
V2: s.readVoltFunc(1),
|
|
V3: s.readVoltFunc(2),
|
|
V4: s.readVoltFunc(3),
|
|
V5: s.readVoltFunc(4),
|
|
Names: s.getNamesFunc(),
|
|
Relais: s.getRelais(),
|
|
Version: ver,
|
|
BuildDate: date,
|
|
}
|
|
json.NewEncoder(w).Encode(resp)
|
|
}
|
|
|
|
func (s *Server) handleAPIToggle(w http.ResponseWriter, r *http.Request) {
|
|
idStr := r.URL.Query().Get("id")
|
|
id, err := strconv.Atoi(idStr)
|
|
if err == nil {
|
|
s.toggleFunc(id)
|
|
}
|
|
s.handleAPIStatus(w, r)
|
|
}
|