-
Notifications
You must be signed in to change notification settings - Fork 1
/
io.go
308 lines (269 loc) · 6.48 KB
/
io.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package iec62056
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"math/bits"
"net"
"strconv"
"strings"
"time"
)
// default i/o frame operations timeout
const timeout = time.Second * 5
type Conn interface {
// PrepareWrite configures frame writing operation. Call it once before frame sequential writes.
PrepareWrite() error
// PrepareRead configures frame reading operation. Call it once before frame sequential reads.
PrepareRead() error
// logs written frame
LogRequest()
// logs received frame
LogResponse()
// ReadByte reads a byte and appends it to frame's log message.
ReadByte() (byte, error)
// ReadBytes reads until the first occurrence of delim in the input and appends returned data to log buffer.
ReadBytes(delim byte) ([]byte, error)
// Write writes data from p into the socket.
Write(data []byte) (int, error)
// WriteByte writes a byte into the socket.
WriteByte(data byte) error
// Flush writes any buffered data to the underlying io.Writer.
Flush() error
//SetBaudRate sets new baudRate for a connection. Does nothing for tcp.
SetBaudRate(int) error
// Close closes the connection.
Close() error
}
// tcpConn is a network connection handle
type tcpConn struct {
// wrapped connection
rwc net.Conn
// operations wrapper
io io.ReadWriter
// i/o operations timeout
to time.Duration
// buffered reader handler.
r reader
//buffered writer handler
w writer
}
func (c *tcpConn) Close() error {
return c.rwc.Close()
}
func (c *tcpConn) PrepareRead() error {
c.r.reset(c.io)
if err := c.rwc.SetReadDeadline(time.Now().Add(c.to)); err != nil {
return err
}
return nil
}
func (c *tcpConn) PrepareWrite() error {
c.w.reset(c.io)
if err := c.rwc.SetWriteDeadline(time.Now().Add(c.to)); err != nil {
return err
}
return nil
}
func (c *tcpConn) LogResponse() {
c.r.log("response")
}
func (c *tcpConn) LogRequest() {
c.w.log("request")
}
func (c *tcpConn) ReadByte() (byte, error) {
return c.r.ReadByte()
}
func (c *tcpConn) ReadBytes(delim byte) ([]byte, error) {
return c.r.ReadBytes(delim)
}
func (c *tcpConn) Write(data []byte) (int, error) {
return c.w.Write(data)
}
func (c *tcpConn) WriteByte(data byte) error {
return c.w.WriteByte(data)
}
func (c *tcpConn) Flush() error {
return c.w.Flush()
}
func (c *tcpConn) SetBaudRate(int) error {
//nothing to do for tcp connection
return nil
}
// A TCPDialer contains options for connecting to a network.
type TCPDialer struct {
// Tcp socket connection timeout.
ConnectionTimeOut time.Duration
// I/O frame operations timeout.
RWTimeOut time.Duration
// Logger for received and sent frames.
ProtocolLogger *log.Logger
// If true then even partiy translation is applied on reads and writes.
SwParity bool
}
// DialTCP connects to the tcp socket on the named network.
// The socket has the form "host:port".
func DialTCP(socket string) (Conn, error) {
var d TCPDialer
return d.Dial(socket)
}
// Dial connects to the tcp socket on the named network.
// The socket has the form "host:port".
func (d *TCPDialer) Dial(socket string) (Conn, error) {
conn, err := net.DialTimeout("tcp", socket, d.ConnectionTimeOut)
if err != nil {
return nil, err
}
var to = d.RWTimeOut
if to == 0 {
to = timeout
}
return newConn(conn, d.ProtocolLogger, d.SwParity, to), nil
}
// creates connection.
func newConn(conn net.Conn, log *log.Logger, swParity bool, to time.Duration) *tcpConn {
var l = &logger{
l: log,
}
var io io.ReadWriter = conn
if swParity {
io = &parityWrapper{io: conn}
}
return &tcpConn{
conn,
io,
to,
reader{
l,
bufio.NewReader(io),
},
writer{
l,
bufio.NewWriter(io),
},
}
}
type parityWrapper struct {
io io.ReadWriter
}
func (w *parityWrapper) Read(p []byte) (int, error) {
n, err := w.io.Read(p)
if err != nil {
return n, err
}
for i := 0; i < n; i++ {
p[i] &= 0x7f
}
return n, err
}
func (w *parityWrapper) Write(p []byte) (int, error) {
p2 := make([]byte, len(p))
copy(p2, p)
for i, b := range p2 {
if bits.OnesCount8(b)&0x1 == 1 {
p2[i] |= 0x80
}
}
return w.io.Write(p2)
}
// Frame logger
type logger struct {
// buffer for partial reads writes.
buf bytes.Buffer
// logger
l *log.Logger
}
// log logs read or written frame. Contents are reset on prepareRead or prepareWrite methods call.
func (l *logger) log(prefix string) {
if l.l != nil {
l.l.Println(formatMsg(prefix, l.buf.Bytes()))
}
l.buf.Reset()
}
// Buffered reader that logs read bytes.
type reader struct {
*logger
*bufio.Reader
}
// reset resets collected frame's log message.
func (b *reader) reset(r io.Reader) {
b.logger.buf.Reset()
}
// io.Reader interface implementation.
// Read reads data into p and appends it to frame's log message.
func (b *reader) Read(p []byte) (int, error) {
n, err := b.Reader.Read(p)
if err == nil && b.l != nil {
_, err = b.logger.buf.Write(p)
}
return n, err
}
// bufio.Reader interface implementation.
func (b *reader) ReadByte() (byte, error) {
n, err := b.Reader.ReadByte()
if err == nil && b.l != nil {
_ = b.logger.buf.WriteByte(n)
}
return n, err
}
// bufio.Reader interface implementation.
func (b *reader) ReadBytes(delim byte) ([]byte, error) {
data, err := b.Reader.ReadBytes(delim)
if err == nil && b.l != nil {
_, err = b.logger.buf.Write(data)
}
return data, err
}
// Buffered writer that logs written bytes
type writer struct {
*logger
*bufio.Writer
}
// reset resets collected frame's log message.
func (b *writer) reset(w io.Writer) {
b.logger.buf.Reset()
}
// io.Writer implementation.
func (b *writer) Write(p []byte) (int, error) {
nn, err := b.Writer.Write(p)
if err == nil && b.l != nil {
_, err = b.logger.buf.Write(p)
}
return nn, err
}
// bufio.Writer implementation.
func (b *writer) WriteByte(p byte) error {
err := b.Writer.WriteByte(p)
if err == nil && b.l != nil {
_ = b.logger.buf.WriteByte(p)
}
return err
}
// formats frame log as two areas. On the left side frame bytes as hex bytes, on the right is a string representation.
func formatMsg(prefix string, data []byte) string {
var b1 strings.Builder
b1.WriteString(prefix)
b1.WriteRune('\n')
for i := 0; i < len(data); i += 16 {
end := i + 16
if end > len(data) {
end = len(data)
}
for _, b := range data[i:end] {
_, _ = fmt.Fprintf(&b1, "%02X ", b)
}
b1.WriteString(strings.Repeat(" ", 58-(3*(end-i))))
b1.WriteString(strings.Map(mapNotPrintable, string(data[i:end])))
b1.WriteRune('\n')
}
return b1.String()
}
// replaces non-printable runes with dots '.'
func mapNotPrintable(r rune) rune {
if strconv.IsPrint(r) {
return r
}
return '.'
}