Skip to content

Commit

Permalink
Fix RTU data race
Browse files Browse the repository at this point in the history
  • Loading branch information
NSMak authored and tbrandon committed Dec 10, 2021
1 parent a1f8ae9 commit 06d83ca
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
9 changes: 9 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package mbserver
import (
"io"
"net"
"sync"

"github.com/goburrow/serial"
)
Expand All @@ -14,6 +15,8 @@ type Server struct {
Debug bool
listeners []net.Listener
ports []serial.Port
portsWG sync.WaitGroup
portsCloseChan chan struct{}
requestChan chan *Request
function [256](func(*Server, Framer) ([]byte, *Exception))
DiscreteInputs []byte
Expand Down Expand Up @@ -49,6 +52,8 @@ func NewServer() *Server {
s.function[16] = WriteHoldingRegisters

s.requestChan = make(chan *Request)
s.portsCloseChan = make(chan struct{})

go s.handler()

return s
Expand Down Expand Up @@ -94,6 +99,10 @@ func (s *Server) Close() {
for _, listen := range s.listeners {
listen.Close()
}

close(s.portsCloseChan)
s.portsWG.Wait()

for _, port := range s.ports {
port.Close()
}
Expand Down
14 changes: 13 additions & 1 deletion servertu.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,25 @@ func (s *Server) ListenRTU(serialConfig *serial.Config) (err error) {
log.Fatalf("failed to open %s: %v\n", serialConfig.Address, err)
}
s.ports = append(s.ports, port)
go s.acceptSerialRequests(port)

s.portsWG.Add(1)
go func() {
defer s.portsWG.Done()
s.acceptSerialRequests(port)
}()

return err
}

func (s *Server) acceptSerialRequests(port serial.Port) {
SkipFrameError:
for {
select {
case <-s.portsCloseChan:
return
default:
}

buffer := make([]byte, 512)

bytesRead, err := port.Read(buffer)
Expand Down

0 comments on commit 06d83ca

Please sign in to comment.