rot finished

This commit is contained in:
2026-01-09 11:56:40 +01:00
parent 1ee0afa088
commit ac99f291a7
30 changed files with 5581 additions and 293 deletions

View File

@@ -0,0 +1,267 @@
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
log.Printf("Initializing RotatorGenius: host=%s port=%d", dm.config.Devices.RotatorGenius.Host, dm.config.Devices.RotatorGenius.Port)
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 device polling in background (non-blocking)
go func() {
if err := dm.powerGenius.Start(); err != nil {
log.Printf("Warning: Failed to start PowerGenius polling: %v", err)
}
}()
go func() {
if err := dm.tunerGenius.Start(); err != nil {
log.Printf("Warning: Failed to start TunerGenius polling: %v", err)
}
}()
go func() {
if err := dm.antennaGenius.Start(); err != nil {
log.Printf("Warning: Failed to start AntennaGenius polling: %v", err)
}
}()
log.Println("About to launch RotatorGenius goroutine...")
go func() {
log.Println("Starting RotatorGenius polling goroutine...")
if err := dm.rotatorGenius.Start(); err != nil {
log.Printf("Warning: Failed to start RotatorGenius polling: %v", err)
}
}()
log.Println("RotatorGenius goroutine launched")
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
}

399
internal/api/handlers.go Normal file
View File

@@ -0,0 +1,399 @@
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/heading", s.handleRotatorHeading)
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/bypass", s.handleTunerBypass)
mux.HandleFunc("/api/tuner/autotune", s.handleTunerAutoTune)
// Antenna Genius endpoints
mux.HandleFunc("/api/antenna/select", s.handleAntennaSelect)
mux.HandleFunc("/api/antenna/reboot", s.handleAntennaReboot)
// Power Genius endpoints
mux.HandleFunc("/api/power/fanmode", s.handlePowerFanMode)
mux.HandleFunc("/api/power/operate", s.handlePowerOperate)
// 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) handleRotatorHeading(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Heading int `json:"heading"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if err := s.deviceManager.RotatorGenius().SetHeading(req.Heading); 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
}
if err := s.deviceManager.RotatorGenius().RotateCW(); 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
}
if err := s.deviceManager.RotatorGenius().RotateCCW(); 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 {
Value int `json:"value"`
}
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.Value); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.sendJSON(w, map[string]string{"status": "ok"})
}
func (s *Server) handleTunerBypass(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Value int `json:"value"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if err := s.deviceManager.TunerGenius().SetBypass(req.Value); 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"})
}
// Antenna Genius handlers
func (s *Server) handleAntennaSelect(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Port int `json:"port"`
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().SetAntenna(req.Port, req.Antenna); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.sendJSON(w, map[string]string{"status": "ok"})
}
func (s *Server) handleAntennaReboot(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if err := s.deviceManager.AntennaGenius().Reboot(); 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) handlePowerOperate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Value int `json:"value"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if err := s.deviceManager.PowerGenius().SetOperate(req.Value); 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
View 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(),
})
}