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

75
cmd/server/main.go Normal file
View File

@@ -0,0 +1,75 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"git.rouggy.com/rouggy/ShackMaster/internal/api"
"git.rouggy.com/rouggy/ShackMaster/internal/config"
)
func main() {
log.Println("Starting ShackMaster server...")
// Load configuration
cfg, err := config.Load("configs/config.yaml")
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
log.Printf("Configuration loaded: %s:%d", cfg.Server.Host, cfg.Server.Port)
// Create WebSocket hub
hub := api.NewHub()
go hub.Run()
// Initialize device manager with hub
deviceManager := api.NewDeviceManager(cfg, hub)
if err := deviceManager.Initialize(); err != nil {
log.Fatalf("Failed to initialize device manager: %v", err)
}
// Start device monitoring (will broadcast automatically)
if err := deviceManager.Start(); err != nil {
log.Fatalf("Failed to start device manager: %v", err)
}
// Create HTTP server
server := api.NewServer(deviceManager, hub, cfg)
mux := server.SetupRoutes()
// Setup HTTP server
addr := fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port)
httpServer := &http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Start HTTP server in goroutine
go func() {
log.Printf("Server listening on %s", addr)
log.Printf("WebSocket endpoint: ws://%s/ws", addr)
log.Printf("Web interface: http://%s/", addr)
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("HTTP server error: %v", err)
}
}()
// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
deviceManager.Stop()
log.Println("Server stopped")
}

View File

@@ -13,7 +13,6 @@ devices:
tuner_genius:
host: "10.10.10.129"
port: 9010
id_number: 1 # Default ID for commands
antenna_genius:
host: "10.10.10.130"

5
go.mod
View File

@@ -2,4 +2,7 @@ module git.rouggy.com/rouggy/ShackMaster
go 1.24.3
require gopkg.in/yaml.v3 v3.0.1 // indirect
require (
github.com/gorilla/websocket v1.5.3
gopkg.in/yaml.v3 v3.0.1
)

3
go.sum
View File

@@ -1,3 +1,6 @@
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

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(),
})
}

View File

@@ -37,9 +37,8 @@ type PowerGeniusConfig struct {
}
type TunerGeniusConfig struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
IDNumber int `yaml:"id_number"`
Host string `yaml:"host"`
Port int `yaml:"port"`
}
type AntennaGeniusConfig struct {

View File

@@ -0,0 +1,437 @@
package antennagenius
import (
"bufio"
"fmt"
"log"
"net"
"strconv"
"strings"
"sync"
"time"
)
type Client struct {
host string
port int
conn net.Conn
reader *bufio.Reader
connMu sync.Mutex
lastStatus *Status
statusMu sync.RWMutex
antennas []Antenna
antennasMu sync.RWMutex
stopChan chan struct{}
running bool
}
type Status struct {
PortA *PortStatus `json:"port_a"`
PortB *PortStatus `json:"port_b"`
Antennas []Antenna `json:"antennas"`
Connected bool `json:"connected"`
}
type PortStatus struct {
Auto bool `json:"auto"`
Source string `json:"source"`
Band int `json:"band"`
Frequency float64 `json:"frequency"`
Nickname string `json:"nickname"`
RxAnt int `json:"rx_ant"`
TxAnt int `json:"tx_ant"`
InBand int `json:"in_band"`
TX bool `json:"tx"`
Inhibit int `json:"inhibit"`
}
type Antenna struct {
Number int `json:"number"`
Name string `json:"name"`
TX string `json:"tx"`
RX string `json:"rx"`
InBand string `json:"in_band"`
Hotkey int `json:"hotkey"`
}
func New(host string, port int) *Client {
return &Client{
host: host,
port: port,
stopChan: make(chan struct{}),
}
}
func (c *Client) Connect() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
return nil
}
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", c.host, c.port), 5*time.Second)
if err != nil {
return fmt.Errorf("failed to connect: %w", err)
}
c.conn = conn
c.reader = bufio.NewReader(c.conn)
// Read and discard banner
_, _ = c.reader.ReadString('\n')
return nil
}
func (c *Client) Close() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.stopChan != nil {
close(c.stopChan)
}
if c.conn != nil {
return c.conn.Close()
}
return nil
}
func (c *Client) Start() error {
if c.running {
return nil
}
_ = c.Connect()
c.running = true
go c.pollLoop()
return nil
}
func (c *Client) pollLoop() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
initialized := false
for {
select {
case <-ticker.C:
c.connMu.Lock()
if c.conn == nil {
c.connMu.Unlock()
c.statusMu.Lock()
c.lastStatus = &Status{Connected: false}
c.statusMu.Unlock()
if err := c.Connect(); err != nil {
continue
}
initialized = false
c.connMu.Lock()
}
c.connMu.Unlock()
// Initialize: get antenna list and subscribe
if !initialized {
if err := c.initialize(); err != nil {
log.Printf("AntennaGenius init error: %v", err)
c.connMu.Lock()
if c.conn != nil {
c.conn.Close()
c.conn = nil
c.reader = nil
}
c.connMu.Unlock()
continue
}
initialized = true
}
// Read spontaneous messages from subscription
c.connMu.Lock()
if c.conn != nil && c.reader != nil {
c.conn.SetReadDeadline(time.Now().Add(150 * time.Millisecond))
for {
line, err := c.reader.ReadString('\n')
if err != nil {
break
}
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "S") {
c.parsePortStatus(line)
}
}
}
c.connMu.Unlock()
case <-c.stopChan:
return
}
}
}
func (c *Client) initialize() error {
// Get antenna list
antennas, err := c.getAntennaList()
if err != nil {
return fmt.Errorf("failed to get antenna list: %w", err)
}
c.antennasMu.Lock()
c.antennas = antennas
c.antennasMu.Unlock()
// Subscribe to port updates
if err := c.subscribeToPortUpdates(); err != nil {
return fmt.Errorf("failed to subscribe: %w", err)
}
// Initialize status
c.statusMu.Lock()
c.lastStatus = &Status{
PortA: &PortStatus{},
PortB: &PortStatus{},
Antennas: antennas,
Connected: true,
}
c.statusMu.Unlock()
return nil
}
func (c *Client) sendCommand(cmd string) (string, error) {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn == nil || c.reader == nil {
return "", fmt.Errorf("not connected")
}
// AntennaGenius only accepts C1| for all commands
fullCmd := fmt.Sprintf("C1|%s\n", cmd)
_, err := c.conn.Write([]byte(fullCmd))
if err != nil {
c.conn = nil
c.reader = nil
return "", fmt.Errorf("failed to send command: %w", err)
}
// Read all response lines using shared reader
var response strings.Builder
// Set a read timeout to avoid blocking forever
c.conn.SetReadDeadline(time.Now().Add(2 * time.Second))
defer c.conn.SetReadDeadline(time.Time{})
for {
line, err := c.reader.ReadString('\n')
if err != nil {
if response.Len() > 0 {
// We got some data, return it
break
}
c.conn = nil
c.reader = nil
return "", fmt.Errorf("failed to read response: %w", err)
}
response.WriteString(line)
// Parse spontaneous status updates
trimmedLine := strings.TrimSpace(line)
if strings.HasPrefix(trimmedLine, "S0|") {
c.connMu.Unlock()
c.parsePortStatus(trimmedLine)
c.connMu.Lock()
}
// Check if this is the last line (empty line or timeout)
if trimmedLine == "" {
break
}
}
return response.String(), nil
}
func (c *Client) getAntennaList() ([]Antenna, error) {
resp, err := c.sendCommand("antenna list")
if err != nil {
return nil, err
}
var antennas []Antenna
// Response format: R<id>|0|antenna <num> name=<name> tx=<hex> rx=<hex> inband=<hex> hotkey=<num>
lines := strings.Split(resp, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if !strings.Contains(line, "antenna ") {
continue
}
antenna := c.parseAntennaLine(line)
// Skip unconfigured antennas (name = Antenna X with space)
if strings.HasPrefix(antenna.Name, "Antenna ") {
continue
}
antennas = append(antennas, antenna)
}
return antennas, nil
}
func (c *Client) parseAntennaLine(line string) Antenna {
antenna := Antenna{}
// Extract antenna number
if idx := strings.Index(line, "antenna "); idx != -1 {
rest := line[idx+8:]
parts := strings.Fields(rest)
if len(parts) > 0 {
antenna.Number, _ = strconv.Atoi(parts[0])
}
}
// Parse key=value pairs
pairs := strings.Fields(line)
for _, pair := range pairs {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
continue
}
key := kv[0]
value := kv[1]
switch key {
case "name":
// Replace underscores with spaces
antenna.Name = strings.ReplaceAll(value, "_", " ")
case "tx":
antenna.TX = value
case "rx":
antenna.RX = value
case "inband":
antenna.InBand = value
case "hotkey":
antenna.Hotkey, _ = strconv.Atoi(value)
}
}
return antenna
}
func (c *Client) subscribeToPortUpdates() error {
resp, err := c.sendCommand("sub port all")
if err != nil {
return err
}
// Parse initial port status from subscription response
// The response may contain S0|port messages with current status
lines := strings.Split(resp, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "S0|port") {
c.parsePortStatus(line)
}
}
return nil
}
func (c *Client) parsePortStatus(line string) {
// Format: S0|port <id> auto=<0|1> source=<src> band=<n> freq=<f> nickname=<name> rxant=<n> txant=<n> inband=<n> tx=<0|1> inhibit=<n>
var portID int
portStatus := &PortStatus{}
// Extract port ID
if idx := strings.Index(line, "port "); idx != -1 {
rest := line[idx+5:]
parts := strings.Fields(rest)
if len(parts) > 0 {
portID, _ = strconv.Atoi(parts[0])
}
}
// Parse key=value pairs
pairs := strings.Fields(line)
for _, pair := range pairs {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
continue
}
key := kv[0]
value := kv[1]
switch key {
case "auto":
portStatus.Auto = value == "1"
case "source":
portStatus.Source = value
case "band":
portStatus.Band, _ = strconv.Atoi(value)
case "freq":
portStatus.Frequency, _ = strconv.ParseFloat(value, 64)
case "nickname":
portStatus.Nickname = value
case "rxant":
portStatus.RxAnt, _ = strconv.Atoi(value)
case "txant":
portStatus.TxAnt, _ = strconv.Atoi(value)
case "inband":
portStatus.InBand, _ = strconv.Atoi(value)
case "tx":
portStatus.TX = value == "1"
case "inhibit":
portStatus.Inhibit, _ = strconv.Atoi(value)
}
}
// Update status
c.statusMu.Lock()
if c.lastStatus != nil {
if portID == 1 {
c.lastStatus.PortA = portStatus
} else if portID == 2 {
c.lastStatus.PortB = portStatus
}
}
c.statusMu.Unlock()
}
func (c *Client) GetStatus() (*Status, error) {
c.statusMu.RLock()
defer c.statusMu.RUnlock()
if c.lastStatus == nil {
return &Status{Connected: false}, nil
}
return c.lastStatus, nil
}
// SetAntenna sets the antenna for a specific port
func (c *Client) SetAntenna(port, antenna int) error {
cmd := fmt.Sprintf("port set %d rxant=%d", port, antenna)
_, err := c.sendCommand(cmd)
return err
}
// Reboot reboots the device
func (c *Client) Reboot() error {
_, err := c.sendCommand("reboot")
return err
}

View File

@@ -0,0 +1,35 @@
package devices
import "sync"
// CommandIDManager manages the global command ID counter for 4O3A devices
// All 4O3A devices share the same command ID sequence
type CommandIDManager struct {
mu sync.Mutex
counter int
}
var globalCommandID = &CommandIDManager{
counter: 0,
}
// GetNextID returns the next command ID and increments the counter
func (m *CommandIDManager) GetNextID() int {
m.mu.Lock()
defer m.mu.Unlock()
m.counter++
return m.counter
}
// Reset resets the counter to 0 (useful for testing or restart)
func (m *CommandIDManager) Reset() {
m.mu.Lock()
defer m.mu.Unlock()
m.counter = 0
}
// GetGlobalCommandID returns the global command ID manager
func GetGlobalCommandID() *CommandIDManager {
return globalCommandID
}

View File

