Skip to content

Commit

Permalink
Solution for issue omriharel#23 -- retry serial connections
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcus Wu committed Mar 28, 2021
1 parent ad2505a commit c437adf
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions pkg/deej/serial.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ type SliderMoveEvent struct {
}

var expectedLinePattern = regexp.MustCompile(`^\d{1,4}(\|\d{1,4})*\r\n$`)
var maxRetryDelay = 100 * time.Second

// NewSerialIO creates a SerialIO instance that uses the provided deej
// instance's connection info to establish communications with the arduino chip
Expand Down Expand Up @@ -96,7 +97,20 @@ func (sio *SerialIO) Start() error {
"minReadSize", minimumReadSize)

var err error
sio.conn, err = serial.Open(sio.connOptions)
delay := 1 * time.Second
for i := int64(1); ; i++ {
sio.conn, err = serial.Open(sio.connOptions)
if err == nil {
break
}
sio.logger.Warnw("Failed to open serial connection", "error", err)
time.Sleep(delay)
// Exponentially back off retries up to a max
if delay < maxRetryDelay {
delay = time.Duration(int64(delay) * i)
}
}

if err != nil {

// might need a user notification here, TBD
Expand All @@ -118,8 +132,13 @@ func (sio *SerialIO) Start() error {
select {
case <-sio.stopChannel:
sio.close(namedLogger)
case line := <-lineChannel:
case line, ok := <-lineChannel:
sio.handleLine(namedLogger, line)
if !ok {
sio.connected = false
sio.Start()
return
}
}
}
}()
Expand Down Expand Up @@ -211,6 +230,7 @@ func (sio *SerialIO) readLine(logger *zap.SugaredLogger, reader *bufio.Reader) c
}

// just ignore the line, the read loop will stop after this
close(ch)
return
}

Expand Down

0 comments on commit c437adf

Please sign in to comment.