Доп. сигналы — отдельные устройства, а не 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, без перезагрузки страницы.
This commit is contained in:
@@ -43,10 +43,60 @@ func (s *Server) routes() {
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user