Debian Codegraph @

serial.go

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