Skip to content

Commit

Permalink
make the VFO offlineClient thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
ftl committed May 26, 2024
1 parent a160605 commit 35a8e08
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions core/vfo/vfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package vfo

import (
"log"
"sync"

"github.com/ftl/hamradio"
"github.com/ftl/hamradio/bandplan"
Expand Down Expand Up @@ -157,13 +158,15 @@ type bandState struct {
type offlineClient struct {
vfo *VFO
currentBand core.Band
stateLock *sync.RWMutex
lastStates map[core.Band]bandState
}

func newOfflineClient(vfo *VFO) *offlineClient {
result := &offlineClient{
vfo: vfo,
currentBand: core.Band160m,
stateLock: &sync.RWMutex{},
lastStates: make(map[core.Band]bandState),
}
_ = result.lastState(result.currentBand)
Expand All @@ -175,16 +178,19 @@ func (c *offlineClient) lastState(band core.Band) bandState {
if ok {
return result
}

plan, ok := c.vfo.bandplan[bandplan.BandName(band)]
if !ok {
log.Printf("Band %s not found in bandplan! (1)", band)
return bandState{}
}

result = bandState{
frequency: core.Frequency(plan.From),
mode: core.ModeCW,
}
c.lastStates[band] = result

return result
}

Expand All @@ -193,7 +199,9 @@ func (c *offlineClient) Active() bool {
}

func (c *offlineClient) Refresh() {
c.stateLock.RLock()
state := c.lastState(c.currentBand)
c.stateLock.RUnlock()

c.vfo.emitFrequencyChanged(state.frequency)
c.vfo.emitBandChanged(c.currentBand)
Expand All @@ -204,9 +212,12 @@ func (c *offlineClient) SetFrequency(frequency core.Frequency) {
planband := c.vfo.bandplan.ByFrequency(hamradio.Frequency(frequency))
newBand := core.Band(planband.Name)

c.stateLock.Lock()
state := c.lastState(newBand)
state.frequency = frequency
c.lastStates[newBand] = state
c.stateLock.Unlock()

c.vfo.emitFrequencyChanged(frequency)

if newBand == c.currentBand {
Expand All @@ -228,16 +239,22 @@ func (c *offlineClient) SetBand(band core.Band) {
return
}

c.stateLock.RLock()
state := c.lastState(newBand)
c.stateLock.RUnlock()

c.vfo.emitFrequencyChanged(state.frequency)

c.currentBand = newBand
c.vfo.emitBandChanged(c.currentBand)
}

func (c *offlineClient) SetMode(mode core.Mode) {
c.stateLock.Lock()
state := c.lastState(c.currentBand)
state.mode = mode
c.lastStates[c.currentBand] = state
c.stateLock.Unlock()

c.vfo.emitModeChanged(mode)
}

0 comments on commit 35a8e08

Please sign in to comment.