Keba: fix race in listener (#7495)

This commit is contained in:
andig 2023-04-16 13:12:00 +02:00 • committed by GitHub
parent 859148b0e6
commit 1db847fd6c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 9 deletions

View file

@ -75,12 +75,9 @@ func NewKebaFromConfig(other map[string]interface{}) (api.Charger, error) {
func NewKeba(uri, serial string, rfid RFID, timeout time.Duration) (*Keba, error) {
log := util.NewLogger("keba")
if keba.Instance == nil {
var err error
keba.Instance, err = keba.New(log)
if err != nil {
return nil, err
}
instance, err := keba.Instance(log)
if err != nil {
return nil, err
}
// add default port
@ -101,7 +98,7 @@ func NewKeba(uri, serial string, rfid RFID, timeout time.Duration) (*Keba, error
serial = conn
}
keba.Instance.Subscribe(serial, c.recv)
instance.Subscribe(serial, c.recv)
return c, err
}

View file

@ -23,9 +23,12 @@ const (
Any = "<any>"
)
// Instance is the KEBA listener instance
// instance is the KEBA listener instance
// This is needed since KEBAs ignore the sender port and always UDP back to port 7090
var Instance *Listener
var (
mu sync.Mutex
instance *Listener
)
// UDPMsg transports the KEBA response. Report is any of Report1,2,3
type UDPMsg struct {
@ -43,6 +46,18 @@ type Listener struct {
cache map[string]string
}
func Instance(log *util.Logger) (*Listener, error) {
mu.Lock()
defer mu.Unlock()
var err error
if instance == nil {
instance, err = New(log)
}
return instance, err
}
// New creates a UDP listener that clients can subscribe to
func New(log *util.Logger) (*Listener, error) {
laddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", Port))