forked from grid-x/modbus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
serial.go
113 lines (94 loc) · 2.33 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
103
104
105
106
107
108
109
110
111
112
113
// 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 (
"fmt"
"io"
"sync"
"time"
"github.com/grid-x/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 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
}
// defaultSerialPort creates a serialPort with default configuration.
func defaultSerialPort(address string) serialPort {
return serialPort{
Config: serial.Config{
Address: address,
Timeout: serialTimeout,
},
IdleTimeout: serialIdleTimeout,
}
}
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 fmt.Errorf("could not open %s: %w", mb.Config.Address, 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
}
if idle := time.Since(mb.lastActivity); idle >= mb.IdleTimeout {
mb.logf("modbus: closing connection due to idle timeout: %v", idle)
mb.close()
}
}