-
Notifications
You must be signed in to change notification settings - Fork 27
/
ascii_over_tcp_client.go
82 lines (72 loc) · 2 KB
/
ascii_over_tcp_client.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
// Copyright 2018 xft. 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 (
"time"
)
// ASCIIOverTCPClientHandler implements Packager and Transporter interface.
type ASCIIOverTCPClientHandler struct {
asciiPackager
asciiTCPTransporter
}
// NewASCIIOverTCPClientHandler allocates and initializes a ASCIIOverTCPClientHandler.
func NewASCIIOverTCPClientHandler(address string) *ASCIIOverTCPClientHandler {
handler := &ASCIIOverTCPClientHandler{}
handler.Address = address
handler.Timeout = tcpTimeout
handler.IdleTimeout = tcpIdleTimeout
return handler
}
// ASCIIOverTCPClient creates ASCII over TCP client with default handler and given connect string.
func ASCIIOverTCPClient(address string) Client {
handler := NewASCIIOverTCPClientHandler(address)
return NewClient(handler)
}
// asciiTCPTransporter implements Transporter interface.
type asciiTCPTransporter struct {
tcpTransporter
}
func (mb *asciiTCPTransporter) Send(aduRequest []byte) (aduResponse []byte, err error) {
mb.mu.Lock()
defer mb.mu.Unlock()
// Make sure port is connected
if err = mb.connect(); err != nil {
return
}
// Start the timer to close when idle
mb.lastActivity = time.Now()
mb.startCloseTimer()
// Set write and read timeout
if mb.Timeout > 0 {
if err = mb.conn.SetDeadline(mb.lastActivity.Add(mb.Timeout)); err != nil {
return
}
}
// Send the request
mb.logf("modbus: send %q\n", aduRequest)
if _, err = mb.conn.Write(aduRequest); err != nil {
return
}
// Get the response
var n, length int
var data [asciiMaxSize]byte
for {
if n, err = mb.conn.Read(data[length:]); err != nil {
return
}
length += n
if length >= asciiMaxSize || n == 0 {
break
}
// Expect end of frame in the data received
if length > asciiMinSize {
if string(data[length-len(asciiEnd):length]) == asciiEnd {
break
}
}
}
aduResponse = data[:length]
mb.logf("modbus: recv %q\n", aduResponse)
return
}