-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgomcprotocol.go
More file actions
326 lines (310 loc) · 8.09 KB
/
gomcprotocol.go
File metadata and controls
326 lines (310 loc) · 8.09 KB
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// Package gomcprotocol implements Mitsubishi MC Protocol clients for 3E and 4E frames
// over TCP and UDP transports.
package gomcprotocol
import (
"encoding/binary"
"fmt"
"net"
"strconv"
"strings"
"sync"
"time"
)
// Client3E is a 3E frame MC Protocol client (TCP or UDP).
// Safe for concurrent use; requests are serialized by an internal mutex.
type Client3E struct {
mu sync.Mutex
host string
port int
mode Mode
timeout time.Duration
timer uint16
isUDP bool
conn net.Conn
}
// New3EClient creates a new 3E frame client. Call Connect before use.
func New3EClient(host string, port int, mode Mode) (*Client3E, error) {
if mode != ModeBinary && mode != ModeASCII {
return nil, fmt.Errorf("mode must be ModeBinary or ModeASCII")
}
return &Client3E{
host: host,
port: port,
mode: mode,
timeout: 5 * time.Second,
timer: 0x0010,
}, nil
}
// New3EClientUDP creates a new 3E frame client using UDP transport.
// Call Connect before use.
func New3EClientUDP(host string, port int, mode Mode) (*Client3E, error) {
c, err := New3EClient(host, port, mode)
if err != nil {
return nil, err
}
c.isUDP = true
return c, nil
}
// Connect establishes the connection to the PLC (TCP or UDP).
func (c *Client3E) Connect() error {
proto := "tcp"
if c.isUDP {
proto = "udp"
}
c.mu.Lock()
timeout := c.timeout
c.mu.Unlock()
conn, err := net.DialTimeout(proto, fmt.Sprintf("%s:%d", c.host, c.port), timeout)
if err != nil {
return &MCProtocolConnectionError{msg: "connect: " + err.Error()}
}
c.mu.Lock()
c.conn = conn
c.mu.Unlock()
return nil
}
// sendBin sends a binary frame and returns the response.
// Acquires the mutex to serialize concurrent callers.
func (c *Client3E) sendBin(frame []byte) ([]byte, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return nil, connErr("not connected")
}
c.applyDeadline()
if c.isUDP {
return xferBinUDP(c.conn, frame)
}
return xferBin(c.conn, frame)
}
// sendAsc sends an ASCII frame and returns the response.
// Acquires the mutex to serialize concurrent callers.
func (c *Client3E) sendAsc(frame string) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return "", connErr("not connected")
}
c.applyDeadline()
if c.isUDP {
return xferAscUDP(c.conn, frame)
}
return xferAsc(c.conn, frame)
}
// SetTimeout sets the per-request I/O deadline and the connect timeout.
// A value of 0 or less disables both the per-request deadline and the
// connect timeout (Connect will block until the OS times out).
// Default is 5 seconds.
func (c *Client3E) SetTimeout(d time.Duration) {
c.mu.Lock()
c.timeout = d
c.mu.Unlock()
}
// applyDeadline sets or clears the connection deadline.
// Must be called with c.mu held.
func (c *Client3E) applyDeadline() {
if c.timeout > 0 {
c.conn.SetDeadline(time.Now().Add(c.timeout))
} else {
c.conn.SetDeadline(time.Time{})
}
}
// Close closes the connection.
func (c *Client3E) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn != nil {
err := c.conn.Close()
c.conn = nil
return err
}
return nil
}
func (c *Client3E) validate(device string, start, count int) (string, error) {
dev := strings.ToUpper(device)
if _, ok := binCode[dev]; !ok {
return "", fmt.Errorf("unsupported device %q", device)
}
if start < 0 {
return "", fmt.Errorf("start must be >= 0, got %d", start)
}
if count <= 0 {
return "", fmt.Errorf("count must be > 0, got %d", count)
}
return dev, nil
}
func (c *Client3E) binBody(dev string, start, count int) []byte {
b := make([]byte, 6)
copy(b, addrBin(dev, start))
binary.LittleEndian.PutUint16(b[4:], uint16(count))
return b
}
// ReadWords reads count word values from device starting at address start.
func (c *Client3E) ReadWords(device string, start, count int) ([]uint16, error) {
dev, err := c.validate(device, start, count)
if err != nil {
return nil, err
}
if c.mode == ModeBinary {
resp, err := c.sendBin(buildBin(c.timer, cmdRead, subcWord, c.binBody(dev, start, count)))
if err != nil {
return nil, err
}
raw, err := chkBin(resp)
if err != nil {
return nil, err
}
if len(raw) < count*2 {
return nil, connErr(fmt.Sprintf("short payload: expected %d bytes, got %d", count*2, len(raw)))
}
vals := make([]uint16, count)
for i := range vals {
vals[i] = binary.LittleEndian.Uint16(raw[i*2:])
}
return vals, nil
}
body := addrAsc(dev, start) + fmt.Sprintf("%04X", count)
resp, err := c.sendAsc(buildAsc(c.timer, cmdRead, subcWord, body))
if err != nil {
return nil, err
}
raw, err := chkAsc(resp)
if err != nil {
return nil, err
}
if len(raw) < count*4 {
return nil, connErr(fmt.Sprintf("short payload: expected %d chars, got %d", count*4, len(raw)))
}
vals := make([]uint16, count)
for i := range vals {
v, err := strconv.ParseUint(raw[i*4:(i+1)*4], 16, 16)
if err != nil {
return nil, connErr(fmt.Sprintf("invalid word at index %d: %v", i, err))
}
vals[i] = uint16(v)
}
return vals, nil
}
// WriteWords writes values to device starting at address start.
func (c *Client3E) WriteWords(device string, start int, values []uint16) error {
dev, err := c.validate(device, start, len(values))
if err != nil {
return err
}
if c.mode == ModeBinary {
wbuf := make([]byte, len(values)*2)
for i, v := range values {
binary.LittleEndian.PutUint16(wbuf[i*2:], v)
}
body := append(c.binBody(dev, start, len(values)), wbuf...)
resp, err := c.sendBin(buildBin(c.timer, cmdWrite, subcWord, body))
if err != nil {
return err
}
_, err = chkBin(resp)
return err
}
prefix := addrAsc(dev, start) + fmt.Sprintf("%04X", len(values))
var sb strings.Builder
sb.Grow(len(prefix) + len(values)*4)
sb.WriteString(prefix)
for _, v := range values {
sb.WriteString(fmt.Sprintf("%04X", v))
}
resp, err := c.sendAsc(buildAsc(c.timer, cmdWrite, subcWord, sb.String()))
if err != nil {
return err
}
_, err = chkAsc(resp)
return err
}
// ReadBits reads count bit values from device starting at address start.
func (c *Client3E) ReadBits(device string, start, count int) ([]bool, error) {
dev, err := c.validate(device, start, count)
if err != nil {
return nil, err
}
if c.mode == ModeBinary {
resp, err := c.sendBin(buildBin(c.timer, cmdRead, subcBit, c.binBody(dev, start, count)))
if err != nil {
return nil, err
}
raw, err := chkBin(resp)
if err != nil {
return nil, err
}
if expected := (count + 1) / 2; len(raw) < expected {
return nil, connErr(fmt.Sprintf("short payload: expected %d bytes, got %d", expected, len(raw)))
}
bits := make([]bool, count)
for i := range bits {
b := raw[i/2]
if i%2 == 0 {
bits[i] = (b>>4)&0x01 != 0
} else {
bits[i] = b&0x01 != 0
}
}
return bits, nil
}
body := addrAsc(dev, start) + fmt.Sprintf("%04X", count)
resp, err := c.sendAsc(buildAsc(c.timer, cmdRead, subcBit, body))
if err != nil {
return nil, err
}
raw, err := chkAsc(resp)
if err != nil {
return nil, err
}
if len(raw) < count {
return nil, connErr(fmt.Sprintf("short payload: expected %d chars, got %d", count, len(raw)))
}
bits := make([]bool, count)
for i := range bits {
bits[i] = raw[i] == '1'
}
return bits, nil
}
// WriteBits writes bit values to device starting at address start.
func (c *Client3E) WriteBits(device string, start int, values []bool) error {
dev, err := c.validate(device, start, len(values))
if err != nil {
return err
}
if c.mode == ModeBinary {
buf := make([]byte, (len(values)+1)/2)
for i, v := range values {
if v {
if i%2 == 0 {
buf[i/2] |= 0x10
} else {
buf[i/2] |= 0x01
}
}
}
body := append(c.binBody(dev, start, len(values)), buf...)
resp, err := c.sendBin(buildBin(c.timer, cmdWrite, subcBit, body))
if err != nil {
return err
}
_, err = chkBin(resp)
return err
}
prefix := addrAsc(dev, start) + fmt.Sprintf("%04X", len(values))
var sb strings.Builder
sb.Grow(len(prefix) + len(values))
sb.WriteString(prefix)
for _, v := range values {
if v {
sb.WriteByte('1')
} else {
sb.WriteByte('0')
}
}
resp, err := c.sendAsc(buildAsc(c.timer, cmdWrite, subcBit, sb.String()))
if err != nil {
return err
}
_, err = chkAsc(resp)
return err
}