@@ -0,0 +1,413 @@
package powergenius
import (
"bufio"
"fmt"
"math"
"net"
"strconv"
"strings"
"sync"
"time"
. "git.rouggy.com/rouggy/ShackMaster/internal/devices"
)
type Client struct {
host string
port int
conn net.Conn
connMu sync.Mutex
lastStatus *Status
statusMu sync.RWMutex
stopChan chan struct{}
running bool
}
type Status struct {
PowerForward float64 `json:"power_forward"`
PowerReflected float64 `json:"power_reflected"`
SWR float64 `json:"swr"`
Voltage float64 `json:"voltage"`
VDD float64 `json:"vdd"`
Current float64 `json:"current"`
PeakCurrent float64 `json:"peak_current"`
Temperature float64 `json:"temperature"`
HarmonicLoadTemp float64 `json:"harmonic_load_temp"`
FanSpeed int `json:"fan_speed"`
FanMode string `json:"fan_mode"`
State string `json:"state"`
BandA string `json:"band_a"`
BandB string `json:"band_b"`
FaultPresent bool `json:"fault_present"`
Connected bool `json:"connected"`
}
func New(host string, port int) *Client {
return &Client{
host: host,
port: port,
stopChan: make(chan struct{}),
}
}
func (c *Client) Connect() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
return nil // Already connected
}
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", c.host, c.port), 5*time.Second)
if err != nil {
return fmt.Errorf("failed to connect: %w", err)
}
c.conn = conn
// Read and discard version banner
reader := bufio.NewReader(c.conn)
_, _ = reader.ReadString('\n')
return nil
}
func (c *Client) Close() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.stopChan != nil {
close(c.stopChan)
}
if c.conn != nil {
return c.conn.Close()
}
return nil
}
// Start begins continuous polling of the device
func (c *Client) Start() error {
if c.running {
return nil
}
// Try to connect, but don't fail if it doesn't work
// The poll loop will keep trying
_ = c.Connect()
c.running = true
go c.pollLoop()
return nil
}
// pollLoop continuously polls the device for status
func (c *Client) pollLoop() {
ticker := time.NewTicker(150 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Try to reconnect if not connected
c.connMu.Lock()
if c.conn == nil {
c.connMu.Unlock()
// Mark as disconnected and reset all values
c.statusMu.Lock()
c.lastStatus = &Status{
Connected: false,
}
c.statusMu.Unlock()
if err := c.Connect(); err != nil {
// Silent fail, will retry on next tick
continue
}
c.connMu.Lock()
}
c.connMu.Unlock()
status, err := c.queryStatus()
if err != nil {
// Connection lost, close and retry next tick
c.connMu.Lock()
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
c.connMu.Unlock()
// Mark as disconnected and reset all values
c.statusMu.Lock()
c.lastStatus = &Status{
Connected: false,
}
c.statusMu.Unlock()
continue
}
// Mark as connected
status.Connected = true
// Merge with existing status (spontaneous messages may only update some fields)
c.statusMu.Lock()
if c.lastStatus != nil {
// Keep existing values for fields not in the new status
if status.PowerForward == 0 && c.lastStatus.PowerForward != 0 {
status.PowerForward = c.lastStatus.PowerForward
}
if status.Temperature == 0 && c.lastStatus.Temperature != 0 {
status.Temperature = c.lastStatus.Temperature
}
if status.HarmonicLoadTemp == 0 && c.lastStatus.HarmonicLoadTemp != 0 {
status.HarmonicLoadTemp = c.lastStatus.HarmonicLoadTemp
}
if status.Voltage == 0 && c.lastStatus.Voltage != 0 {
status.Voltage = c.lastStatus.Voltage
}
if status.FanMode == "" && c.lastStatus.FanMode != "" {
status.FanMode = c.lastStatus.FanMode
}
if status.BandA == "" && c.lastStatus.BandA != "" {
status.BandA = c.lastStatus.BandA
}
if status.BandB == "" && c.lastStatus.BandB != "" {
status.BandB = c.lastStatus.BandB
}
}
c.lastStatus = status
c.statusMu.Unlock()
case <-c.stopChan:
return
}
}
}
func (c *Client) queryStatus() (*Status, error) {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn == nil {
return nil, fmt.Errorf("not connected")
}
// Get next command ID from global counter
cmdID := GetGlobalCommandID().GetNextID()
// Format command with ID: C<id>|status
fullCmd := fmt.Sprintf("C%d|status\n", cmdID)
// Send command
_, err := c.conn.Write([]byte(fullCmd))
if err != nil {
c.conn = nil
return nil, fmt.Errorf("failed to send command: %w", err)
}
// Read response
reader := bufio.NewReader(c.conn)
response, err := reader.ReadString('\n')
if err != nil {
c.conn = nil
return nil, fmt.Errorf("failed to read response: %w", err)
}
return c.parseStatus(strings.TrimSpace(response))
}
func (c *Client) sendCommand(cmd string) (string, error) {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn == nil {
return "", fmt.Errorf("not connected")
}
// Get next command ID from global counter
cmdID := GetGlobalCommandID().GetNextID()
// Format command with ID: C<id>|<command>
fullCmd := fmt.Sprintf("C%d|%s\n", cmdID, cmd)
// Send command
_, err := c.conn.Write([]byte(fullCmd))
if err != nil {
c.conn = nil
return "", fmt.Errorf("failed to send command: %w", err)
}
// Read response
reader := bufio.NewReader(c.conn)
response, err := reader.ReadString('\n')
if err != nil {
c.conn = nil
return "", fmt.Errorf("failed to read response: %w", err)
}
return strings.TrimSpace(response), nil
}
func (c *Client) GetStatus() (*Status, error) {
c.statusMu.RLock()
defer c.statusMu.RUnlock()
if c.lastStatus == nil {
return &Status{Connected: false}, nil
}
return c.lastStatus, nil
}
func (c *Client) parseStatus(resp string) (*Status, error) {
status := &Status{
Connected: true,
}
var data string
// Handle two message formats:
// 1. Response to command: R<id>|0|state=IDLE bandA=40 ...
// 2. Spontaneous status: S0|state=TRANSMIT_A
if strings.HasPrefix(resp, "R") {
// Response format: R<id>|0|state=IDLE bandA=40 ...
parts := strings.SplitN(resp, "|", 3)
if len(parts) < 3 {
return nil, fmt.Errorf("invalid response format: %s", resp)
}
data = parts[2] // Get everything after "R<id>|0|"
} else if strings.HasPrefix(resp, "S") {
// Spontaneous message format: S0|state=TRANSMIT_A
parts := strings.SplitN(resp, "|", 2)
if len(parts) < 2 {
return nil, fmt.Errorf("invalid spontaneous message format: %s", resp)
}
data = parts[1] // Get everything after "S0|"
} else {
return nil, fmt.Errorf("unknown message format: %s", resp)
}
// Parse key=value pairs separated by spaces
pairs := strings.Fields(data)
for _, pair := range pairs {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
continue
}
key := kv[0]
value := kv[1]
switch key {
case "fwd":
// fwd is in dBm (e.g., 56.5 dBm = 446W)
// Formula: watts = 10^(dBm/10) / 1000
if dBm, err := strconv.ParseFloat(value, 64); err == nil {
milliwatts := math.Pow(10, dBm/10.0)
status.PowerForward = milliwatts / 1000.0
}
case "peakfwd":
// Peak forward power
case "swr":
// SWR from return loss
// Formula: returnLoss = abs(swr) / 20
// swr = (10^returnLoss + 1) / (10^returnLoss - 1)
if swrRaw, err := strconv.ParseFloat(value, 64); err == nil {
returnLoss := math.Abs(swrRaw) / 20.0
tenPowRL := math.Pow(10, returnLoss)
calculatedSWR := (tenPowRL + 1) / (tenPowRL - 1)
status.SWR = calculatedSWR
}
case "vac":
status.Voltage, _ = strconv.ParseFloat(value, 64)
case "vdd":
status.VDD, _ = strconv.ParseFloat(value, 64)
case "id":
status.Current, _ = strconv.ParseFloat(value, 64)
case "peakid":
status.PeakCurrent, _ = strconv.ParseFloat(value, 64)
case "temp":
status.Temperature, _ = strconv.ParseFloat(value, 64)
case "hltemp":
status.HarmonicLoadTemp, _ = strconv.ParseFloat(value, 64)
case "bandA":
if band, err := strconv.Atoi(value); err == nil {
status.BandA = fmt.Sprintf("%dM", band)
}
case "bandB":
if band, err := strconv.Atoi(value); err == nil && band > 0 {
status.BandB = fmt.Sprintf("%dM", band)
}
case "fanmode":
status.FanMode = value
case "state":
status.State = value
}
}
return status, nil
}
// Subscribe starts receiving periodic status updates
func (c *Client) Subscribe() error {
_, err := c.sendCommand("sub status")
return err
}
// Unsubscribe stops receiving periodic status updates
func (c *Client) Unsubscribe() error {
_, err := c.sendCommand("unsub status")
return err
}
// ReadUpdate reads a status update (when subscribed)
func (c *Client) ReadUpdate() (*Status, error) {
if c.conn == nil {
return nil, fmt.Errorf("not connected")
}
reader := bufio.NewReader(c.conn)
response, err := reader.ReadString('\n')
if err != nil {
return nil, fmt.Errorf("failed to read update: %w", err)
}
return c.parseStatus(strings.TrimSpace(response))
}
// SetFanMode sets the fan mode
// mode can be: STANDARD, CONTEST, or BROADCAST
func (c *Client) SetFanMode(mode string) error {
validModes := map[string]bool{
"STANDARD": true,
"CONTEST": true,
"BROADCAST": true,
}
if !validModes[mode] {
return fmt.Errorf("invalid fan mode: %s (must be STANDARD, CONTEST, or BROADCAST)", mode)
}
cmd := fmt.Sprintf("setup fanmode=%s", mode)
_, err := c.sendCommand(cmd)
return err
}
// SetOperate sets the operate mode
// value can be: 0 (STANDBY) or 1 (OPERATE)
func (c *Client) SetOperate(value int) error {
if value != 0 && value != 1 {
return fmt.Errorf("invalid operate value: %d (must be 0 or 1)", value)
}
cmd := fmt.Sprintf("operate=%d", value)
_, err := c.sendCommand(cmd)
return err
}

View File

