Files
cacto 5674917f95 Доп. сигналы — отдельные устройства, а не sensor_type у существующего
Раньше "добавить сигнал" дописывал ещё один sensor_type к sensor-1 —
концептуально неверно и для дискретных входов, и тем более для выходов.
Теперь и вход (датчик), и выход (актуатор) создаются как полноценное
отдельное MQTT-устройство со своим external_id/zone_id — так же, как
завели бы новое Device на платформе.

state.Store обобщён: 4 фиксированных слота (плата, GPIO-пины, нельзя
удалить) + произвольное число доп. устройств (свой slot "extra-N",
можно удалить). HTTP: POST /api/devices (создать, kind=sensor|actuator),
DELETE /api/devices/{slot}.

На схеме доп. устройства подвешены к пину EXT пунктирным проводом —
визуально отделены от жёстко распаянных GPIO4/16/17/18. Можно указать
и произвольный пин (просто текстовая метка на схеме, без валидации) —
подписывается у провода вместо общего EXT.

Карточки создаются/удаляются динамически при получении снапшота через
SSE, без перезагрузки страницы.
2026-08-14 06:44:18 +05:00

200 lines
5.9 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", s.handleAddDevice)
s.mux.HandleFunc("DELETE /api/devices/{slot}", s.handleRemoveDevice)
s.mux.HandleFunc("POST /api/devices/{slot}/identity", s.handleSetIdentity)
s.mux.HandleFunc("POST /api/devices/{slot}/telemetry", s.handlePublishTelemetry)
}
// handleAddDevice creates a new standalone sensor (input) or actuator
// (output) device — a separate MQTT device_id, not another sensor_type or
// a manual override tacked onto an existing device. Mirrors how you'd
// actually add a second physical device to the platform (a new Device row
// with its own external_id).
func (s *Server) handleAddDevice(w http.ResponseWriter, r *http.Request) {
var req struct {
Kind string `json:"kind"` // "sensor" | "actuator"
SignalName string `json:"signal_name"`
ExternalID string `json:"external_id"`
ZoneID string `json:"zone_id"`
Pin string `json:"pin"`
Discrete bool `json:"discrete"`
SupportsLevel bool `json:"supports_level"`
}
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
}
var slot string
switch req.Kind {
case "sensor":
if req.SignalName == "" {
http.Error(w, "signal_name is required for a sensor device", http.StatusBadRequest)
return
}
slot = s.store.AddSensorDevice(req.SignalName, req.ExternalID, req.ZoneID, req.Pin, req.Discrete)
case "actuator":
slot = s.store.AddActuatorDevice(req.ExternalID, req.ZoneID, req.Pin, req.SupportsLevel)
default:
http.Error(w, `kind must be "sensor" or "actuator"`, http.StatusBadRequest)
return
}
writeJSON(w, http.StatusCreated, s.store.Snapshot())
s.logger.Info("extra device added", "slot", slot, "kind", req.Kind, "device_id", req.ExternalID)
}
func (s *Server) handleRemoveDevice(w http.ResponseWriter, r *http.Request) {
slot := r.PathValue("slot")
if !s.store.RemoveDevice(slot) {
http.Error(w, "unknown or non-removable slot", http.StatusBadRequest)
return
}
writeJSON(w, http.StatusOK, s.store.Snapshot())
}
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)
}