forked from goburrow/modbus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.go
102 lines (85 loc) · 2.04 KB
/
serial.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Copyright 2014 Quoc-Viet Nguyen. All rights reserved.
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
package modbus
import (
"io"
"log"
"sync"
"time"
"github.com/goburrow/serial"
)
const (
// Default timeout
serialTimeout = 5 * time.Second
serialIdleTimeout = 60 * time.Second
)
// serialPort has configuration and I/O controller.
type serialPort struct {
// Serial port configuration.
serial.Config
Logger *log.Logger
IdleTimeout time.Duration
mu sync.Mutex
// port is platform-dependent data structure for serial port.
port io.ReadWriteCloser
lastActivity time.Time
closeTimer *time.Timer
}
func (mb *serialPort) Connect() (err error) {
mb.mu.Lock()
defer mb.mu.Unlock()
return mb.connect()
}
// connect connects to the serial port if it is not connected. Caller must hold the mutex.
func (mb *serialPort) connect() error {
if mb.port == nil {
port, err := serial.Open(&mb.Config)
if err != nil {
return err
}
mb.port = port
}
return nil
}
func (mb *serialPort) Close() (err error) {
mb.mu.Lock()
defer mb.mu.Unlock()
return mb.close()
}
// close closes the serial port if it is connected. Caller must hold the mutex.
func (mb *serialPort) close() (err error) {
if mb.port != nil {
err = mb.port.Close()
mb.port = nil
}
return
}
func (mb *serialPort) logf(format string, v ...interface{}) {
if mb.Logger != nil {
mb.Logger.Printf(format, v...)
}
}
func (mb *serialPort) startCloseTimer() {
if mb.IdleTimeout <= 0 {
return
}
if mb.closeTimer == nil {
mb.closeTimer = time.AfterFunc(mb.IdleTimeout, mb.closeIdle)
} else {
mb.closeTimer.Reset(mb.IdleTimeout)
}
}
// closeIdle closes the connection if last activity is passed behind IdleTimeout.
func (mb *serialPort) closeIdle() {
mb.mu.Lock()
defer mb.mu.Unlock()
if mb.IdleTimeout <= 0 {
return
}
idle := time.Now().Sub(mb.lastActivity)
if idle >= mb.IdleTimeout {
mb.logf("modbus: closing connection due to idle timeout: %v", idle)
mb.close()
}
}