rot finished
This commit is contained in:
437
internal/devices/antennagenius/antennagenius.go
Normal file
437
internal/devices/antennagenius/antennagenius.go
Normal 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
|
||||
}
|
||||
35
internal/devices/command_id.go
Normal file
35
internal/devices/command_id.go
Normal 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
|
||||
}
|
||||
413
internal/devices/powergenius/powergenius.go
Normal file
413
internal/devices/powergenius/powergenius.go
Normal 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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user