Files
home_automation_emulator/internal/httpserver/server.go
T
cacto 0eed35289c ESP32 Emulator: веб-морда контроллера гроубокса поверх MQTT
Go-сервис без внешних фронтенд-зависимостей: embedded HTML-страница
с SVG-изображением платы (датчик + вентилятор + свет + помпа) и
Server-Sent Events для live-обновления. Слушает devices/+/commands
и реально отвечает ack'ом, публикует devices/{id}/telemetry —
протокол зеркалит ingest-service/device-control-service основного
репозитория, общего кода между репозиториями нет. Дефолтные
external_id (sensor-1/fan-1/light-1/pump-1) совпадают с
DemoGrowboxSeeder платформы.
2026-08-13 11:12:29 +05:00

150 lines
4.0 KiB
Go

// Package httpserver is the emulator's own control surface: a web UI (the
// "controller board") plus the JSON/SSE API it talks to. This is separate
// from the MQTT side — the browser never speaks MQTT directly, it asks this
// server to do so.
package httpserver
import (
"embed"
"encoding/json"
"fmt"
"io/fs"
"log/slog"
"net/http"
"git.cactoz.su/cacto/home_automation_emulator/internal/mqttclient"
"git.cactoz.su/cacto/home_automation_emulator/internal/state"
)
//go:embed web
var webFS embed.FS
type Server struct {
store *state.Store
mqtt *mqttclient.Client
logger *slog.Logger
mux *http.ServeMux
}
func New(store *state.Store, mqtt *mqttclient.Client, logger *slog.Logger) *Server {
s := &Server{store: store, mqtt: mqtt, logger: logger, mux: http.NewServeMux()}
s.routes()
return s
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mux.ServeHTTP(w, r) }
func (s *Server) routes() {
static, err := fs.Sub(webFS, "web")
if err != nil {
panic(err) // embedded FS is compiled in — can only fail if the embed directive itself is wrong
}
s.mux.Handle("GET /", http.FileServerFS(static))
s.mux.HandleFunc("GET /api/snapshot", s.handleSnapshot)
s.mux.HandleFunc("GET /api/events", s.handleEvents)
s.mux.HandleFunc("POST /api/devices/{slot}/identity", s.handleSetIdentity)
s.mux.HandleFunc("POST /api/devices/{slot}/telemetry", s.handlePublishTelemetry)
}
func (s *Server) handleSnapshot(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, s.store.Snapshot())
}
func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
ch, unsubscribe := s.store.Subscribe()
defer unsubscribe()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
writeEvent(w, s.store.Snapshot())
flusher.Flush()
for {
select {
case <-r.Context().Done():
return
case snap, ok := <-ch:
if !ok {
return
}
writeEvent(w, snap)
flusher.Flush()
}
}
}
func writeEvent(w http.ResponseWriter, snap state.Snapshot) {
body, err := json.Marshal(snap)
if err != nil {
return
}
fmt.Fprintf(w, "data: %s\n\n", body)
}
func (s *Server) handleSetIdentity(w http.ResponseWriter, r *http.Request) {
slot := r.PathValue("slot")
if _, ok := s.store.Device(slot); !ok {
http.Error(w, "unknown slot", http.StatusNotFound)
return
}
var req struct {
ExternalID string `json:"external_id"`
ZoneID string `json:"zone_id"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ExternalID == "" || req.ZoneID == "" {
http.Error(w, "external_id and zone_id are required", http.StatusBadRequest)
return
}
s.store.SetIdentity(slot, req.ExternalID, req.ZoneID)
writeJSON(w, http.StatusOK, s.store.Snapshot())
}
func (s *Server) handlePublishTelemetry(w http.ResponseWriter, r *http.Request) {
slot := r.PathValue("slot")
device, ok := s.store.Device(slot)
if !ok {
http.Error(w, "unknown slot", http.StatusNotFound)
return
}
if device.Kind != state.KindSensor {
http.Error(w, "slot is not a sensor", http.StatusBadRequest)
return
}
var req struct {
SensorType string `json:"sensor_type"`
Value float64 `json:"value"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.SensorType == "" {
http.Error(w, "sensor_type is required", http.StatusBadRequest)
return
}
s.store.SetReading(slot, req.SensorType, req.Value)
if err := s.mqtt.PublishTelemetry(device.ExternalID, device.ZoneID, req.SensorType, req.Value); err != nil {
s.logger.Error("publish telemetry failed", "slot", slot, "error", err)
http.Error(w, "failed to publish to mqtt", http.StatusBadGateway)
return
}
writeJSON(w, http.StatusOK, s.store.Snapshot())
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}