Skip to content

Commit 03811a9

Browse files
committed
modify serial read loop to handle port disconnection
if the port is open and gets detached Read() doesn't return error; however, the function returns really fast so we can catch that event and signal a portClose Former-commit-id: c4d4dc3430c14e97e1e27dca388a4344c5f6d8dc [formerly 0f2312236fa5ef9bacd583aa5ceb7c1c70f35604] Former-commit-id: adf44041c3d77c15a073e58c5cad214d422564f4
1 parent 8adabc0 commit 03811a9

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

serialport.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"io"
99
"log"
1010
"strconv"
11+
"time"
1112
)
1213

1314
type SerialConfig struct {
@@ -92,6 +93,8 @@ func (p *serport) reader() {
9293

9394
//var buf bytes.Buffer
9495
ch := make([]byte, 1024)
96+
timeCheckOpen := time.Now()
97+
9598
for {
9699

97100
n, err := p.portIo.Read(ch)
@@ -156,7 +159,7 @@ func (p *serport) reader() {
156159
// close and the OS doesn't clear out that buffer on a new
157160
// connect. This means we'll only catch EOF's when there are
158161
// other characters with it, but that seems to work ok
159-
if len(ch) == 0 {
162+
if n <= 0 {
160163
if err == io.EOF || err == io.ErrUnexpectedEOF {
161164
// hit end of file
162165
log.Println("Hit end of file on serial port")
@@ -171,6 +174,17 @@ func (p *serport) reader() {
171174
h.broadcastSys <- []byte("{\"Cmd\":\"OpenFail\",\"Desc\":\"Got error reading on port. " + err.Error() + "\",\"Port\":\"" + p.portConf.Name + "\",\"Baud\":" + strconv.Itoa(p.portConf.Baud) + "}")
172175
break
173176
}
177+
178+
// Keep track of time difference between two consecutive read with n == 0 and err == nil
179+
// we get here if the port has been disconnected while open (cpu usage will jump to 100%)
180+
// let's close the port only if the events are extremely fast (<1ms)
181+
if err == nil {
182+
diff := time.Since(timeCheckOpen)
183+
if diff.Nanoseconds() < 1000000 {
184+
p.isClosing = true
185+
}
186+
timeCheckOpen = time.Now()
187+
}
174188
}
175189
}
176190
p.portIo.Close()

0 commit comments

Comments
 (0)