up
This commit is contained in:
243
internal/api/device_manager.go
Normal file
243
internal/api/device_manager.go
Normal file
@@ -0,0 +1,243 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/config"
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/devices/antennagenius"
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/devices/powergenius"
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/devices/rotatorgenius"
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/devices/tunergenius"
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/devices/webswitch"
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/services/solar"
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/services/weather"
|
||||
)
|
||||
|
||||
type DeviceManager struct {
|
||||
config *config.Config
|
||||
|
||||
webSwitch *webswitch.Client
|
||||
powerGenius *powergenius.Client
|
||||
tunerGenius *tunergenius.Client
|
||||
antennaGenius *antennagenius.Client
|
||||
rotatorGenius *rotatorgenius.Client
|
||||
solarClient *solar.Client
|
||||
weatherClient *weather.Client
|
||||
|
||||
hub *Hub
|
||||
statusMu sync.RWMutex
|
||||
lastStatus *SystemStatus
|
||||
|
||||
updateInterval time.Duration
|
||||
stopChan chan struct{}
|
||||
}
|
||||
|
||||
type SystemStatus struct {
|
||||
WebSwitch *webswitch.Status `json:"webswitch"`
|
||||
PowerGenius *powergenius.Status `json:"power_genius"`
|
||||
TunerGenius *tunergenius.Status `json:"tuner_genius"`
|
||||
AntennaGenius *antennagenius.Status `json:"antenna_genius"`
|
||||
RotatorGenius *rotatorgenius.Status `json:"rotator_genius"`
|
||||
Solar *solar.SolarData `json:"solar"`
|
||||
Weather *weather.WeatherData `json:"weather"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
func NewDeviceManager(cfg *config.Config, hub *Hub) *DeviceManager {
|
||||
return &DeviceManager{
|
||||
config: cfg,
|
||||
hub: hub,
|
||||
updateInterval: 1 * time.Second, // Update status every second
|
||||
stopChan: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) Initialize() error {
|
||||
log.Println("Initializing device manager...")
|
||||
|
||||
// Initialize WebSwitch
|
||||
dm.webSwitch = webswitch.New(dm.config.Devices.WebSwitch.Host)
|
||||
|
||||
// Initialize Power Genius
|
||||
dm.powerGenius = powergenius.New(
|
||||
dm.config.Devices.PowerGenius.Host,
|
||||
dm.config.Devices.PowerGenius.Port,
|
||||
)
|
||||
|
||||
// Initialize Tuner Genius
|
||||
dm.tunerGenius = tunergenius.New(
|
||||
dm.config.Devices.TunerGenius.Host,
|
||||
dm.config.Devices.TunerGenius.Port,
|
||||
)
|
||||
|
||||
// Initialize Antenna Genius
|
||||
dm.antennaGenius = antennagenius.New(
|
||||
dm.config.Devices.AntennaGenius.Host,
|
||||
dm.config.Devices.AntennaGenius.Port,
|
||||
)
|
||||
|
||||
// Initialize Rotator Genius
|
||||
dm.rotatorGenius = rotatorgenius.New(
|
||||
dm.config.Devices.RotatorGenius.Host,
|
||||
dm.config.Devices.RotatorGenius.Port,
|
||||
)
|
||||
|
||||
// Initialize Solar data client
|
||||
dm.solarClient = solar.New()
|
||||
|
||||
// Initialize Weather client
|
||||
dm.weatherClient = weather.New(
|
||||
dm.config.Weather.OpenWeatherMapAPIKey,
|
||||
dm.config.Location.Latitude,
|
||||
dm.config.Location.Longitude,
|
||||
)
|
||||
|
||||
// Start PowerGenius continuous polling
|
||||
if err := dm.powerGenius.Start(); err != nil {
|
||||
log.Printf("Warning: Failed to start PowerGenius polling: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Device manager initialized")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) Start() error {
|
||||
log.Println("Starting device monitoring...")
|
||||
go dm.monitorDevices()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) Stop() {
|
||||
log.Println("Stopping device manager...")
|
||||
close(dm.stopChan)
|
||||
|
||||
// Close all connections
|
||||
if dm.powerGenius != nil {
|
||||
dm.powerGenius.Close()
|
||||
}
|
||||
if dm.tunerGenius != nil {
|
||||
dm.tunerGenius.Close()
|
||||
}
|
||||
if dm.antennaGenius != nil {
|
||||
dm.antennaGenius.Close()
|
||||
}
|
||||
if dm.rotatorGenius != nil {
|
||||
dm.rotatorGenius.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) monitorDevices() {
|
||||
ticker := time.NewTicker(dm.updateInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
dm.updateStatus()
|
||||
case <-dm.stopChan:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) updateStatus() {
|
||||
status := &SystemStatus{
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
// Query all devices
|
||||
// WebSwitch - get actual relay states
|
||||
if wsStatus, err := dm.webSwitch.GetStatus(); err == nil {
|
||||
status.WebSwitch = wsStatus
|
||||
} else {
|
||||
log.Printf("WebSwitch error: %v", err)
|
||||
}
|
||||
|
||||
// Power Genius
|
||||
if pgStatus, err := dm.powerGenius.GetStatus(); err == nil {
|
||||
status.PowerGenius = pgStatus
|
||||
} else {
|
||||
log.Printf("Power Genius error: %v", err)
|
||||
}
|
||||
|
||||
// // Tuner Genius
|
||||
// if tgStatus, err := dm.tunerGenius.GetStatus(); err == nil {
|
||||
// status.TunerGenius = tgStatus
|
||||
// } else {
|
||||
// log.Printf("Tuner Genius error: %v", err)
|
||||
// }
|
||||
|
||||
// // Antenna Genius
|
||||
// if agStatus, err := dm.antennaGenius.GetStatus(); err == nil {
|
||||
// status.AntennaGenius = agStatus
|
||||
// } else {
|
||||
// log.Printf("Antenna Genius error: %v", err)
|
||||
// }
|
||||
|
||||
// // Rotator Genius
|
||||
// if rgStatus, err := dm.rotatorGenius.GetStatus(); err == nil {
|
||||
// status.RotatorGenius = rgStatus
|
||||
// } else {
|
||||
// log.Printf("Rotator Genius error: %v", err)
|
||||
// }
|
||||
|
||||
// Solar Data (fetched every 15 minutes, cached)
|
||||
if solarData, err := dm.solarClient.GetSolarData(); err == nil {
|
||||
status.Solar = solarData
|
||||
} else {
|
||||
log.Printf("Solar data error: %v", err)
|
||||
}
|
||||
|
||||
// Weather Data (fetched every 10 minutes, cached)
|
||||
if weatherData, err := dm.weatherClient.GetWeatherData(); err == nil {
|
||||
status.Weather = weatherData
|
||||
} else {
|
||||
log.Printf("Weather data error: %v", err)
|
||||
}
|
||||
|
||||
// Update cached status
|
||||
dm.statusMu.Lock()
|
||||
dm.lastStatus = status
|
||||
dm.statusMu.Unlock()
|
||||
|
||||
// Broadcast to all connected clients
|
||||
if dm.hub != nil {
|
||||
dm.hub.BroadcastStatusUpdate(status)
|
||||
}
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) GetStatus() *SystemStatus {
|
||||
dm.statusMu.RLock()
|
||||
defer dm.statusMu.RUnlock()
|
||||
|
||||
if dm.lastStatus == nil {
|
||||
return &SystemStatus{
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
return dm.lastStatus
|
||||
}
|
||||
|
||||
// Device control methods
|
||||
func (dm *DeviceManager) WebSwitch() *webswitch.Client {
|
||||
return dm.webSwitch
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) PowerGenius() *powergenius.Client {
|
||||
return dm.powerGenius
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) TunerGenius() *tunergenius.Client {
|
||||
return dm.tunerGenius
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) AntennaGenius() *antennagenius.Client {
|
||||
return dm.antennaGenius
|
||||
}
|
||||
|
||||
func (dm *DeviceManager) RotatorGenius() *rotatorgenius.Client {
|
||||
return dm.rotatorGenius
|
||||
}
|
||||
373
internal/api/handlers.go
Normal file
373
internal/api/handlers.go
Normal file
@@ -0,0 +1,373 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.rouggy.com/rouggy/ShackMaster/internal/config"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
deviceManager *DeviceManager
|
||||
hub *Hub
|
||||
config *config.Config
|
||||
upgrader websocket.Upgrader
|
||||
}
|
||||
|
||||
func NewServer(dm *DeviceManager, hub *Hub, cfg *config.Config) *Server {
|
||||
return &Server{
|
||||
deviceManager: dm,
|
||||
hub: hub,
|
||||
config: cfg,
|
||||
upgrader: websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true // Allow all origins for now
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) SetupRoutes() *http.ServeMux {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// WebSocket endpoint
|
||||
mux.HandleFunc("/ws", s.handleWebSocket)
|
||||
|
||||
// REST API endpoints
|
||||
mux.HandleFunc("/api/status", s.handleGetStatus)
|
||||
mux.HandleFunc("/api/config", s.handleGetConfig)
|
||||
|
||||
// WebSwitch endpoints
|
||||
mux.HandleFunc("/api/webswitch/relay/on", s.handleWebSwitchRelayOn)
|
||||
mux.HandleFunc("/api/webswitch/relay/off", s.handleWebSwitchRelayOff)
|
||||
mux.HandleFunc("/api/webswitch/all/on", s.handleWebSwitchAllOn)
|
||||
mux.HandleFunc("/api/webswitch/all/off", s.handleWebSwitchAllOff)
|
||||
|
||||
// Rotator endpoints
|
||||
mux.HandleFunc("/api/rotator/move", s.handleRotatorMove)
|
||||
mux.HandleFunc("/api/rotator/cw", s.handleRotatorCW)
|
||||
mux.HandleFunc("/api/rotator/ccw", s.handleRotatorCCW)
|
||||
mux.HandleFunc("/api/rotator/stop", s.handleRotatorStop)
|
||||
|
||||
// Tuner endpoints
|
||||
mux.HandleFunc("/api/tuner/operate", s.handleTunerOperate)
|
||||
mux.HandleFunc("/api/tuner/tune", s.handleTunerAutoTune)
|
||||
mux.HandleFunc("/api/tuner/antenna", s.handleTunerAntenna)
|
||||
|
||||
// Antenna Genius endpoints
|
||||
mux.HandleFunc("/api/antenna/set", s.handleAntennaSet)
|
||||
|
||||
// Power Genius endpoints
|
||||
mux.HandleFunc("/api/power/fanmode", s.handlePowerFanMode)
|
||||
|
||||
// Static files (will be frontend)
|
||||
mux.Handle("/", http.FileServer(http.Dir("./web/dist")))
|
||||
|
||||
return mux
|
||||
}
|
||||
|
||||
func (s *Server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := s.upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("WebSocket upgrade error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
ServeWs(s.hub, conn)
|
||||
}
|
||||
|
||||
func (s *Server) handleGetStatus(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
status := s.deviceManager.GetStatus()
|
||||
s.sendJSON(w, status)
|
||||
}
|
||||
|
||||
func (s *Server) handleGetConfig(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// Only send public config info (not API keys)
|
||||
configInfo := map[string]interface{}{
|
||||
"callsign": s.config.Location.Callsign,
|
||||
"location": map[string]float64{
|
||||
"latitude": s.config.Location.Latitude,
|
||||
"longitude": s.config.Location.Longitude,
|
||||
},
|
||||
}
|
||||
|
||||
s.sendJSON(w, configInfo)
|
||||
}
|
||||
|
||||
// WebSwitch handlers
|
||||
func (s *Server) handleWebSwitchRelayOn(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
relay, err := strconv.Atoi(r.URL.Query().Get("relay"))
|
||||
if err != nil || relay < 1 || relay > 5 {
|
||||
http.Error(w, "Invalid relay number", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.WebSwitch().TurnOn(relay); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebSwitchRelayOff(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
relay, err := strconv.Atoi(r.URL.Query().Get("relay"))
|
||||
if err != nil || relay < 1 || relay > 5 {
|
||||
http.Error(w, "Invalid relay number", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.WebSwitch().TurnOff(relay); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebSwitchAllOn(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.WebSwitch().AllOn(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleWebSwitchAllOff(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.WebSwitch().AllOff(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// Rotator handlers
|
||||
func (s *Server) handleRotatorMove(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Rotator int `json:"rotator"`
|
||||
Azimuth int `json:"azimuth"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.RotatorGenius().MoveToAzimuth(req.Rotator, req.Azimuth); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleRotatorCW(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
rotator, err := strconv.Atoi(r.URL.Query().Get("rotator"))
|
||||
if err != nil || rotator < 1 || rotator > 2 {
|
||||
http.Error(w, "Invalid rotator number", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.RotatorGenius().RotateCW(rotator); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleRotatorCCW(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
rotator, err := strconv.Atoi(r.URL.Query().Get("rotator"))
|
||||
if err != nil || rotator < 1 || rotator > 2 {
|
||||
http.Error(w, "Invalid rotator number", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.RotatorGenius().RotateCCW(rotator); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleRotatorStop(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.RotatorGenius().Stop(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// Tuner handlers
|
||||
func (s *Server) handleTunerOperate(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Operate bool `json:"operate"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.TunerGenius().SetOperate(req.Operate); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleTunerAutoTune(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.TunerGenius().AutoTune(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleTunerAntenna(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Antenna int `json:"antenna"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.TunerGenius().ActivateAntenna(req.Antenna); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// Antenna Genius handlers
|
||||
func (s *Server) handleAntennaSet(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Radio int `json:"radio"`
|
||||
Antenna int `json:"antenna"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.AntennaGenius().SetRadioAntenna(req.Radio, req.Antenna); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// Power Genius handlers
|
||||
func (s *Server) handlePowerFanMode(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.deviceManager.PowerGenius().SetFanMode(req.Mode); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
s.sendJSON(w, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) sendJSON(w http.ResponseWriter, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
193
internal/api/websocket.go
Normal file
193
internal/api/websocket.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.rouggy.com/rouggy/ShackMaster/pkg/protocol"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type Hub struct {
|
||||
clients map[*Client]bool
|
||||
broadcast chan *protocol.WebSocketMessage
|
||||
register chan *Client
|
||||
unregister chan *Client
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
hub *Hub
|
||||
conn *websocket.Conn
|
||||
send chan *protocol.WebSocketMessage
|
||||
}
|
||||
|
||||
func NewHub() *Hub {
|
||||
return &Hub{
|
||||
clients: make(map[*Client]bool),
|
||||
broadcast: make(chan *protocol.WebSocketMessage, 256),
|
||||
register: make(chan *Client),
|
||||
unregister: make(chan *Client),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) Run() {
|
||||
for {
|
||||
select {
|
||||
case client := <-h.register:
|
||||
h.mu.Lock()
|
||||
h.clients[client] = true
|
||||
h.mu.Unlock()
|
||||
log.Printf("Client connected, total: %d", len(h.clients))
|
||||
|
||||
case client := <-h.unregister:
|
||||
h.mu.Lock()
|
||||
if _, ok := h.clients[client]; ok {
|
||||
delete(h.clients, client)
|
||||
close(client.send)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
log.Printf("Client disconnected, total: %d", len(h.clients))
|
||||
|
||||
case message := <-h.broadcast:
|
||||
h.mu.RLock()
|
||||
for client := range h.clients {
|
||||
select {
|
||||
case client.send <- message:
|
||||
default:
|
||||
// Client's send buffer is full, close it
|
||||
h.mu.RUnlock()
|
||||
h.unregister <- client
|
||||
h.mu.RLock()
|
||||
}
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) Broadcast(msg *protocol.WebSocketMessage) {
|
||||
h.broadcast <- msg
|
||||
}
|
||||
|
||||
func (h *Hub) ClientCount() int {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return len(h.clients)
|
||||
}
|
||||
|
||||
const (
|
||||
writeWait = 10 * time.Second
|
||||
pongWait = 60 * time.Second
|
||||
pingPeriod = (pongWait * 9) / 10
|
||||
maxMessageSize = 512 * 1024 // 512KB
|
||||
)
|
||||
|
||||
func (c *Client) readPump() {
|
||||
defer func() {
|
||||
c.hub.unregister <- c
|
||||
c.conn.Close()
|
||||
}()
|
||||
|
||||
c.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
c.conn.SetReadLimit(maxMessageSize)
|
||||
c.conn.SetPongHandler(func(string) error {
|
||||
c.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
return nil
|
||||
})
|
||||
|
||||
for {
|
||||
var msg protocol.WebSocketMessage
|
||||
err := c.conn.ReadJSON(&msg)
|
||||
if err != nil {
|
||||
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
||||
log.Printf("WebSocket error: %v", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// Handle incoming commands from client
|
||||
log.Printf("Received message: type=%s, device=%s", msg.Type, msg.Device)
|
||||
|
||||
// Commands are handled via REST API, not WebSocket
|
||||
// WebSocket is primarily for server -> client updates
|
||||
// Client should use REST endpoints for commands
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) writePump() {
|
||||
ticker := time.NewTicker(pingPeriod)
|
||||
defer func() {
|
||||
ticker.Stop()
|
||||
c.conn.Close()
|
||||
}()
|
||||
|
||||
for {
|
||||
select {
|
||||
case message, ok := <-c.send:
|
||||
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if !ok {
|
||||
// Hub closed the channel
|
||||
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
|
||||
return
|
||||
}
|
||||
|
||||
if err := c.conn.WriteJSON(message); err != nil {
|
||||
log.Printf("Error writing message: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
case <-ticker.C:
|
||||
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ServeWs(hub *Hub, conn *websocket.Conn) {
|
||||
client := &Client{
|
||||
hub: hub,
|
||||
conn: conn,
|
||||
send: make(chan *protocol.WebSocketMessage, 256),
|
||||
}
|
||||
|
||||
client.hub.register <- client
|
||||
|
||||
// Send initial status
|
||||
go func() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
client.send <- &protocol.WebSocketMessage{
|
||||
Type: protocol.MsgTypeStatus,
|
||||
Data: map[string]string{"status": "connected"},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
}()
|
||||
|
||||
go client.writePump()
|
||||
go client.readPump()
|
||||
}
|
||||
|
||||
// BroadcastStatusUpdate sends a status update to all connected clients
|
||||
func (h *Hub) BroadcastStatusUpdate(status interface{}) {
|
||||
data, err := json.Marshal(status)
|
||||
if err != nil {
|
||||
log.Printf("Error marshaling status: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
var statusMap map[string]interface{}
|
||||
if err := json.Unmarshal(data, &statusMap); err != nil {
|
||||
log.Printf("Error unmarshaling status: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
h.Broadcast(&protocol.WebSocketMessage{
|
||||
Type: protocol.MsgTypeUpdate,
|
||||
Data: statusMap,
|
||||
Timestamp: time.Now(),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user