@@ -6,227 +6,244 @@ import (
"net"
"strconv"
"strings"
"sync"
"time"
)
type Client struct {
host string
port int
conn net.Conn
host string
port int
conn net.Conn
reader *bufio.Reader
connMu sync.Mutex
lastStatus *Status
statusMu sync.RWMutex
stopChan chan struct{}
running bool
}
type Status struct {
Rotator1 RotatorData `json:"rotator1"`
Rotator2 RotatorData `json:"rotator2"`
Panic bool `json:"panic"`
}
type RotatorData struct {
CurrentAzimuth int `json:"current_azimuth"`
LimitCW int `json:"limit_cw"`
LimitCCW int `json:"limit_ccw"`
Configuration string `json:"configuration"` // "A" for azimuth, "E" for elevation
Moving int `json:"moving"` // 0=stopped, 1=CW, 2=CCW
Offset int `json:"offset"`
TargetAzimuth int `json:"target_azimuth"`
StartAzimuth int `json:"start_azimuth"`
OutsideLimit bool `json:"outside_limit"`
Name string `json:"name"`
Connected bool `json:"connected"`
Heading int `json:"heading"`
Connected bool `json:"connected"`
}
func New(host string, port int) *Client {
return &Client{
host: host,
port: port,
host: host,
port: port,
stopChan: make(chan struct{}),
}
}
func (c *Client) Connect() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
return nil
}
fmt.Printf("RotatorGenius: Attempting to connect to %s:%d\n", c.host, c.port)
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", c.host, c.port), 5*time.Second)
if err != nil {
fmt.Printf("RotatorGenius: Connection failed: %v\n", err)
return fmt.Errorf("failed to connect: %w", err)
}
c.conn = conn
c.reader = bufio.NewReader(c.conn)
fmt.Println("RotatorGenius: Connected successfully")
return nil
}
func (c *Client) Close() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.stopChan != nil {
close(c.stopChan)
}
if c.conn != nil {
return c.conn.Close()
}
return nil
}
func (c *Client) sendCommand(cmd string) (string, error) {
if c.conn == nil {
if err := c.Connect(); err != nil {
return "", err
}
func (c *Client) Start() error {
fmt.Println("RotatorGenius Start() called")
if c.running {
fmt.Println("RotatorGenius already running, skipping")
return nil
}
fmt.Println("RotatorGenius attempting initial connection...")
_ = c.Connect()
c.running = true
fmt.Println("RotatorGenius launching pollLoop...")
go c.pollLoop()
fmt.Println("RotatorGenius Start() completed")
return nil
}
func (c *Client) pollLoop() {
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.connMu.Lock()
if c.conn == nil {
c.connMu.Unlock()
c.statusMu.Lock()
c.lastStatus = &Status{Connected: false}
c.statusMu.Unlock()
if err := c.Connect(); err != nil {
continue
}
c.connMu.Lock()
}
c.connMu.Unlock()
status, err := c.queryStatus()
if err != nil {
c.connMu.Lock()
if c.conn != nil {
c.conn.Close()
c.conn = nil
c.reader = nil
}
c.connMu.Unlock()
c.statusMu.Lock()
c.lastStatus = &Status{Connected: false}
c.statusMu.Unlock()
continue
}
status.Connected = true
c.statusMu.Lock()
c.lastStatus = status
c.statusMu.Unlock()
case <-c.stopChan:
return
}
}
}
func (c *Client) sendCommand(cmd string) error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn == nil || c.reader == nil {
return fmt.Errorf("not connected")
}
// Send command
_, err := c.conn.Write([]byte(cmd))
if err != nil {
c.conn = nil
return "", fmt.Errorf("failed to send command: %w", err)
c.reader = nil
return fmt.Errorf("failed to send command: %w", err)
}
// Read response
reader := bufio.NewReader(c.conn)
response, err := reader.ReadString('\n')
return nil
}
func (c *Client) queryStatus() (*Status, error) {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn == nil || c.reader == nil {
return nil, fmt.Errorf("not connected")
}
// Send |h command
_, err := c.conn.Write([]byte("|h"))
if err != nil {
c.conn = nil
return "", fmt.Errorf("failed to read response: %w", err)
c.reader = nil
return nil, fmt.Errorf("failed to send query: %w", err)
}
return strings.TrimSpace(response), nil
// Read response - RotatorGenius doesn't send newline, read fixed amount
c.conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
defer c.conn.SetReadDeadline(time.Time{})
buf := make([]byte, 100)
n, err := c.reader.Read(buf)
if err != nil || n == 0 {
c.conn = nil
c.reader = nil
return nil, fmt.Errorf("failed to read response: %w", err)
}
response := string(buf[:n])
return c.parseStatus(response), nil
}
func (c *Client) parseStatus(response string) *Status {
status := &Status{}
// Response format: |h2<null><heading>...
// Example: |h2\x00183 8 10A0...
// After |h2 there's a null byte, then 3 digits for heading
if !strings.HasPrefix(response, "|h2") {
return status
}
// Skip |h2 (3 chars) and null byte (1 char), then read 3 digits
if len(response) >= 7 {
// Position 3 is the null byte, position 4-6 are the heading
headingStr := response[4:7]
heading, err := strconv.Atoi(strings.TrimSpace(headingStr))
if err == nil {
status.Heading = heading
}
}
return status
}
func (c *Client) GetStatus() (*Status, error) {
resp, err := c.sendCommand("|h")
if err != nil {
return nil, err
c.statusMu.RLock()
defer c.statusMu.RUnlock()
if c.lastStatus == nil {
return &Status{Connected: false}, nil
}
return parseStatusResponse(resp)
return c.lastStatus, nil
}
func parseStatusResponse(resp string) (*Status, error) {
if len(resp) < 80 {
return nil, fmt.Errorf("response too short: %d bytes", len(resp))
}
status := &Status{}
// Parse panic flag
status.Panic = resp[3] != 0x00
// Parse Rotator 1 (positions 4-38)
status.Rotator1 = parseRotatorData(resp[4:38])
// Parse Rotator 2 (positions 38-72)
if len(resp) >= 72 {
status.Rotator2 = parseRotatorData(resp[38:72])
}
return status, nil
// SetHeading rotates to a specific azimuth
func (c *Client) SetHeading(azimuth int) error {
cmd := fmt.Sprintf("|A1%d", azimuth)
return c.sendCommand(cmd)
}
func parseRotatorData(data string) RotatorData {
rd := RotatorData{}
// Current azimuth (3 bytes)
if azStr := strings.TrimSpace(data[0:3]); azStr != "999" {
rd.CurrentAzimuth, _ = strconv.Atoi(azStr)
rd.Connected = true
} else {
rd.CurrentAzimuth = 999
rd.Connected = false
}
// Limits
rd.LimitCW, _ = strconv.Atoi(strings.TrimSpace(data[3:6]))
rd.LimitCCW, _ = strconv.Atoi(strings.TrimSpace(data[6:9]))
// Configuration
rd.Configuration = string(data[9])
// Moving state
rd.Moving, _ = strconv.Atoi(string(data[10]))
// Offset
rd.Offset, _ = strconv.Atoi(strings.TrimSpace(data[11:15]))
// Target azimuth
if targetStr := strings.TrimSpace(data[15:18]); targetStr != "999" {
rd.TargetAzimuth, _ = strconv.Atoi(targetStr)
} else {
rd.TargetAzimuth = 999
}
// Start azimuth
if startStr := strings.TrimSpace(data[18:21]); startStr != "999" {
rd.StartAzimuth, _ = strconv.Atoi(startStr)
} else {
rd.StartAzimuth = 999
}
// Limit flag
rd.OutsideLimit = data[21] == '1'
// Name
rd.Name = strings.TrimSpace(data[22:34])
return rd
// RotateCW rotates clockwise
func (c *Client) RotateCW() error {
return c.sendCommand("|P1")
}
func (c *Client) MoveToAzimuth(rotator int, azimuth int) error {
if rotator < 1 || rotator > 2 {
return fmt.Errorf("rotator must be 1 or 2")
}
if azimuth < 0 || azimuth > 360 {
return fmt.Errorf("azimuth must be between 0 and 360")
}
cmd := fmt.Sprintf("|A%d%03d", rotator, azimuth)
resp, err := c.sendCommand(cmd)
if err != nil {
return err
}
if !strings.HasSuffix(resp, "K") {
return fmt.Errorf("command failed: %s", resp)
}
return nil
}
func (c *Client) RotateCW(rotator int) error {
if rotator < 1 || rotator > 2 {
return fmt.Errorf("rotator must be 1 or 2")
}
cmd := fmt.Sprintf("|P%d", rotator)
resp, err := c.sendCommand(cmd)
if err != nil {
return err
}
if !strings.HasSuffix(resp, "K") {
return fmt.Errorf("command failed: %s", resp)
}
return nil
}
func (c *Client) RotateCCW(rotator int) error {
if rotator < 1 || rotator > 2 {
return fmt.Errorf("rotator must be 1 or 2")
}
cmd := fmt.Sprintf("|M%d", rotator)
resp, err := c.sendCommand(cmd)
if err != nil {
return err
}
if !strings.HasSuffix(resp, "K") {
return fmt.Errorf("command failed: %s", resp)
}
return nil
// RotateCCW rotates counter-clockwise
func (c *Client) RotateCCW() error {
return c.sendCommand("|M1")
}
// Stop stops rotation
func (c *Client) Stop() error {
resp, err := c.sendCommand("|S")
if err != nil {
return err
}
if !strings.HasSuffix(resp, "K") {
return fmt.Errorf("command failed: %s", resp)
}
return nil
return c.sendCommand("|S")
}

View File

@@ -3,67 +3,217 @@ package tunergenius
import (
"bufio"
"fmt"
"math"
"net"
"strconv"
"strings"
"sync"
"time"
. "git.rouggy.com/rouggy/ShackMaster/internal/devices"
)
type Client struct {
host string
port int
idNumber int
conn net.Conn
host string
port int
conn net.Conn
connMu sync.Mutex
lastStatus *Status
statusMu sync.RWMutex
stopChan chan struct{}
running bool
}
type Status struct {
Operate bool `json:"operate"` // true = OPERATE, false = STANDBY
Bypass bool `json:"bypass"` // Bypass mode
ActiveAntenna int `json:"active_antenna"` // 0=ANT1, 1=ANT2, 2=ANT3
TuningStatus string `json:"tuning_status"`
FrequencyA float64 `json:"frequency_a"`
FrequencyB float64 `json:"frequency_b"`
C1 int `json:"c1"`
L int `json:"l"`
C2 int `json:"c2"`
SWR float64 `json:"swr"`
Power float64 `json:"power"`
Temperature float64 `json:"temperature"`
Connected bool `json:"connected"`
PowerForward float64 `json:"power_forward"`
PowerPeak float64 `json:"power_peak"`
PowerMax float64 `json:"power_max"`
SWR float64 `json:"swr"`
PTTA int `json:"ptt_a"`
BandA int `json:"band_a"`
FreqA float64 `json:"frequency_a"`
BypassA bool `json:"bypass_a"`
AntA int `json:"antenna_a"`
PTTB int `json:"ptt_b"`
BandB int `json:"band_b"`
FreqB float64 `json:"frequency_b"`
BypassB bool `json:"bypass_b"`
AntB int `json:"antenna_b"`
State int `json:"state"`
Active int `json:"active"`
Tuning int `json:"tuning"`
Bypass bool `json:"bypass"`
RelayC1 int `json:"c1"`
RelayL int `json:"l"`
RelayC2 int `json:"c2"`
TuningStatus string `json:"tuning_status"`
Connected bool `json:"connected"`
}
func New(host string, port int, idNumber int) *Client {
func New(host string, port int) *Client {
return &Client{
host: host,
port: port,
idNumber: idNumber,
stopChan: make(chan struct{}),
}
}
func (c *Client) Connect() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
return nil // Already connected
}
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", c.host, c.port), 5*time.Second)
if err != nil {
return fmt.Errorf("failed to connect: %w", err)
}
c.conn = conn
// Read and discard version banner
reader := bufio.NewReader(c.conn)
_, _ = reader.ReadString('\n')
return nil
}
func (c *Client) Close() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.stopChan != nil {
close(c.stopChan)
}
if c.conn != nil {
return c.conn.Close()
}
return nil
}
func (c *Client) sendCommand(cmd string) (string, error) {
if c.conn == nil {
if err := c.Connect(); err != nil {
return "", err
}
// Start begins continuous polling of the device
func (c *Client) Start() error {
if c.running {
return nil
}
// Format command with ID
fullCmd := fmt.Sprintf("C%d|%s\n", c.idNumber, cmd)
// Try to connect, but don't fail if it doesn't work
// The poll loop will keep trying
_ = c.Connect()
c.running = true
go c.pollLoop()
return nil
}
// pollLoop continuously polls the device for status
func (c *Client) pollLoop() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Try to reconnect if not connected
c.connMu.Lock()
if c.conn == nil {
c.connMu.Unlock()
// Mark as disconnected and reset all values
c.statusMu.Lock()
c.lastStatus = &Status{
Connected: false,
}
c.statusMu.Unlock()
if err := c.Connect(); err != nil {
// Silent fail, will retry on next tick
continue
}
c.connMu.Lock()
}
c.connMu.Unlock()
status, err := c.queryStatus()
if err != nil {
// Connection lost, close and retry next tick
c.connMu.Lock()
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
c.connMu.Unlock()
// Mark as disconnected and reset all values
c.statusMu.Lock()
c.lastStatus = &Status{
Connected: false,
}
c.statusMu.Unlock()
continue
}
// Mark as connected
status.Connected = true
c.statusMu.Lock()
c.lastStatus = status
c.statusMu.Unlock()
case <-c.stopChan:
return
}
}
}
func (c *Client) queryStatus() (*Status, error) {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn == nil {
return nil, fmt.Errorf("not connected")
}
// Get next command ID from global counter
cmdID := GetGlobalCommandID().GetNextID()
// Format command with ID: C<id>|status get
fullCmd := fmt.Sprintf("C%d|status get\n", cmdID)
// Send command
_, err := c.conn.Write([]byte(fullCmd))
if err != nil {
c.conn = nil
return nil, fmt.Errorf("failed to send command: %w", err)
}
// Read response
reader := bufio.NewReader(c.conn)
response, err := reader.ReadString('\n')
if err != nil {
c.conn = nil
return nil, fmt.Errorf("failed to read response: %w", err)
}
return c.parseStatus(strings.TrimSpace(response))
}
func (c *Client) sendCommand(cmd string) (string, error) {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn == nil {
return "", fmt.Errorf("not connected")
}
// Get next command ID from global counter
cmdID := GetGlobalCommandID().GetNextID()
// Format command with ID: C<id>|<command>
fullCmd := fmt.Sprintf("C%d|%s\n", cmdID, cmd)
// Send command
_, err := c.conn.Write([]byte(fullCmd))
@@ -84,119 +234,156 @@ func (c *Client) sendCommand(cmd string) (string, error) {
}
func (c *Client) GetStatus() (*Status, error) {
resp, err := c.sendCommand("status")
if err != nil {
return nil, err
c.statusMu.RLock()
defer c.statusMu.RUnlock()
if c.lastStatus == nil {
return &Status{Connected: false}, nil
}
// Parse the response - format will depend on actual device response
// This is a placeholder that should be updated based on real response format
return c.lastStatus, nil
}
func (c *Client) parseStatus(resp string) (*Status, error) {
status := &Status{
Connected: true,
}
// TODO: Parse actual status response from device
// The response format needs to be determined from real device testing
// For now, we just check if we got a response
_ = resp // Temporary: will be used when we parse the actual response format
// Response format: S<id>|status fwd=21.19 peak=21.55 ...
// Extract the data part after "S<id>|status "
idx := strings.Index(resp, "|status ")
if idx == -1 {
return nil, fmt.Errorf("invalid response format: %s", resp)
}
data := resp[idx+8:] // Skip "|status "
// Parse key=value pairs separated by spaces
pairs := strings.Fields(data)
for _, pair := range pairs {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
continue
}
key := kv[0]
value := kv[1]
switch key {
case "fwd":
// fwd is in dBm (e.g., 42.62 dBm)
// Formula: watts = 10^(dBm/10) / 1000
if dBm, err := strconv.ParseFloat(value, 64); err == nil {
milliwatts := math.Pow(10, dBm/10.0)
status.PowerForward = milliwatts / 1000.0
}
case "peak":
// peak power in dBm
if dBm, err := strconv.ParseFloat(value, 64); err == nil {
milliwatts := math.Pow(10, dBm/10.0)
status.PowerPeak = milliwatts / 1000.0
}
case "max":
if dBm, err := strconv.ParseFloat(value, 64); err == nil {
milliwatts := math.Pow(10, dBm/10.0)
status.PowerMax = milliwatts / 1000.0
}
case "swr":
// SWR from return loss
// Formula: returnLoss = abs(swr) / 20
// swr = (10^returnLoss + 1) / (10^returnLoss - 1)
if swrRaw, err := strconv.ParseFloat(value, 64); err == nil {
returnLoss := math.Abs(swrRaw) / 20.0
tenPowRL := math.Pow(10, returnLoss)
calculatedSWR := (tenPowRL + 1) / (tenPowRL - 1)
status.SWR = calculatedSWR
}
case "pttA":
status.PTTA, _ = strconv.Atoi(value)
case "bandA":
status.BandA, _ = strconv.Atoi(value)
case "freqA":
status.FreqA, _ = strconv.ParseFloat(value, 64)
case "bypassA":
status.BypassA = value == "1"
case "antA":
status.AntA, _ = strconv.Atoi(value)
case "pttB":
status.PTTB, _ = strconv.Atoi(value)
case "bandB":
status.BandB, _ = strconv.Atoi(value)
case "freqB":
status.FreqB, _ = strconv.ParseFloat(value, 64)
case "bypassB":
status.BypassB = value == "1"
case "antB":
status.AntB, _ = strconv.Atoi(value)
case "state":
status.State, _ = strconv.Atoi(value)
case "active":
status.Active, _ = strconv.Atoi(value)
case "tuning":
status.Tuning, _ = strconv.Atoi(value)
if status.Tuning == 1 {
status.TuningStatus = "TUNING"
} else {
status.TuningStatus = "READY"
}
case "bypass":
status.Bypass = value == "1"
case "relayC1":
status.RelayC1, _ = strconv.Atoi(value)
case "relayL":
status.RelayL, _ = strconv.Atoi(value)
case "relayC2":
status.RelayC2, _ = strconv.Atoi(value)
}
}
return status, nil
}
func (c *Client) SetOperate(operate bool) error {
var state int
if operate {
state = 1
// SetOperate switches between STANDBY (0) and OPERATE (1)
func (c *Client) SetOperate(value int) error {
if value != 0 && value != 1 {
return fmt.Errorf("invalid operate value: %d (must be 0 or 1)", value)
}
cmd := fmt.Sprintf("operate set=%d", state)
resp, err := c.sendCommand(cmd)
if err != nil {
return err
}
// Check if command was successful
if resp == "" {
return fmt.Errorf("empty response from device")
}
return nil
cmd := fmt.Sprintf("operate set=%d", value)
_, err := c.sendCommand(cmd)
return err
}
func (c *Client) SetBypass(bypass bool) error {
var state int
if bypass {
state = 1
// SetBypass sets BYPASS mode
func (c *Client) SetBypass(value int) error {
if value != 0 && value != 1 {
return fmt.Errorf("invalid bypass value: %d (must be 0 or 1)", value)
}
cmd := fmt.Sprintf("bypass set=%d", state)
resp, err := c.sendCommand(cmd)
if err != nil {
return err
}
// Check if command was successful
if resp == "" {
return fmt.Errorf("empty response from device")
}
return nil
}
func (c *Client) ActivateAntenna(antenna int) error {
if antenna < 0 || antenna > 2 {
return fmt.Errorf("antenna must be 0 (ANT1), 1 (ANT2), or 2 (ANT3)")
}
cmd := fmt.Sprintf("activate ant=%d", antenna)
resp, err := c.sendCommand(cmd)
if err != nil {
return err
}
// Check if command was successful
if resp == "" {
return fmt.Errorf("empty response from device")
}
return nil
cmd := fmt.Sprintf("bypass set=%d", value)
_, err := c.sendCommand(cmd)
return err
}
// AutoTune starts a tuning cycle
func (c *Client) AutoTune() error {
resp, err := c.sendCommand("autotune")
if err != nil {
return err
}
// Check if command was successful
if resp == "" {
return fmt.Errorf("empty response from device")
}
return nil
_, err := c.sendCommand("autotune")
return err
}
// TuneRelay adjusts tuning parameters manually
// TuneRelay adjusts one tuning parameter by one step
// relay: 0=C1, 1=L, 2=C2
// move: -1 to decrease, 1 to increase
func (c *Client) TuneRelay(relay int, move int) error {
// move: -1 (decrease) or 1 (increase)
func (c *Client) TuneRelay(relay, move int) error {
if relay < 0 || relay > 2 {
return fmt.Errorf("relay must be 0 (C1), 1 (L), or 2 (C2)")
return fmt.Errorf("invalid relay: %d (must be 0, 1, or 2)", relay)
}
if move != -1 && move != 1 {
return fmt.Errorf("move must be -1 or 1")
return fmt.Errorf("invalid move: %d (must be -1 or 1)", move)
}
cmd := fmt.Sprintf("tune relay=%d move=%d", relay, move)
resp, err := c.sendCommand(cmd)
if err != nil {
return err
}
// Check if command was successful
if resp == "" {
return fmt.Errorf("empty response from device")
}
return nil
_, err := c.sendCommand(cmd)
return err
}

View File

@@ -4,6 +4,8 @@ import (
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
@@ -13,7 +15,8 @@ type Client struct {
}
type Status struct {
Relays []RelayState `json:"relays"`
Relays []RelayState `json:"relays"`
Connected bool `json:"connected"`
}
type RelayState struct {
@@ -65,23 +68,110 @@ func (c *Client) TurnOff(relay int) error {
}
func (c *Client) AllOn() error {
for i := 1; i <= 5; i++ {
if err := c.TurnOn(i); err != nil {
return fmt.Errorf("failed to turn on relay %d: %w", i, err)
// Sequence for ALL ON:
// 1. Turn on relays 1, 2, 3, 5 immediately
// 2. Wait 5 seconds
// 3. Turn on relay 4 (Flex Radio Start)
// Turn on relays 1, 2, 3, 5
for _, relay := range []int{1, 2, 3, 5} {
if err := c.TurnOn(relay); err != nil {
return fmt.Errorf("failed to turn on relay %d: %w", relay, err)
}
}
// Wait 5 seconds for power supply to stabilize
time.Sleep(5 * time.Second)
// Turn on relay 4 (Flex Radio)
if err := c.TurnOn(4); err != nil {
return fmt.Errorf("failed to turn on relay 4: %w", err)
}
return nil
}
func (c *Client) AllOff() error {
for i := 1; i <= 5; i++ {
if err := c.TurnOff(i); err != nil {
return fmt.Errorf("failed to turn off relay %d: %w", i, err)
// Sequence for ALL OFF:
// 1. Turn off relay 4 (Flex Radio) immediately
// 2. Turn off relays 2, 3, 5 immediately
// 3. Wait 35 seconds for Flex Radio to shut down
// 4. Turn off relay 1 (Power Supply)
// Turn off relay 4 (Flex Radio)
if err := c.TurnOff(4); err != nil {
return fmt.Errorf("failed to turn off relay 4: %w", err)
}
// Turn off relays 2, 3, 5
for _, relay := range []int{2, 3, 5} {
if err := c.TurnOff(relay); err != nil {
return fmt.Errorf("failed to turn off relay %d: %w", relay, err)
}
}
// Wait 35 seconds for Flex Radio to shut down properly
time.Sleep(35 * time.Second)
// Turn off relay 1 (Power Supply)
if err := c.TurnOff(1); err != nil {
return fmt.Errorf("failed to turn off relay 1: %w", err)
}
return nil
}
// GetStatus queries the actual state of all relays
func (c *Client) GetStatus() (*Status, error) {
url := fmt.Sprintf("http://%s/relaystate/get2/1$2$3$4$5$", c.host)
resp, err := c.httpClient.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to get relay status: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
// Parse response format: "1,1\n2,1\n3,1\n4,1\n5,0\n"
status := &Status{
Relays: make([]RelayState, 0, 5),
Connected: true,
}
lines := strings.Split(strings.TrimSpace(string(body)), "\n")
for _, line := range lines {
parts := strings.Split(strings.TrimSpace(line), ",")
if len(parts) != 2 {
continue
}
relayNum, err := strconv.Atoi(parts[0])
if err != nil {
continue
}
relayState, err := strconv.Atoi(parts[1])
if err != nil {
continue
}
status.Relays = append(status.Relays, RelayState{
Number: relayNum,
State: relayState == 1,
})
}
return status, nil
}
// Ping checks if the device is reachable
func (c *Client) Ping() error {
url := fmt.Sprintf("http://%s/", c.host)

View File

@@ -0,0 +1,96 @@
package solar
import (
"encoding/xml"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// SolarData contains current solar and geomagnetic conditions
type SolarData struct {
SolarFluxIndex int `json:"sfi"` // Solar Flux Index
Sunspots int `json:"sunspots"` // Number of sunspots
AIndex int `json:"a_index"` // A-index (geomagnetic activity)
KIndex int `json:"k_index"` // K-index (geomagnetic activity)
GeomagField string `json:"geomag"` // Geomagnetic field status
UpdatedAt string `json:"updated"` // Last update time
}
// HamQSLResponse matches the XML structure from hamqsl.com
type HamQSLResponse struct {
XMLName xml.Name `xml:"solar"`
SolarData SolarDataXML `xml:"solardata"`
}
type SolarDataXML struct {
Updated string `xml:"updated"`
SolarFlux string `xml:"solarflux"`
AIndex string `xml:"aindex"`
KIndex string `xml:"kindex"`
Sunspots string `xml:"sunspots"`
GeomagField string `xml:"geomagfield"`
}
type Client struct {
httpClient *http.Client
lastUpdate time.Time
cachedData *SolarData
}
func New() *Client {
return &Client{
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// GetSolarData fetches current solar data from HamQSL
// Data is cached for 15 minutes to avoid excessive requests
func (c *Client) GetSolarData() (*SolarData, error) {
// Return cached data if less than 15 minutes old
if c.cachedData != nil && time.Since(c.lastUpdate) < 15*time.Minute {
return c.cachedData, nil
}
resp, err := c.httpClient.Get("http://www.hamqsl.com/solarxml.php")
if err != nil {
return nil, fmt.Errorf("failed to fetch solar data: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
var hamqslData HamQSLResponse
if err := xml.Unmarshal(body, &hamqslData); err != nil {
return nil, fmt.Errorf("failed to parse XML: %w", err)
}
// Parse the data
solarData := &SolarData{
GeomagField: hamqslData.SolarData.GeomagField,
UpdatedAt: hamqslData.SolarData.Updated,
}
// Parse numeric values (trim spaces)
fmt.Sscanf(strings.TrimSpace(hamqslData.SolarData.SolarFlux), "%d", &solarData.SolarFluxIndex)
fmt.Sscanf(strings.TrimSpace(hamqslData.SolarData.AIndex), "%d", &solarData.AIndex)
fmt.Sscanf(strings.TrimSpace(hamqslData.SolarData.KIndex), "%d", &solarData.KIndex)
fmt.Sscanf(strings.TrimSpace(hamqslData.SolarData.Sunspots), "%d", &solarData.Sunspots)
// Cache the data
c.cachedData = solarData
c.lastUpdate = time.Now()
return solarData, nil
}

View File

@@ -0,0 +1,126 @@
package weather
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// WeatherData contains current weather conditions
type WeatherData struct {
Temperature float64 `json:"temp"`
FeelsLike float64 `json:"feels_like"`
Humidity int `json:"humidity"`
Pressure int `json:"pressure"`
WindSpeed float64 `json:"wind_speed"`
WindGust float64 `json:"wind_gust"`
WindDeg int `json:"wind_deg"`
Clouds int `json:"clouds"`
Description string `json:"description"`
Icon string `json:"icon"`
UpdatedAt string `json:"updated"`
}
// OpenWeatherMapResponse matches the API response
type OpenWeatherMapResponse struct {
Weather []struct {
Description string `json:"description"`
Icon string `json:"icon"`
} `json:"weather"`
Main struct {
Temp float64 `json:"temp"`
FeelsLike float64 `json:"feels_like"`
Humidity int `json:"humidity"`
Pressure int `json:"pressure"`
} `json:"main"`
Wind struct {
Speed float64 `json:"speed"`
Deg int `json:"deg"`
Gust float64 `json:"gust"`
} `json:"wind"`
Clouds struct {
All int `json:"all"`
} `json:"clouds"`
Dt int64 `json:"dt"`
}
type Client struct {
apiKey string
latitude float64
longitude float64
httpClient *http.Client
lastUpdate time.Time
cachedData *WeatherData
}
func New(apiKey string, latitude, longitude float64) *Client {
return &Client{
apiKey: apiKey,
latitude: latitude,
longitude: longitude,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// GetWeatherData fetches current weather from OpenWeatherMap
// Data is cached for 10 minutes
func (c *Client) GetWeatherData() (*WeatherData, error) {
// Return cached data if less than 10 minutes old
if c.cachedData != nil && time.Since(c.lastUpdate) < 10*time.Minute {
return c.cachedData, nil
}
url := fmt.Sprintf(
"https://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%s&units=metric",
c.latitude, c.longitude, c.apiKey,
)
resp, err := c.httpClient.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to fetch weather data: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code %d: %s", resp.StatusCode, string(body))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
var owmData OpenWeatherMapResponse
if err := json.Unmarshal(body, &owmData); err != nil {
return nil, fmt.Errorf("failed to parse JSON: %w", err)
}
// Convert to our structure
weatherData := &WeatherData{
Temperature: owmData.Main.Temp,
FeelsLike: owmData.Main.FeelsLike,
Humidity: owmData.Main.Humidity,
Pressure: owmData.Main.Pressure,
WindSpeed: owmData.Wind.Speed,
WindGust: owmData.Wind.Gust,
WindDeg: owmData.Wind.Deg,
Clouds: owmData.Clouds.All,
UpdatedAt: time.Unix(owmData.Dt, 0).Format(time.RFC3339),
}
if len(owmData.Weather) > 0 {
weatherData.Description = owmData.Weather[0].Description
weatherData.Icon = owmData.Weather[0].Icon
}
// Cache the data
c.cachedData = weatherData
c.lastUpdate = time.Now()
return weatherData, nil
}

15
web/index.html Normal file
View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ShackMaster - F4BPO Shack</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

18
web/package.json Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "shackmaster-web",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^3.0.1",
"svelte": "^4.2.8",
"vite": "^5.0.11"
},
"dependencies": {
"@turf/turf": "^6.5.0"
}
}

265
web/src/App.svelte Normal file
View File

@@ -0,0 +1,265 @@
<script>
import { onMount, onDestroy } from 'svelte';
import { wsService, connected, systemStatus } from './lib/websocket.js';
import { api } from './lib/api.js';
import WebSwitch from './components/WebSwitch.svelte';
import PowerGenius from './components/PowerGenius.svelte';
import TunerGenius from './components/TunerGenius.svelte';
import AntennaGenius from './components/AntennaGenius.svelte';
import RotatorGenius from './components/RotatorGenius.svelte';
let status = null;
let isConnected = false;
let currentTime = new Date();
let callsign = 'F4BPO'; // Default
const unsubscribeStatus = systemStatus.subscribe(value => {
status = value;
});
const unsubscribeConnected = connected.subscribe(value => {
isConnected = value;
});
// Solar data from status
$: solarData = status?.solar || {
sfi: 0,
sunspots: 0,
a_index: 0,
k_index: 0,
geomag: 'Unknown'
};
onMount(async () => {
wsService.connect();
// Fetch config to get callsign
try {
const config = await api.getConfig();
if (config.callsign) {
callsign = config.callsign;
}
} catch (err) {
console.error('Failed to fetch config:', err);
}
// Update clock every second
const clockInterval = setInterval(() => {
currentTime = new Date();
}, 1000);
return () => {
clearInterval(clockInterval);
};
});
onDestroy(() => {
wsService.disconnect();
unsubscribeStatus();
unsubscribeConnected();
});
function formatTime(date) {
return date.toTimeString().slice(0, 8);
}
// Weather data from status
$: weatherData = status?.weather || {
wind_speed: 0,
wind_gust: 0,
temp: 0,
feels_like: 0
};
</script>
<div class="app">
<header>
<div class="header-left">
<h1>{callsign} Shack</h1>
<div class="connection-status">
<span class="status-indicator" class:status-online={isConnected} class:status-offline={!isConnected}></span>
{isConnected ? 'Connected' : 'Disconnected'}
</div>
</div>
<div class="header-center">
<div class="solar-info">
<span class="solar-item">SFI <span class="value">{solarData.sfi}</span></span>
<span class="solar-item">Spots <span class="value">{solarData.sunspots}</span></span>
<span class="solar-item">A <span class="value">{solarData.a_index}</span></span>
<span class="solar-item">K <span class="value">{solarData.k_index}</span></span>
<span class="solar-item">G <span class="value">{solarData.geomag}</span></span>
</div>
</div>
<div class="header-right">
<div class="weather-info">
<span title="Wind">🌬️ {weatherData.wind_speed.toFixed(1)}m/s</span>
<span title="Gust">💨 {weatherData.wind_gust.toFixed(1)}m/s</span>
<span title="Temperature">🌡️ {weatherData.temp.toFixed(1)}°C</span>
<span title="Feels like">{weatherData.feels_like.toFixed(1)}°C</span>
</div>
<div class="clock">
<span class="time">{formatTime(currentTime)}</span>
<span class="date">{currentTime.toLocaleDateString()}</span>
</div>
</div>
</header>
<main>
<div class="dashboard-grid">
<div class="row">
<WebSwitch status={status?.webswitch} />
<PowerGenius status={status?.power_genius} />
<TunerGenius status={status?.tuner_genius} />
</div>
<div class="row">
<AntennaGenius status={status?.antenna_genius} />
<RotatorGenius status={status?.rotator_genius} />
</div>
</div>
</main>
</div>
<style>
.app {
min-height: 100vh;
display: flex;
flex-direction: column;
}
header {
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
padding: 16px 24px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
flex-wrap: wrap;
gap: 16px;
}
.header-left {
display: flex;
align-items: center;
gap: 16px;
}
h1 {
font-size: 24px;
font-weight: 500;
margin: 0;
color: white;
}
.connection-status {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
padding: 6px 12px;
background: rgba(0, 0, 0, 0.3);
border-radius: 16px;
}
.header-center {
flex: 1;
display: flex;
justify-content: center;
}
.solar-info {
display: flex;
gap: 20px;
font-size: 14px;
}
.solar-item {
color: rgba(255, 255, 255, 0.8);
}
.solar-item .value {
color: var(--accent-teal);
font-weight: 500;
margin-left: 4px;
}
.header-right {
display: flex;
gap: 20px;
align-items: center;
}
.weather-info {
display: flex;
gap: 12px;
font-size: 14px;
color: rgba(255, 255, 255, 0.9);
}
.clock {
display: flex;
flex-direction: column;
align-items: flex-end;
}
.time {
font-size: 18px;
font-weight: 500;
color: white;
}
.date {
font-size: 12px;
color: rgba(255, 255, 255, 0.7);
}
main {
flex: 1;
padding: 24px;
overflow-y: auto;
}
.dashboard-grid {
display: flex;
flex-direction: column;
gap: 24px;
max-width: 1800px;
margin: 0 auto;
}
.row {
display: flex;
gap: 24px;
flex-wrap: wrap;
}
.row > :global(*) {
flex: 1;
min-width: 300px;
}
@media (max-width: 1200px) {
.row {
flex-direction: column;
}
}
@media (max-width: 768px) {
header {
flex-direction: column;
align-items: flex-start;
}
.header-center,
.header-right {
width: 100%;
justify-content: flex-start;
}
.solar-info {
flex-wrap: wrap;
}
}
</style>

438
web/src/app.css Normal file
View File

@@ -0,0 +1,438 @@
:root {
/* Modern dark theme inspired by FlexDXCluster */
--bg-primary: #0a1628;
--bg-secondary: #1a2332;
--bg-tertiary: #243447;
--bg-hover: #2a3f5f;
--text-primary: #e0e6ed;
--text-secondary: #a0aec0;
--text-muted: #718096;
--accent-cyan: #4fc3f7;
--accent-blue: #2196f3;
--accent-green: #4caf50;
--accent-orange: #ff9800;
--accent-red: #f44336;
--accent-purple: #9c27b0;
--accent-yellow: #ffc107;
--border-color: #2d3748;
--border-light: #374151;
--card-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
--card-radius: 6px;
--header-height: 56px;
--spacing-xs: 4px;
--spacing-sm: 8px;
--spacing-md: 12px;
--spacing-lg: 16px;
--spacing-xl: 20px;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: var(--bg-primary);
color: var(--text-primary);
font-size: 13px;
line-height: 1.4;
overflow-x: hidden;
}
.app {
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
/* ==================== HEADER ==================== */
header {
height: var(--header-height);
background: var(--bg-secondary);
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 var(--spacing-lg);
flex-shrink: 0;
}
.header-left {
display: flex;
align-items: center;
gap: var(--spacing-lg);
}
.header-left h1 {
font-size: 16px;
font-weight: 600;
color: var(--accent-cyan);
letter-spacing: 0.5px;
}
.connection-status {
display: flex;
align-items: center;
gap: var(--spacing-sm);
font-size: 12px;
color: var(--text-secondary);
}
.status-indicator {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent-red);
transition: background 0.3s;
}
.status-indicator.status-online {
background: var(--accent-green);
box-shadow: 0 0 8px var(--accent-green);
}
.header-center {
display: flex;
gap: var(--spacing-xl);
}
.solar-info {
display: flex;
gap: var(--spacing-md);
font-size: 12px;
}
.solar-item {
color: var(--text-secondary);
}
.solar-item .value {
color: var(--accent-cyan);
font-weight: 600;
margin-left: var(--spacing-xs);
}
.header-right {
display: flex;
align-items: center;
gap: var(--spacing-lg);
}
.weather-info {
display: flex;
gap: var(--spacing-md);
font-size: 12px;
color: var(--text-secondary);
}
.clock {
display: flex;
flex-direction: column;
align-items: flex-end;
font-size: 11px;
}
.clock .time {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
}
.clock .date {
color: var(--text-secondary);
}
/* ==================== MAIN CONTENT ==================== */
main {
flex: 1;
overflow-y: auto;
padding: var(--spacing-md);
}
.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: var(--spacing-md);
max-width: 1800px;
margin: 0 auto;
}
/* ==================== CARDS ==================== */
.card {
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: var(--card-radius);
padding: var(--spacing-md);
box-shadow: var(--card-shadow);
transition: border-color 0.2s;
}
.card:hover {
border-color: var(--border-light);
}
.card h2 {
font-size: 14px;
font-weight: 600;
color: var(--accent-cyan);
margin-bottom: var(--spacing-md);
display: flex;
align-items: center;
gap: var(--spacing-sm);
letter-spacing: 0.5px;
}
.card h2::before {
content: '';
width: 3px;
height: 14px;
background: var(--accent-cyan);
border-radius: 2px;
}
/* Status indicators */
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent-green);
}
.status-dot.disconnected {
background: var(--accent-red);
}
/* ==================== LABELS & VALUES ==================== */
.label {
font-size: 11px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: var(--spacing-xs);
}
.value {
font-size: 18px;
font-weight: 300;
color: var(--text-primary);
}
/* ==================== BUTTONS ==================== */
button, .button {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-color);
border-radius: 4px;
padding: var(--spacing-sm) var(--spacing-md);
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
text-transform: uppercase;
letter-spacing: 0.5px;
}
button:hover, .button:hover {
background: var(--bg-hover);
border-color: var(--border-light);
}
button:active, .button:active {
transform: scale(0.98);
}
button.primary {
background: var(--accent-cyan);
border-color: var(--accent-cyan);
color: #000;
}
button.primary:hover {
background: #29b6f6;
border-color: #29b6f6;
}
button.success {
background: var(--accent-green);
border-color: var(--accent-green);
color: white;
}
button.danger {
background: var(--accent-red);
border-color: var(--accent-red);
color: white;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* ==================== SELECT ==================== */
select {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-color);
border-radius: 4px;
padding: var(--spacing-sm);
font-size: 12px;
cursor: pointer;
outline: none;
transition: all 0.2s;
}
select:hover {
border-color: var(--border-light);
}
select:focus {
border-color: var(--accent-cyan);
}
/* ==================== BADGES ==================== */
.badge {
display: inline-block;
padding: 4px 10px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.badge.green {
background: rgba(76, 175, 80, 0.2);
color: var(--accent-green);
}
.badge.red {
background: rgba(244, 67, 54, 0.2);
color: var(--accent-red);
}
.badge.orange {
background: rgba(255, 152, 0, 0.2);
color: var(--accent-orange);
}
.badge.cyan {
background: rgba(79, 195, 247, 0.2);
color: var(--accent-cyan);
}
.badge.purple {
background: rgba(156, 39, 176, 0.2);
color: var(--accent-purple);
}
/* ==================== PROGRESS BARS ==================== */
.bar {
width: 100%;
height: 6px;
background: var(--bg-tertiary);
border-radius: 3px;
overflow: hidden;
margin: var(--spacing-xs) 0;
}
.bar-fill {
height: 100%;
background: linear-gradient(90deg, var(--accent-green), var(--accent-orange), var(--accent-red));
transition: width 0.3s ease;
border-radius: 3px;
}
.scale {
display: flex;
justify-content: space-between;
font-size: 10px;
color: var(--text-muted);
margin-top: var(--spacing-xs);
}
/* ==================== METRICS ==================== */
.metrics {
display: flex;
flex-direction: column;
gap: var(--spacing-md);
}
.metric {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
}
.metric-row {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: var(--spacing-md);
}
.metric.small {
min-width: 0;
}
.metric-value {
display: flex;
justify-content: space-between;
align-items: baseline;
flex-wrap: wrap;
}
/* ==================== SCROLLBAR ==================== */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-primary);
}
::-webkit-scrollbar-thumb {
background: var(--bg-tertiary);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--bg-hover);
}
/* ==================== RESPONSIVE ==================== */
@media (max-width: 1400px) {
.dashboard-grid {
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
}
@media (max-width: 768px) {
header {
flex-direction: column;
height: auto;
padding: var(--spacing-sm);
gap: var(--spacing-sm);
}
.dashboard-grid {
grid-template-columns: 1fr;
}
.header-center {
order: 3;
width: 100%;
}
}

View File

@@ -0,0 +1,310 @@
<script>
import { api } from '../lib/api.js';
export let status;
$: connected = status?.connected || false;
$: portA = status?.port_a || {};
$: portB = status?.port_b || {};
$: antennas = status?.antennas || [];
// Band names
const bandNames = {
0: '160M', 1: '80M', 2: '60M', 3: '40M', 4: '30M',
5: '20M', 6: '17M', 7: '15M', 8: '12M', 9: '10M',
10: '6M', 11: '4M', 12: '2M', 13: '1.25M', 14: '70CM', 15: 'GEN'
};
$: bandAName = bandNames[portA.band] || 'None';
$: bandBName = bandNames[portB.band] || 'None';
async function selectAntenna(port, antennaNum) {
try {
await api.antenna.selectAntenna(port, antennaNum, antennaNum);
} catch (err) {
console.error('Failed to select antenna:', err);
alert('Failed to select antenna');
}
}
async function reboot() {
if (!confirm('Are you sure you want to reboot the Antenna Genius?')) {
return;
}
try {
await api.antenna.reboot();
} catch (err) {
console.error('Failed to reboot:', err);
alert('Failed to reboot');
}
}
</script>
<div class="card">
<div class="card-header">
<h2>Antenna Genius</h2>
<span class="status-dot" class:disconnected={!connected}></span>
</div>
<div class="metrics">
<!-- Radio Sources -->
<div class="sources">
<div class="source-item">
<div class="source-label">{portA.source || 'FLEX'}</div>
</div>
<div class="source-item">
<div class="source-label">{portB.source || 'FLEX'}</div>
</div>
</div>
<!-- Bands -->
<div class="bands">
<div class="band-item">
<div class="band-value">{bandAName}</div>
</div>
<div class="band-item">
<div class="band-value">{bandBName}</div>
</div>
</div>
<!-- Antennas -->
<div class="antennas">
{#each antennas as antenna}
{@const isPortATx = portA.tx && portA.tx_ant === antenna.number}
{@const isPortBTx = portB.tx && portB.tx_ant === antenna.number}
{@const isPortARx = !portA.tx && (portA.rx_ant === antenna.number || portA.tx_ant === antenna.number)}
{@const isPortBRx = !portB.tx && (portB.rx_ant === antenna.number || portB.tx_ant === antenna.number)}
{@const isTx = isPortATx || isPortBTx}
{@const isActive = isPortARx || isPortBRx}
<div
class="antenna-card"
class:tx={isTx}
class:active-a={isPortARx}
class:active-b={isPortBRx}
>
<div class="antenna-name">{antenna.name}</div>
<div class="antenna-ports">
<button
class="port-btn"
class:active={portA.tx_ant === antenna.number || portA.rx_ant === antenna.number}
on:click={() => selectAntenna(1, antenna.number)}
>
A
</button>
<button
class="port-btn"
class:active={portB.tx_ant === antenna.number || portB.rx_ant === antenna.number}
on:click={() => selectAntenna(2, antenna.number)}
>
B
</button>
</div>
</div>
{/each}
</div>
<!-- Reboot Button -->
<button class="reboot-btn" on:click={reboot}>
<span class="reboot-icon">🔄</span>
REBOOT
</button>
</div>
</div>
<style>
.card {
background: linear-gradient(135deg, #1a2332 0%, #0f1923 100%);
border: 1px solid #2d3748;
border-radius: 8px;
padding: 0;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
background: rgba(79, 195, 247, 0.05);
border-bottom: 1px solid #2d3748;
}
h2 {
font-size: 14px;
font-weight: 600;
color: var(--accent-cyan);
margin: 0;
letter-spacing: 0.5px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #4caf50;
box-shadow: 0 0 8px #4caf50;
}
.status-dot.disconnected {
background: #f44336;
box-shadow: 0 0 8px #f44336;
}
.metrics {
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
/* Sources */
.sources {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.source-item {
padding: 8px;
background: var(--bg-tertiary);
border-radius: 4px;
text-align: center;
}
.source-label {
font-size: 12px;
font-weight: 600;
color: var(--text-primary);
text-transform: uppercase;
}
/* Bands */
.bands {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.band-item {
padding: 10px;
background: rgba(79, 195, 247, 0.1);
border: 1px solid rgba(79, 195, 247, 0.3);
border-radius: 4px;
text-align: center;
}
.band-value {
font-size: 16px;
font-weight: 600;
color: var(--accent-cyan);
}
/* Antennas */
.antennas {
display: flex;
flex-direction: column;
gap: 8px;
}
.antenna-card {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
background: var(--bg-tertiary);
border: 2px solid var(--border-color);
border-radius: 6px;
transition: all 0.3s;
}
.antenna-card.tx {
background: rgba(244, 67, 54, 0.2);
border-color: #f44336;
box-shadow: 0 0 20px rgba(244, 67, 54, 0.4);
}
.antenna-card.active-a {
background: rgba(76, 175, 80, 0.2);
border-color: #4caf50;
box-shadow: 0 0 20px rgba(76, 175, 80, 0.3);
}
.antenna-card.active-b {
background: rgba(33, 150, 243, 0.2);
border-color: #2196f3;
box-shadow: 0 0 20px rgba(33, 150, 243, 0.3);
}
.antenna-name {
font-size: 14px;
font-weight: 500;
color: var(--text-primary);
}
.antenna-ports {
display: flex;
gap: 6px;
}
.port-btn {
width: 36px;
height: 36px;
border-radius: 4px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
border: 1px solid var(--border-color);
background: var(--bg-primary);
color: var(--text-secondary);
transition: all 0.2s;
}
.port-btn:hover {
border-color: var(--accent-cyan);
transform: scale(1.05);
}
.port-btn.active {
background: var(--accent-cyan);
border-color: var(--accent-cyan);
color: #000;
box-shadow: 0 0 12px rgba(79, 195, 247, 0.5);
}
/* Reboot Button */
.reboot-btn {
width: 100%;
padding: 12px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
cursor: pointer;
border: none;
background: linear-gradient(135deg, #ff9800, #f57c00);
color: white;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
box-shadow: 0 4px 12px rgba(255, 152, 0, 0.4);
margin-top: 8px;
}
.reboot-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(255, 152, 0, 0.5);
}
.reboot-btn:active {
transform: translateY(0);
}
.reboot-icon {
font-size: 16px;
}
</style>

View File

@@ -0,0 +1,492 @@
<script>
import { api } from '../lib/api.js';
export let status;
$: powerForward = status?.power_forward || 0;
$: powerReflected = status?.power_reflected || 0;
$: swr = status?.swr || 1.0;
$: voltage = status?.voltage || 0;
$: vdd = status?.vdd || 0;
$: current = status?.current || 0;
$: peakCurrent = status?.peak_current || 0;
$: temperature = status?.temperature || 0;
$: harmonicLoadTemp = status?.harmonic_load_temp || 0;
$: fanMode = status?.fan_mode || 'CONTEST';
$: state = status?.state || 'IDLE';
$: bandA = status?.band_a || '0';
$: bandB = status?.band_b || '0';
$: connected = status?.connected || false;
$: displayState = state.replace('TRANSMIT_A', 'TRANSMIT').replace('TRANSMIT_B', 'TRANSMIT');
// Color functions
$: tempColor = temperature < 40 ? '#4caf50' : temperature < 60 ? '#ffc107' : temperature < 75 ? '#ff9800' : '#f44336';
$: swrColor = swr < 1.5 ? '#4caf50' : swr < 2.0 ? '#ffc107' : swr < 3.0 ? '#ff9800' : '#f44336';
$: powerPercent = Math.min((powerForward / 2000) * 100, 100);
async function setFanMode(mode) {
try {
await api.power.setFanMode(mode);
} catch (err) {
console.error('Failed to set fan mode:', err);
alert('Failed to set fan mode');
}
}
async function toggleOperate() {
try {
const operateValue = state === 'IDLE' ? 0 : 1;
await api.power.setOperate(operateValue);
} catch (err) {
console.error('Failed to toggle operate:', err);
alert('Failed to toggle operate mode');
}
}
</script>
<div class="card">
<div class="card-header">
<h2>Power Genius XL</h2>
<div class="header-right">
<button
class="state-badge"
class:idle={state === 'IDLE'}
class:transmit={state.includes('TRANSMIT')}
on:click={toggleOperate}
>
{displayState}
</button>
<span class="status-dot" class:disconnected={!connected}></span>
</div>
</div>
<div class="metrics">
<!-- Power Display - Big and Bold -->
<div class="power-display">
<div class="power-main">
<div class="power-value">{powerForward.toFixed(0)}<span class="unit">W</span></div>
<div class="power-label">Forward Power</div>
</div>
<div class="power-bar">
<div class="power-bar-fill" style="width: {powerPercent}%">
<div class="power-bar-glow"></div>
</div>
<div class="power-scale">
<span>0</span>
<span>1000</span>
<span>2000</span>
</div>
</div>
</div>
<!-- SWR Circle Indicator -->
<div class="swr-container">
<div class="swr-circle" style="--swr-color: {swrColor}">
<div class="swr-value">{swr.toFixed(2)}</div>
<div class="swr-label">SWR</div>
</div>
<div class="swr-status">
{#if swr < 1.5}
<span class="status-text good">Excellent</span>
{:else if swr < 2.0}
<span class="status-text ok">Good</span>
{:else if swr < 3.0}
<span class="status-text warning">Caution</span>
{:else}
<span class="status-text danger">High!</span>
{/if}
</div>
</div>
<!-- Temperature Gauges -->
<div class="temp-group">
<div class="temp-item">
<div class="temp-value" style="color: {tempColor}">{temperature.toFixed(0)}°</div>
<div class="temp-label">PA Temp</div>
<div class="temp-mini-bar">
<div class="temp-mini-fill" style="width: {(temperature / 80) * 100}%; background: {tempColor}"></div>
</div>
</div>
<div class="temp-item">
<div class="temp-value" style="color: {tempColor}">{harmonicLoadTemp.toFixed(0)}°</div>
<div class="temp-label">HL Temp</div>
<div class="temp-mini-bar">
<div class="temp-mini-fill" style="width: {(harmonicLoadTemp / 80) * 100}%; background: {tempColor}"></div>
</div>
</div>
</div>
<!-- Electrical Parameters -->
<div class="params-grid">
<div class="param-box">
<div class="param-label">VAC</div>
<div class="param-value">{voltage.toFixed(0)}</div>
</div>
<div class="param-box">
<div class="param-label">VDD</div>
<div class="param-value">{vdd.toFixed(1)}</div>
</div>
<div class="param-box">
<div class="param-label">ID Peak</div>
<div class="param-value">{peakCurrent.toFixed(1)}</div>
</div>
</div>
<!-- Band Display -->
<div class="band-display">
<div class="band-item">
<span class="band-label">Band A</span>
<span class="band-value">{bandA}</span>
</div>
<div class="band-item">
<span class="band-label">Band B</span>
<span class="band-value">{bandB}</span>
</div>
</div>
<!-- Fan Control -->
<div class="fan-control">
<label class="control-label">Fan Mode</label>
<select value={fanMode} on:change={(e) => setFanMode(e.target.value)}>
<option value="STANDARD">Standard</option>
<option value="CONTEST">Contest</option>
<option value="BROADCAST">Broadcast</option>
</select>
</div>
</div>
</div>
<style>
.card {
background: linear-gradient(135deg, #1a2332 0%, #0f1923 100%);
border: 1px solid #2d3748;
border-radius: 8px;
padding: 0;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
background: rgba(79, 195, 247, 0.05);
border-bottom: 1px solid #2d3748;
}
h2 {
font-size: 14px;
font-weight: 600;
color: var(--accent-cyan);
margin: 0;
letter-spacing: 0.5px;
}
.header-right {
display: flex;
align-items: center;
gap: 8px;
}
.state-badge {
padding: 4px 12px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
cursor: pointer;
border: none;
transition: all 0.2s;
}
.state-badge.idle {
background: rgba(76, 175, 80, 0.2);
color: #4caf50;
}
.state-badge.transmit {
background: rgba(255, 152, 0, 0.2);
color: #ff9800;
animation: pulse 1s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #4caf50;
box-shadow: 0 0 8px #4caf50;
}
.status-dot.disconnected {
background: #f44336;
box-shadow: 0 0 8px #f44336;
}
.metrics {
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
}
/* Power Display */
.power-display {
display: flex;
flex-direction: column;
gap: 8px;
}
.power-main {
text-align: center;
}
.power-value {
font-size: 48px;
font-weight: 200;
color: var(--accent-cyan);
line-height: 1;
text-shadow: 0 0 20px rgba(79, 195, 247, 0.5);
}
.power-value .unit {
font-size: 24px;
color: var(--text-secondary);
margin-left: 4px;
}
.power-label {
font-size: 11px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 1px;
margin-top: 4px;
}
.power-bar {
position: relative;
height: 8px;
background: var(--bg-tertiary);
border-radius: 4px;
overflow: hidden;
}
.power-bar-fill {
position: relative;
height: 100%;
background: linear-gradient(90deg, #4caf50, #ffc107, #ff9800, #f44336);
border-radius: 4px;
transition: width 0.3s ease;
}
.power-bar-glow {
position: absolute;
top: 0;
right: 0;
width: 20px;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.5));
animation: shimmer 2s infinite;
}
@keyframes shimmer {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
.power-scale {
display: flex;
justify-content: space-between;
font-size: 9px;
color: var(--text-muted);
margin-top: 4px;
}
/* SWR Circle */
.swr-container {
display: flex;
align-items: center;
gap: 16px;
}
.swr-circle {
width: 80px;
height: 80px;
border-radius: 50%;
background: radial-gradient(circle, rgba(79, 195, 247, 0.1), transparent);
border: 3px solid var(--swr-color);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
box-shadow: 0 0 20px var(--swr-color);
}
.swr-value {
font-size: 24px;
font-weight: 300;
color: var(--swr-color);
}
.swr-label {
font-size: 10px;
color: var(--text-muted);
text-transform: uppercase;
}
.swr-status {
flex: 1;
}
.status-text {
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.status-text.good { color: #4caf50; }
.status-text.ok { color: #ffc107; }
.status-text.warning { color: #ff9800; }
.status-text.danger { color: #f44336; }
/* Temperature */
.temp-group {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.temp-item {
display: flex;
flex-direction: column;
gap: 4px;
padding: 12px;
background: var(--bg-tertiary);
border-radius: 6px;
}
.temp-value {
font-size: 32px;
font-weight: 300;
line-height: 1;
}
.temp-label {
font-size: 10px;
color: var(--text-muted);
text-transform: uppercase;
}
.temp-mini-bar {
height: 4px;
background: rgba(255, 255, 255, 0.1);
border-radius: 2px;
overflow: hidden;
margin-top: 4px;
}
.temp-mini-fill {
height: 100%;
border-radius: 2px;
transition: width 0.3s ease;
}
/* Parameters Grid */
.params-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.param-box {
padding: 8px;
background: var(--bg-tertiary);
border-radius: 4px;
text-align: center;
}
.param-label {
font-size: 9px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.param-value {
font-size: 18px;
font-weight: 300;
color: var(--text-primary);
margin-top: 2px;
}
/* Band Display */
.band-display {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
padding: 8px;
background: rgba(79, 195, 247, 0.05);
border-radius: 6px;
}
.band-item {
display: flex;
justify-content: space-between;
align-items: center;
}
.band-label {
font-size: 11px;
color: var(--text-muted);
}
.band-value {
font-size: 14px;
font-weight: 600;
color: var(--accent-cyan);
}
/* Fan Control */
.fan-control {
display: flex;
flex-direction: column;
gap: 6px;
}
.control-label {
font-size: 11px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.5px;
}
select {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-color);
border-radius: 4px;
padding: 8px;
font-size: 12px;
cursor: pointer;
outline: none;
transition: all 0.2s;
}
select:hover {
border-color: var(--accent-cyan);
}
select:focus {
border-color: var(--accent-cyan);
box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.2);
}
</style>

View File

@@ -0,0 +1,427 @@
<script>
import { api } from '../lib/api.js';
export let status;
$: heading = status?.heading || 0;
$: connected = status?.connected || false;
let targetHeading = 0;
async function goToHeading() {
if (targetHeading < 0 || targetHeading > 359) {
alert('Heading must be between 0 and 359');
return;
}
try {
// Subtract 10 degrees to compensate for rotator momentum
const adjustedHeading = (targetHeading - 10 + 360) % 360;
await api.rotator.setHeading(adjustedHeading);
} catch (err) {
console.error('Failed to set heading:', err);
alert('Failed to rotate');
}
}
async function rotateCW() {
try {
await api.rotator.rotateCW();
} catch (err) {
console.error('Failed to rotate CW:', err);
}
}
async function rotateCCW() {
try {
await api.rotator.rotateCCW();
} catch (err) {
console.error('Failed to rotate CCW:', err);
}
}
async function stop() {
try {
await api.rotator.stop();
} catch (err) {
console.error('Failed to stop:', err);
}
}
</script>
<div class="card">
<div class="card-header">
<h2>Rotator Genius</h2>
<span class="status-dot" class:disconnected={!connected}></span>
</div>
<div class="metrics">
<!-- Current Heading Display -->
<div class="heading-display">
<div class="heading-label">CURRENT HEADING</div>
<div class="heading-value">{heading}°</div>
</div>
<!-- Map with Beam -->
<div class="map-container">
<svg viewBox="0 0 500 500" class="map-svg">
<defs>
<!-- Gradient for beam -->
<radialGradient id="beamGradient">
<stop offset="0%" style="stop-color:rgba(79, 195, 247, 0.7);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgba(79, 195, 247, 0);stop-opacity:0" />
</radialGradient>
</defs>
<!-- Ocean background -->
<circle cx="250" cy="250" r="240" fill="rgba(30, 64, 175, 0.2)" stroke="rgba(79, 195, 247, 0.4)" stroke-width="3"/>
<!-- Simplified world map (Azimuthal centered on France ~46°N 6°E) -->
<g transform="translate(250, 250)" opacity="0.5">
<!-- Europe (enlarged and centered) -->
<!-- France -->
<path d="M -20,-15 L -15,-25 L -5,-28 L 5,-25 L 10,-18 L 8,-8 L 0,-5 L -10,-8 L -18,-12 Z"
fill="#4CAF50" stroke="#81C784" stroke-width="1.5"/>
<!-- Spain/Portugal -->
<path d="M -30,-8 L -22,-12 L -18,-8 L -20,0 L -25,5 L -32,3 L -35,-2 Z"
fill="#4CAF50" stroke="#81C784" stroke-width="1.5"/>
<!-- Italy -->
<path d="M 5,-10 L 10,-12 L 15,-8 L 18,5 L 15,15 L 10,12 L 8,0 Z"
fill="#4CAF50" stroke="#81C784" stroke-width="1.5"/>
<!-- Germany/Central Europe -->
<path d="M -5,-28 L 5,-32 L 15,-30 L 20,-22 L 15,-18 L 5,-20 L 0,-25 Z"
fill="#4CAF50" stroke="#81C784" stroke-width="1.5"/>
<!-- UK/Ireland -->
<path d="M -45,-25 L -40,-32 L -32,-35 L -28,-28 L -32,-20 L -40,-22 Z"
fill="#4CAF50" stroke="#81C784" stroke-width="1.5"/>
<!-- Scandinavia -->
<path d="M 0,-40 L 10,-50 L 20,-48 L 25,-38 L 20,-32 L 10,-35 L 5,-38 Z"
fill="#66BB6A" stroke="#81C784" stroke-width="1.5"/>
<!-- Eastern Europe/Russia West -->
<path d="M 20,-35 L 35,-40 L 50,-35 L 55,-20 L 50,-10 L 35,-8 L 25,-15 Z"
fill="#66BB6A" stroke="#81C784" stroke-width="1.5"/>
<!-- North Africa -->
<path d="M -35,10 L -20,8 L 0,12 L 15,18 L 10,35 L -5,40 L -25,35 L -35,25 Z"
fill="#FFA726" stroke="#FFB74D" stroke-width="1.5"/>
<!-- Sub-Saharan Africa -->
<path d="M -20,42 L 0,45 L 15,50 L 20,70 L 10,95 L -10,100 L -30,90 L -35,70 L -30,50 Z"
fill="#FF9800" stroke="#FFB74D" stroke-width="1.5"/>
<!-- Middle East -->
<path d="M 25,0 L 40,5 L 55,10 L 60,25 L 55,38 L 42,42 L 30,35 L 22,20 Z"
fill="#FFEB3B" stroke="#FFF176" stroke-width="1.5"/>
<!-- Russia East/Central Asia -->
<path d="M 60,-30 L 90,-35 L 120,-25 L 135,-10 L 140,15 L 130,30 L 105,35 L 80,28 L 65,10 L 62,-10 Z"
fill="#AB47BC" stroke="#BA68C8" stroke-width="1.5"/>
<!-- India/South Asia -->
<path d="M 70,40 L 85,38 L 95,45 L 98,60 L 92,75 L 78,80 L 68,72 L 65,55 Z"
fill="#EC407A" stroke="#F06292" stroke-width="1.5"/>
<!-- China/East Asia -->
<path d="M 110,0 L 135,5 L 150,18 L 155,35 L 145,52 L 125,58 L 105,50 L 95,32 L 100,15 Z"
fill="#7E57C2" stroke="#9575CD" stroke-width="1.5"/>
<!-- Japan -->
<path d="M 165,25 L 172,22 L 178,28 L 175,40 L 168,45 L 162,42 L 160,32 Z"
fill="#E91E63" stroke="#F06292" stroke-width="1.5"/>
<!-- North America -->
<path d="M -140,-40 L -110,-50 L -80,-48 L -60,-35 L -55,-15 L -65,5 L -85,15 L -110,12 L -135,-5 L -145,-25 Z"
fill="#42A5F5" stroke="#64B5F6" stroke-width="1.5"/>
<!-- Central America -->
<path d="M -75,20 L -65,18 L -55,25 L -58,35 L -68,38 L -78,32 Z"
fill="#29B6F6" stroke="#4FC3F7" stroke-width="1.5"/>
<!-- South America -->
<path d="M -70,45 L -60,42 L -48,50 L -45,70 L -50,100 L -60,120 L -75,125 L -88,115 L -92,90 L -85,65 L -78,52 Z"
fill="#26C6DA" stroke="#4DD0E1" stroke-width="1.5"/>
<!-- Australia -->
<path d="M 130,95 L 155,92 L 175,100 L 180,120 L 170,135 L 145,138 L 125,128 L 122,110 Z"
fill="#66BB6A" stroke="#81C784" stroke-width="1.5"/>
</g>
<!-- Distance circles -->
<circle cx="250" cy="250" r="180" fill="none" stroke="rgba(79,195,247,0.2)" stroke-width="1" stroke-dasharray="4,4"/>
<circle cx="250" cy="250" r="120" fill="none" stroke="rgba(79,195,247,0.2)" stroke-width="1" stroke-dasharray="4,4"/>
<circle cx="250" cy="250" r="60" fill="none" stroke="rgba(79,195,247,0.2)" stroke-width="1" stroke-dasharray="4,4"/>
<!-- Rotated group for beam -->
<g transform="translate(250, 250)">
<!-- Beam (rotates with heading) -->
<g transform="rotate({heading})">
<!-- Beam sector (±15° = 30° total beamwidth) -->
<path d="M 0,0 L {-Math.sin(15 * Math.PI/180) * 220},{-Math.cos(15 * Math.PI/180) * 220}
A 220,220 0 0,1 {Math.sin(15 * Math.PI/180) * 220},{-Math.cos(15 * Math.PI/180) * 220} Z"
fill="url(#beamGradient)"
opacity="0.85"/>
<!-- Beam outline -->
<line x1="0" y1="0" x2={-Math.sin(15 * Math.PI/180) * 220} y2={-Math.cos(15 * Math.PI/180) * 220}
stroke="#4fc3f7" stroke-width="3" opacity="0.9"/>
<line x1="0" y1="0" x2={Math.sin(15 * Math.PI/180) * 220} y2={-Math.cos(15 * Math.PI/180) * 220}
stroke="#4fc3f7" stroke-width="3" opacity="0.9"/>
<!-- Direction arrow -->
<g transform="translate(0, -190)">
<polygon points="0,-30 -12,8 0,0 12,8"
fill="#4fc3f7"
stroke="#0288d1"
stroke-width="3"
style="filter: drop-shadow(0 0 15px rgba(79, 195, 247, 1))"/>
</g>
</g>
<!-- Center dot (your QTH - JN36dg) -->
<circle cx="0" cy="0" r="6" fill="#f44336" stroke="#fff" stroke-width="3">
<animate attributeName="r" values="6;9;6" dur="2s" repeatCount="indefinite"/>
</circle>
<circle cx="0" cy="0" r="12" fill="none" stroke="#f44336" stroke-width="2" opacity="0.5">
<animate attributeName="r" values="12;20;12" dur="2s" repeatCount="indefinite"/>
<animate attributeName="opacity" values="0.5;0;0.5" dur="2s" repeatCount="indefinite"/>
</circle>
</g>
<!-- Cardinal points -->
<text x="250" y="30" text-anchor="middle" class="cardinal">N</text>
<text x="470" y="255" text-anchor="middle" class="cardinal">E</text>
<text x="250" y="480" text-anchor="middle" class="cardinal">S</text>
<text x="30" y="255" text-anchor="middle" class="cardinal">W</text>
<!-- Degree markers every 30° -->
{#each [30, 60, 120, 150, 210, 240, 300, 330] as angle}
{@const x = 250 + 215 * Math.sin(angle * Math.PI / 180)}
{@const y = 250 - 215 * Math.cos(angle * Math.PI / 180)}
<text x={x} y={y} text-anchor="middle" dominant-baseline="middle" class="degree-label">{angle}°</text>
{/each}
</svg>
</div>
<!-- Go To Heading -->
<div class="goto-container">
<input
type="number"
min="0"
max="359"
bind:value={targetHeading}
placeholder="Enter heading"
class="heading-input"
/>
<button class="go-btn" on:click={goToHeading}>GO</button>
</div>
<!-- Control Buttons -->
<div class="controls">
<button class="control-btn ccw" on:click={rotateCCW}>
<span class="arrow"></span>
CCW
</button>
<button class="control-btn stop" on:click={stop}>
STOP
</button>
<button class="control-btn cw" on:click={rotateCW}>
<span class="arrow"></span>
CW
</button>
</div>
</div>
</div>
<style>
.card {
background: linear-gradient(135deg, #1a2332 0%, #0f1923 100%);
border: 1px solid #2d3748;
border-radius: 8px;
padding: 0;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
background: rgba(79, 195, 247, 0.05);
border-bottom: 1px solid #2d3748;
}
h2 {
font-size: 14px;
font-weight: 600;
color: var(--accent-cyan);
margin: 0;
letter-spacing: 0.5px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #4caf50;
box-shadow: 0 0 8px #4caf50;
}
.status-dot.disconnected {
background: #f44336;
box-shadow: 0 0 8px #f44336;
}
.metrics {
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
}
/* Heading Display */
.heading-display {
text-align: center;
padding: 12px;
background: rgba(79, 195, 247, 0.1);
border-radius: 6px;
border: 1px solid rgba(79, 195, 247, 0.3);
}
.heading-label {
font-size: 10px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 4px;
}
.heading-value {
font-size: 42px;
font-weight: 200;
color: var(--accent-cyan);
text-shadow: 0 0 20px rgba(79, 195, 247, 0.5);
}
/* Map */
.map-container {
display: flex;
justify-content: center;
padding: 10px;
background: rgba(10, 22, 40, 0.6);
border-radius: 8px;
}
.map-svg {
width: 100%;
max-width: 500px;
height: auto;
}
.cardinal {
fill: var(--accent-cyan);
font-size: 18px;
font-weight: 700;
text-shadow: 0 0 10px rgba(79, 195, 247, 0.8);
}
.degree-label {
fill: rgba(79, 195, 247, 0.7);
font-size: 12px;
font-weight: 600;
}
/* Go To Heading */
.goto-container {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
}
.heading-input {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-color);
border-radius: 4px;
padding: 10px 12px;
font-size: 14px;
outline: none;
transition: all 0.2s;
}
.heading-input:focus {
border-color: var(--accent-cyan);
box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.2);
}
.go-btn {
padding: 10px 24px;
border-radius: 4px;
font-size: 13px;
font-weight: 600;
text-transform: uppercase;
cursor: pointer;
border: none;
background: linear-gradient(135deg, var(--accent-cyan), #0288d1);
color: #000;
transition: all 0.2s;
box-shadow: 0 4px 12px rgba(79, 195, 247, 0.4);
}
.go-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(79, 195, 247, 0.5);
}
/* Controls */
.controls {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 8px;
}
.control-btn {
padding: 12px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
cursor: pointer;
border: 1px solid var(--border-color);
background: var(--bg-tertiary);
color: var(--text-primary);
transition: all 0.2s;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.control-btn:hover {
border-color: var(--accent-cyan);
transform: translateY(-1px);
}
.control-btn.stop {
background: linear-gradient(135deg, #f44336, #d32f2f);
border-color: #f44336;
color: white;
box-shadow: 0 4px 12px rgba(244, 67, 54, 0.4);
}
.control-btn.stop:hover {
box-shadow: 0 6px 16px rgba(244, 67, 54, 0.5);
}
.arrow {
font-size: 20px;
line-height: 1;
}
</style>

View File

@@ -0,0 +1,477 @@
<script>
import { api } from '../lib/api.js';
export let status;
$: powerForward = status?.power_forward || 0;
$: swr = status?.swr || 1.0;
$: tuningStatus = status?.tuning_status || 'READY';
$: frequencyA = status?.frequency_a || 0;
$: frequencyB = status?.frequency_b || 0;
$: bypass = status?.bypass || false;
$: state = status?.state || 0;
$: relayC1 = status?.c1 || 0;
$: relayL = status?.l || 0;
$: relayC2 = status?.c2 || 0;
$: connected = status?.connected || false;
// Color functions
$: swrColor = swr < 1.5 ? '#4caf50' : swr < 2.0 ? '#ffc107' : swr < 3.0 ? '#ff9800' : '#f44336';
$: powerPercent = Math.min((powerForward / 2000) * 100, 100);
async function autoTune() {
try {
await api.tuner.autoTune();
} catch (err) {
console.error('Failed to tune:', err);
alert('Failed to start tuning');
}
}
async function setBypass(value) {
try {
await api.tuner.setBypass(value);
} catch (err) {
console.error('Failed to set bypass:', err);
alert('Failed to set bypass');
}
}
async function setOperate(value) {
try {
await api.tuner.setOperate(value);
} catch (err) {
console.error('Failed to set operate:', err);
alert('Failed to set operate');
}
}
</script>
<div class="card">
<div class="card-header">
<h2>Tuner Genius XL</h2>
<div class="header-right">
<span class="tuning-badge" class:tuning={tuningStatus === 'TUNING'}>{tuningStatus}</span>
<span class="status-dot" class:disconnected={!connected}></span>
</div>
</div>
<div class="metrics">
<!-- Power Display -->
<div class="power-display">
<div class="power-main">
<div class="power-value">{powerForward.toFixed(0)}<span class="unit">W</span></div>
<div class="power-label">Forward Power</div>
</div>
<div class="power-bar">
<div class="power-bar-fill" style="width: {powerPercent}%">
<div class="power-bar-glow"></div>
</div>
<div class="power-scale">
<span>0</span>
<span>1000</span>
<span>2000</span>
</div>
</div>
</div>
<!-- SWR Circle -->
<div class="swr-container">
<div class="swr-circle" style="--swr-color: {swrColor}">
<div class="swr-value">{swr.toFixed(2)}</div>
<div class="swr-label">SWR</div>
</div>
<div class="swr-status">
{#if swr < 1.5}
<span class="status-text good">Excellent</span>
{:else if swr < 2.0}
<span class="status-text ok">Good</span>
{:else if swr < 3.0}
<span class="status-text warning">Caution</span>
{:else}
<span class="status-text danger">High!</span>
{/if}
</div>
</div>
<!-- Tuning Capacitors -->
<div class="capacitors">
<div class="cap-item">
<div class="cap-value">{relayC1}</div>
<div class="cap-label">C1</div>
</div>
<div class="cap-item">
<div class="cap-value">{relayL}</div>
<div class="cap-label">L</div>
</div>
<div class="cap-item">
<div class="cap-value">{relayC2}</div>
<div class="cap-label">C2</div>
</div>
</div>
<!-- Frequencies -->
<div class="freq-display">
<div class="freq-item">
<div class="freq-label">Freq A</div>
<div class="freq-value">{(frequencyA / 1000).toFixed(3)}<span class="freq-unit">MHz</span></div>
</div>
<div class="freq-item">
<div class="freq-label">Freq B</div>
<div class="freq-value">{(frequencyB / 1000).toFixed(3)}<span class="freq-unit">MHz</span></div>
</div>
</div>
<!-- Control Buttons -->
<div class="controls">
<button
class="control-btn operate"
class:active={state === 1}
on:click={() => setOperate(state === 1 ? 0 : 1)}
>
{state === 1 ? 'OPERATE' : 'STANDBY'}
</button>
<button
class="control-btn bypass"
class:active={bypass}
on:click={() => setBypass(bypass ? 0 : 1)}
>
BYPASS
</button>
</div>
<button class="tune-btn" on:click={autoTune}>
<span class="tune-icon"></span>
AUTO TUNE
</button>
</div>
</div>
<style>
.card {
background: linear-gradient(135deg, #1a2332 0%, #0f1923 100%);
border: 1px solid #2d3748;
border-radius: 8px;
padding: 0;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
background: rgba(79, 195, 247, 0.05);
border-bottom: 1px solid #2d3748;
}
h2 {
font-size: 14px;
font-weight: 600;
color: var(--accent-cyan);
margin: 0;
letter-spacing: 0.5px;
}
.header-right {
display: flex;
align-items: center;
gap: 8px;
}
.tuning-badge {
padding: 4px 12px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
background: rgba(76, 175, 80, 0.2);
color: #4caf50;
}
.tuning-badge.tuning {
background: rgba(255, 152, 0, 0.2);
color: #ff9800;
animation: pulse 1s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #4caf50;
box-shadow: 0 0 8px #4caf50;
}
.status-dot.disconnected {
background: #f44336;
box-shadow: 0 0 8px #f44336;
}
.metrics {
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
}
/* Power Display */
.power-display {
display: flex;
flex-direction: column;
gap: 8px;
}
.power-main {
text-align: center;
}
.power-value {
font-size: 48px;
font-weight: 200;
color: var(--accent-cyan);
line-height: 1;
text-shadow: 0 0 20px rgba(79, 195, 247, 0.5);
}
.power-value .unit {
font-size: 24px;
color: var(--text-secondary);
margin-left: 4px;
}
.power-label {
font-size: 11px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 1px;
margin-top: 4px;
}
.power-bar {
position: relative;
height: 8px;
background: var(--bg-tertiary);
border-radius: 4px;
overflow: hidden;
}
.power-bar-fill {
position: relative;
height: 100%;
background: linear-gradient(90deg, #4caf50, #ffc107, #ff9800, #f44336);
border-radius: 4px;
transition: width 0.3s ease;
}
.power-bar-glow {
position: absolute;
top: 0;
right: 0;
width: 20px;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.5));
animation: shimmer 2s infinite;
}
@keyframes shimmer {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
.power-scale {
display: flex;
justify-content: space-between;
font-size: 9px;
color: var(--text-muted);
margin-top: 4px;
}
/* SWR Circle */
.swr-container {
display: flex;
align-items: center;
gap: 16px;
}
.swr-circle {
width: 80px;
height: 80px;
border-radius: 50%;
background: radial-gradient(circle, rgba(79, 195, 247, 0.1), transparent);
border: 3px solid var(--swr-color);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
box-shadow: 0 0 20px var(--swr-color);
}
.swr-value {
font-size: 24px;
font-weight: 300;
color: var(--swr-color);
}
.swr-label {
font-size: 10px;
color: var(--text-muted);
text-transform: uppercase;
}
.swr-status {
flex: 1;
}
.status-text {
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.status-text.good { color: #4caf50; }
.status-text.ok { color: #ffc107; }
.status-text.warning { color: #ff9800; }
.status-text.danger { color: #f44336; }
/* Capacitors */
.capacitors {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
padding: 16px;
background: rgba(79, 195, 247, 0.05);
border-radius: 6px;
border: 1px solid rgba(79, 195, 247, 0.2);
}
.cap-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.cap-value {
font-size: 32px;
font-weight: 300;
color: var(--accent-cyan);
text-shadow: 0 0 15px rgba(79, 195, 247, 0.5);
}
.cap-label {
font-size: 10px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 1px;
}
/* Frequencies */
.freq-display {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.freq-item {
padding: 10px;
background: var(--bg-tertiary);
border-radius: 6px;
display: flex;
flex-direction: column;
gap: 4px;
}
.freq-label {
font-size: 9px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.freq-value {
font-size: 16px;
font-weight: 300;
color: var(--text-primary);
}
.freq-unit {
font-size: 11px;
color: var(--text-secondary);
margin-left: 2px;
}
/* Controls */
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.control-btn {
padding: 12px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
cursor: pointer;
border: 1px solid var(--border-color);
background: var(--bg-tertiary);
color: var(--text-primary);
transition: all 0.2s;
}
.control-btn:hover {
border-color: var(--accent-cyan);
transform: translateY(-1px);
}
.control-btn.active {
background: var(--accent-cyan);
border-color: var(--accent-cyan);
color: #000;
box-shadow: 0 0 15px rgba(79, 195, 247, 0.5);
}
.tune-btn {
width: 100%;
padding: 14px;
border-radius: 6px;
font-size: 13px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
cursor: pointer;
border: none;
background: linear-gradient(135deg, #f44336, #d32f2f);
color: white;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
box-shadow: 0 4px 12px rgba(244, 67, 54, 0.4);
}
.tune-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(244, 67, 54, 0.5);
}
.tune-btn:active {
transform: translateY(0);
}
.tune-icon {
font-size: 18px;
}
</style>

View File

@@ -0,0 +1,305 @@
<script>
import { api } from '../lib/api.js';
export let status;
$: relays = status?.relays || [];
$: connected = status?.connected || false;
const relayNames = {
1: 'Power Supply',
2: 'PGXL',
3: 'TGXL',
4: 'Flex Radio Start',
5: 'Reserve'
};
let loading = {};
async function toggleRelay(relayNum) {
const relay = relays.find(r => r.number === relayNum);
const currentState = relay?.state || false;
loading[relayNum] = true;
try {
if (currentState) {
await api.webswitch.relayOff(relayNum);
} else {
await api.webswitch.relayOn(relayNum);
}
} catch (err) {
console.error('Failed to toggle relay:', err);
alert('Failed to control relay');
} finally {
loading[relayNum] = false;
}
}
async function allOn() {
try {
await api.webswitch.allOn();
} catch (err) {
console.error('Failed to turn all on:', err);
}
}
async function allOff() {
try {
await api.webswitch.allOff();
} catch (err) {
console.error('Failed to turn all off:', err);
}
}
</script>
<div class="card">
<div class="card-header">
<h2>WebSwitch</h2>
<span class="status-dot" class:disconnected={!connected}></span>
</div>
<div class="metrics">
<div class="relays">
{#each [1, 2, 3, 4, 5] as relayNum}
{@const relay = relays.find(r => r.number === relayNum)}
{@const isOn = relay?.state || false}
<div class="relay-card" class:relay-on={isOn}>
<div class="relay-info">
<div class="relay-details">
<div class="relay-name">{relayNames[relayNum]}</div>
<div class="relay-status">{isOn ? 'ON' : 'OFF'}</div>
</div>
</div>
<button
class="relay-toggle"
class:active={isOn}
class:loading={loading[relayNum]}
disabled={loading[relayNum]}
on:click={() => toggleRelay(relayNum)}
>
<div class="toggle-track">
<div class="toggle-thumb"></div>
</div>
</button>
</div>
{/each}
</div>
<div class="controls">
<button class="control-btn all-on" on:click={allOn}>
<span class="btn-icon"></span>
ALL ON
</button>
<button class="control-btn all-off" on:click={allOff}>
<span class="btn-icon"></span>
ALL OFF
</button>
</div>
</div>
</div>
<style>
.card {
background: linear-gradient(135deg, #1a2332 0%, #0f1923 100%);
border: 1px solid #2d3748;
border-radius: 8px;
padding: 0;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
background: rgba(79, 195, 247, 0.05);
border-bottom: 1px solid #2d3748;
}
h2 {
font-size: 14px;
font-weight: 600;
color: var(--accent-cyan);
margin: 0;
letter-spacing: 0.5px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #4caf50;
box-shadow: 0 0 8px #4caf50;
}
.status-dot.disconnected {
background: #f44336;
box-shadow: 0 0 8px #f44336;
}
.metrics {
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
/* Relays */
.relays {
display: flex;
flex-direction: column;
gap: 8px;
}
.relay-card {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
background: var(--bg-tertiary);
border-radius: 6px;
border: 1px solid var(--border-color);
transition: all 0.3s;
}
.relay-card.relay-on {
background: rgba(76, 175, 80, 0.1);
border-color: rgba(76, 175, 80, 0.3);
box-shadow: 0 0 15px rgba(76, 175, 80, 0.2);
}
.relay-info {
display: flex;
align-items: center;
}
.relay-details {
display: flex;
flex-direction: column;
gap: 2px;
}
.relay-name {
font-size: 12px;
color: var(--text-primary);
font-weight: 500;
}
.relay-status {
font-size: 10px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.relay-card.relay-on .relay-status {
color: #4caf50;
font-weight: 600;
}
/* Toggle Switch */
.relay-toggle {
padding: 0;
background: transparent;
border: none;
cursor: pointer;
}
.toggle-track {
width: 52px;
height: 28px;
background: var(--bg-primary);
border: 2px solid var(--border-color);
border-radius: 14px;
position: relative;
transition: all 0.3s;
}
.relay-toggle:hover .toggle-track {
border-color: var(--accent-cyan);
}
.relay-toggle.active .toggle-track {
background: linear-gradient(135deg, #4caf50, #66bb6a);
border-color: #4caf50;
box-shadow: 0 0 15px rgba(76, 175, 80, 0.5);
}
.toggle-thumb {
width: 20px;
height: 20px;
background: white;
border-radius: 50%;
position: absolute;
top: 2px;
left: 2px;
transition: all 0.3s;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.relay-toggle.active .toggle-thumb {
transform: translateX(24px);
}
.relay-toggle:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Controls */
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 8px;
}
.control-btn {
padding: 12px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
cursor: pointer;
border: none;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.control-btn:hover {
transform: translateY(-2px);
}
.control-btn:active {
transform: translateY(0);
}
.btn-icon {
font-size: 16px;
}
.all-on {
background: linear-gradient(135deg, #4caf50, #66bb6a);
color: white;
box-shadow: 0 4px 12px rgba(76, 175, 80, 0.4);
}
.all-on:hover {
box-shadow: 0 6px 16px rgba(76, 175, 80, 0.5);
}
.all-off {
background: linear-gradient(135deg, #f44336, #d32f2f);
color: white;
box-shadow: 0 4px 12px rgba(244, 67, 54, 0.4);
}
.all-off:hover {
box-shadow: 0 6px 16px rgba(244, 67, 54, 0.5);
}
</style>

92
web/src/lib/api.js Normal file
View File

@@ -0,0 +1,92 @@
const API_BASE = '/api';
async function request(endpoint, options = {}) {
try {
const response = await fetch(`${API_BASE}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
export const api = {
// Status
getStatus: () => request('/status'),
getConfig: () => request('/config'),
// WebSwitch
webswitch: {
relayOn: (relay) => request(`/webswitch/relay/on?relay=${relay}`, { method: 'POST' }),
relayOff: (relay) => request(`/webswitch/relay/off?relay=${relay}`, { method: 'POST' }),
allOn: () => request('/webswitch/all/on', { method: 'POST' }),
allOff: () => request('/webswitch/all/off', { method: 'POST' }),
},
// Rotator
rotator: {
move: (rotator, azimuth) => request('/rotator/move', {
method: 'POST',
body: JSON.stringify({ rotator, azimuth }),
}),
cw: (rotator) => request(`/rotator/cw?rotator=${rotator}`, { method: 'POST' }),
ccw: (rotator) => request(`/rotator/ccw?rotator=${rotator}`, { method: 'POST' }),
stop: () => request('/rotator/stop', { method: 'POST' }),
},
// Tuner
tuner: {
setOperate: (value) => request('/tuner/operate', {
method: 'POST',
body: JSON.stringify({ value }),
}),
setBypass: (value) => request('/tuner/bypass', {
method: 'POST',
body: JSON.stringify({ value }),
}),
autoTune: () => request('/tuner/autotune', { method: 'POST' }),
},
// Antenna Genius
antenna: {
selectAntenna: (port, antenna) => request('/antenna/select', {
method: 'POST',
body: JSON.stringify({ port, antenna }),
}),
reboot: () => request('/antenna/reboot', { method: 'POST' }),
},
// Power Genius
power: {
setFanMode: (mode) => request('/power/fanmode', {
method: 'POST',
body: JSON.stringify({ mode }),
}),
setOperate: (value) => request('/power/operate', {
method: 'POST',
body: JSON.stringify({ value }),
}),
},
// Rotator Genius
rotator: {
setHeading: (heading) => request('/rotator/heading', {
method: 'POST',
body: JSON.stringify({ heading }),
}),
rotateCW: () => request('/rotator/cw', { method: 'POST' }),
rotateCCW: () => request('/rotator/ccw', { method: 'POST' }),
stop: () => request('/rotator/stop', { method: 'POST' }),
},
};

82
web/src/lib/websocket.js Normal file
View File

@@ -0,0 +1,82 @@
import { writable } from 'svelte/store';
export const connected = writable(false);
export const systemStatus = writable(null);
export const lastUpdate = writable(null);
class WebSocketService {
constructor() {
this.ws = null;
this.reconnectTimeout = null;
this.reconnectDelay = 3000;
}
connect() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/ws`;
try {
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('WebSocket connected');
connected.set(true);
};
this.ws.onmessage = (event) => {
try {
const message = JSON.parse(event.data);
if (message.type === 'update') {
console.log('System status updated:', message.data);
systemStatus.set(message.data);
lastUpdate.set(new Date(message.timestamp));
}
} catch (err) {
console.error('Error parsing message:', err);
}
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
this.ws.onclose = () => {
console.log('WebSocket disconnected');
connected.set(false);
this.scheduleReconnect();
};
} catch (err) {
console.error('Error creating WebSocket:', err);
this.scheduleReconnect();
}
}
scheduleReconnect() {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout);
}
this.reconnectTimeout = setTimeout(() => {
console.log('Attempting to reconnect...');
this.connect();
}, this.reconnectDelay);
}
send(message) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(message));
}
}
disconnect() {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout);
}
if (this.ws) {
this.ws.close();
}
}
}
export const wsService = new WebSocketService();

8
web/src/main.js Normal file
View File

@@ -0,0 +1,8 @@
import App from './App.svelte'
import './app.css'
const app = new App({
target: document.getElementById('app')
})
export default app

1
web/svelte.config.js Normal file
View File

@@ -0,0 +1 @@
export default {}

19
web/vite.config.js Normal file
View File

@@ -0,0 +1,19 @@
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
export default defineConfig({
plugins: [svelte()],
build: {
outDir: 'dist'
},
server: {
port: 5173,
proxy: {
'/api': 'http://localhost:8081',
'/ws': {
target: 'ws://localhost:8081',
ws: true
}
}
}
})