This repository has been archived by the owner on Mar 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
serial.go
71 lines (60 loc) · 1.32 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
package modbus
import (
"io"
"sync"
"time"
"github.com/goburrow/serial"
)
// SerialDefaultTimeout Serial Default timeout
const SerialDefaultTimeout = 1 * time.Second
// serialPort has configuration and I/O controller.
type serialPort struct {
// Serial port configuration.
serial.Config
mu sync.Mutex
port io.ReadWriteCloser
}
// Connect try to connect the remote server
func (sf *serialPort) Connect() (err error) {
sf.mu.Lock()
err = sf.connect()
sf.mu.Unlock()
return
}
// Caller must hold the mutex before calling this method.
func (sf *serialPort) connect() error {
if sf.port == nil {
port, err := serial.Open(&sf.Config)
if err != nil {
return err
}
sf.port = port
}
return nil
}
// IsConnected returns a bool signifying whether the client is connected or not.
func (sf *serialPort) IsConnected() (b bool) {
sf.mu.Lock()
b = sf.port != nil
sf.mu.Unlock()
return b
}
// setSerialConfig set serial config
func (sf *serialPort) setSerialConfig(config serial.Config) {
sf.Config = config
}
func (sf *serialPort) setTCPTimeout(time.Duration) {}
func (sf *serialPort) close() (err error) {
if sf.port != nil {
err = sf.port.Close()
sf.port = nil
}
return err
}
// Close close current connection.
func (sf *serialPort) Close() (err error) {
sf.mu.Lock()
err = sf.close()
sf.mu.Unlock()
return
}