rot finished
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user