Debian Codegraph @

tcpclient.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 "encoding/binary"
9 "fmt"
10 "io"
11 "log"
12 "net"
13 "sync"
14 "sync/atomic"
15 "time"
16 )
17
18 const (
19 tcpProtocolIdentifier uint16 = 0x0000
20
21 // Modbus Application Protocol
22 tcpHeaderSize = 7
23 tcpMaxLength = 260
24 // Default TCP timeout is not set
25 tcpTimeout = 10 * time.Second
26 tcpIdleTimeout = 60 * time.Second
27 )
28
29 // TCPClientHandler implements Packager and Transporter interface.
30 type TCPClientHandler struct {
31 tcpPackager
32 tcpTransporter
33 }
34
35 // NewTCPClientHandler allocates a new TCPClientHandler.
36 func NewTCPClientHandler(address string) *TCPClientHandler {
37 h := &TCPClientHandler{}
38 h.Address = address
39 h.Timeout = tcpTimeout
40 h.IdleTimeout = tcpIdleTimeout
41 return h
42 }
43
44 // TCPClient creates TCP client with default handler and given connect string.
45 func TCPClient(address string) Client {
46 handler := NewTCPClientHandler(address)
47 return NewClient(handler)
48 }
49
50 // tcpPackager implements Packager interface.
51 type tcpPackager struct {
52 // For synchronization between messages of server & client
53 transactionId uint32
54 // Broadcast address is 0
55 SlaveId byte
56 }
57
58 // Encode adds modbus application protocol header:
59 // Transaction identifier: 2 bytes
60 // Protocol identifier: 2 bytes
61 // Length: 2 bytes
62 // Unit identifier: 1 byte
63 // Function code: 1 byte
64 // Data: n bytes
65 func (mb *tcpPackager) Encode(pdu *ProtocolDataUnit) (adu []byte, err error) {
66 adu = make([]byte, tcpHeaderSize+1+len(pdu.Data))
67
68 // Transaction identifier
69 transactionId := atomic.AddUint32(&mb.transactionId, 1)
70 binary.BigEndian.PutUint16(adu, uint16(transactionId))
71 // Protocol identifier
72 binary.BigEndian.PutUint16(adu[2:], tcpProtocolIdentifier)
73 // Length = sizeof(SlaveId) + sizeof(FunctionCode) + Data
74 length := uint16(1 + 1 + len(pdu.Data))
75 binary.BigEndian.PutUint16(adu[4:], length)
76 // Unit identifier
77 adu[6] = mb.SlaveId
78
79 // PDU
80 adu[tcpHeaderSize] = pdu.FunctionCode
81 copy(adu[tcpHeaderSize+1:], pdu.Data)
82 return
83 }
84
85 // Verify confirms transaction, protocol and unit id.
86 func (mb *tcpPackager) Verify(aduRequest []byte, aduResponse []byte) (err error) {
87 // Transaction id
88 responseVal := binary.BigEndian.Uint16(aduResponse)
89 requestVal := binary.BigEndian.Uint16(aduRequest)
90 if responseVal != requestVal {
91 err = fmt.Errorf("modbus: response transaction id '%v' does not match request '%v'", responseVal, requestVal)
92 return
93 }
94 // Protocol id
95 responseVal = binary.BigEndian.Uint16(aduResponse[2:])
96 requestVal = binary.BigEndian.Uint16(aduRequest[2:])
97 if responseVal != requestVal {
98 err = fmt.Errorf("modbus: response protocol id '%v' does not match request '%v'", responseVal, requestVal)
99 return
100 }
101 // Unit id (1 byte)
102 if aduResponse[6] != aduRequest[6] {
103 err = fmt.Errorf("modbus: response unit id '%v' does not match request '%v'", aduResponse[6], aduRequest[6])
104 return
105 }
106 return
107 }
108
109 // Decode extracts PDU from TCP frame:
110 // Transaction identifier: 2 bytes
111 // Protocol identifier: 2 bytes
112 // Length: 2 bytes
113 // Unit identifier: 1 byte
114 func (mb *tcpPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) {
115 // Read length value in the header
116 length := binary.BigEndian.Uint16(adu[4:])
117 pduLength := len(adu) - tcpHeaderSize
118 if pduLength <= 0 || pduLength != int(length-1) {
119 err = fmt.Errorf("modbus: length in response '%v' does not match pdu data length '%v'", length-1, pduLength)
120 return
121 }
122 pdu = &ProtocolDataUnit{}
123 // The first byte after header is function code
124 pdu.FunctionCode = adu[tcpHeaderSize]
125 pdu.Data = adu[tcpHeaderSize+1:]
126 return
127 }
128
129 // tcpTransporter implements Transporter interface.
130 type tcpTransporter struct {
131 // Connect string
132 Address string
133 // Connect & Read timeout
134 Timeout time.Duration
135 // Idle timeout to close the connection
136 IdleTimeout time.Duration
137 // Transmission logger
138 Logger *log.Logger
139
140 // TCP connection
141 mu sync.Mutex
142 conn net.Conn
143 closeTimer *time.Timer
144 lastActivity time.Time
145 }
146
147 // Send sends data to server and ensures response length is greater than header length.
148 func (mb *tcpTransporter) Send(aduRequest []byte) (aduResponse []byte, err error) {
149 mb.mu.Lock()
150 defer mb.mu.Unlock()
151
152 // Establish a new connection if not connected
153 if err = mb.connect(); err != nil {
154 return
155 }
156 // Set timer to close when idle
157 mb.lastActivity = time.Now()
158 mb.startCloseTimer()
159 // Set write and read timeout
160 var timeout time.Time
161 if mb.Timeout > 0 {
162 timeout = mb.lastActivity.Add(mb.Timeout)
163 }
164 if err = mb.conn.SetDeadline(timeout); err != nil {
165 return
166 }
167 // Send data
168 mb.logf("modbus: sending % x", aduRequest)
169 if _, err = mb.conn.Write(aduRequest); err != nil {
170 return
171 }
172 // Read header first
173 var data [tcpMaxLength]byte
174 if _, err = io.ReadFull(mb.conn, data[:tcpHeaderSize]); err != nil {
175 return
176 }
177 // Read length, ignore transaction & protocol id (4 bytes)
178 length := int(binary.BigEndian.Uint16(data[4:]))
179 if length <= 0 {
180 mb.flush(data[:])
181 err = fmt.Errorf("modbus: length in response header '%v' must not be zero", length)
182 return
183 }
184 if length > (tcpMaxLength - (tcpHeaderSize - 1)) {
185 mb.flush(data[:])
186 err = fmt.Errorf("modbus: length in response header '%v' must not greater than '%v'", length, tcpMaxLength-tcpHeaderSize+1)
187 return
188 }
189 // Skip unit id
190 length += tcpHeaderSize - 1
191 if _, err = io.ReadFull(mb.conn, data[tcpHeaderSize:length]); err != nil {
192 return
193 }
194 aduResponse = data[:length]
195 mb.logf("modbus: received % x\n", aduResponse)
196 return
197 }
198
199 // Connect establishes a new connection to the address in Address.
200 // Connect and Close are exported so that multiple requests can be done with one session
201 func (mb *tcpTransporter) Connect() error {
202 mb.mu.Lock()
203 defer mb.mu.Unlock()
204
205 return mb.connect()
206 }
207
208 func (mb *tcpTransporter) connect() error {
209 if mb.conn == nil {
210 dialer := net.Dialer{Timeout: mb.Timeout}
211 conn, err := dialer.Dial("tcp", mb.Address)
212 if err != nil {
213 return err
214 }
215 mb.conn = conn
216 }
217 return nil
218 }
219
220 func (mb *tcpTransporter) startCloseTimer() {
221 if mb.IdleTimeout <= 0 {
222 return
223 }
224 if mb.closeTimer == nil {
225 mb.closeTimer = time.AfterFunc(mb.IdleTimeout, mb.closeIdle)
226 } else {
227 mb.closeTimer.Reset(mb.IdleTimeout)
228 }
229 }
230
231 // Close closes current connection.
232 func (mb *tcpTransporter) Close() error {
233 mb.mu.Lock()
234 defer mb.mu.Unlock()
235
236 return mb.close()
237 }
238
239 // flush flushes pending data in the connection,
240 // returns io.EOF if connection is closed.
241 func (mb *tcpTransporter) flush(b []byte) (err error) {
242 if err = mb.conn.SetReadDeadline(time.Now()); err != nil {
243 return
244 }
245 // Timeout setting will be reset when reading
246 if _, err = mb.conn.Read(b); err != nil {
247 // Ignore timeout error
248 if netError, ok := err.(net.Error); ok && netError.Timeout() {
249 err = nil
250 }
251 }
252 return
253 }
254
255 func (mb *tcpTransporter) logf(format string, v ...interface{}) {
256 if mb.Logger != nil {
257 mb.Logger.Printf(format, v...)
258 }
259 }
260
261 // closeLocked closes current connection. Caller must hold the mutex before calling this method.
262 func (mb *tcpTransporter) close() (err error) {
263 if mb.conn != nil {
264 err = mb.conn.Close()
265 mb.conn = nil
266 }
267 return
268 }
269
270 // closeIdle closes the connection if last activity is passed behind IdleTimeout.
271 func (mb *tcpTransporter) closeIdle() {
272 mb.mu.Lock()
273 defer mb.mu.Unlock()
274
275 if mb.IdleTimeout <= 0 {
276 return
277 }
278 idle := time.Now().Sub(mb.lastActivity)
279 if idle >= mb.IdleTimeout {
280 mb.logf("modbus: closing connection due to idle timeout: %v", idle)
281 mb.close()
282 }
283 }