Debian Codegraph @

asciiclient.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 "bytes"
9 "encoding/hex"
10 "fmt"
11 "time"
12 )
13
14 const (
15 asciiStart = ":"
16 asciiEnd = "\r\n"
17 asciiMinSize = 3
18 asciiMaxSize = 513
19
20 hexTable = "0123456789ABCDEF"
21 )
22
23 // ASCIIClientHandler implements Packager and Transporter interface.
24 type ASCIIClientHandler struct {
25 asciiPackager
26 asciiSerialTransporter
27 }
28
29 // NewASCIIClientHandler allocates and initializes a ASCIIClientHandler.
30 func NewASCIIClientHandler(address string) *ASCIIClientHandler {
31 handler := &ASCIIClientHandler{}
32 handler.Address = address
33 handler.Timeout = serialTimeout
34 handler.IdleTimeout = serialIdleTimeout
35 return handler
36 }
37
38 // ASCIIClient creates ASCII client with default handler and given connect string.
39 func ASCIIClient(address string) Client {
40 handler := NewASCIIClientHandler(address)
41 return NewClient(handler)
42 }
43
44 // asciiPackager implements Packager interface.
45 type asciiPackager struct {
46 SlaveId byte
47 }
48
49 // Encode encodes PDU in a ASCII frame:
50 // Start : 1 char
51 // Address : 2 chars
52 // Function : 2 chars
53 // Data : 0 up to 2x252 chars
54 // LRC : 2 chars
55 // End : 2 chars
56 func (mb *asciiPackager) Encode(pdu *ProtocolDataUnit) (adu []byte, err error) {
57 var buf bytes.Buffer
58
59 if _, err = buf.WriteString(asciiStart); err != nil {
60 return
61 }
62 if err = writeHex(&buf, []byte{mb.SlaveId, pdu.FunctionCode}); err != nil {
63 return
64 }
65 if err = writeHex(&buf, pdu.Data); err != nil {
66 return
67 }
68 // Exclude the beginning colon and terminating CRLF pair characters
69 var lrc lrc
70 lrc.reset()
71 lrc.pushByte(mb.SlaveId).pushByte(pdu.FunctionCode).pushBytes(pdu.Data)
72 if err = writeHex(&buf, []byte{lrc.value()}); err != nil {
73 return
74 }
75 if _, err = buf.WriteString(asciiEnd); err != nil {
76 return
77 }
78 adu = buf.Bytes()
79 return
80 }
81
82 // Verify verifies response length, frame boundary and slave id.
83 func (mb *asciiPackager) Verify(aduRequest []byte, aduResponse []byte) (err error) {
84 length := len(aduResponse)
85 // Minimum size (including address, function and LRC)
86 if length < asciiMinSize+6 {
87 err = fmt.Errorf("modbus: response length '%v' does not meet minimum '%v'", length, 9)
88 return
89 }
90 // Length excluding colon must be an even number
91 if length%2 != 1 {
92 err = fmt.Errorf("modbus: response length '%v' is not an even number", length-1)
93 return
94 }
95 // First char must be a colon
96 str := string(aduResponse[0:len(asciiStart)])
97 if str != asciiStart {
98 err = fmt.Errorf("modbus: response frame '%v'... is not started with '%v'", str, asciiStart)
99 return
100 }
101 // 2 last chars must be \r\n
102 str = string(aduResponse[len(aduResponse)-len(asciiEnd):])
103 if str != asciiEnd {
104 err = fmt.Errorf("modbus: response frame ...'%v' is not ended with '%v'", str, asciiEnd)
105 return
106 }
107 // Slave id
108 responseVal, err := readHex(aduResponse[1:])
109 if err != nil {
110 return
111 }
112 requestVal, err := readHex(aduRequest[1:])
113 if err != nil {
114 return
115 }
116 if responseVal != requestVal {
117 err = fmt.Errorf("modbus: response slave id '%v' does not match request '%v'", responseVal, requestVal)
118 return
119 }
120 return
121 }
122
123 // Decode extracts PDU from ASCII frame and verify LRC.
124 func (mb *asciiPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) {
125 pdu = &ProtocolDataUnit{}
126 // Slave address
127 address, err := readHex(adu[1:])
128 if err != nil {
129 return
130 }
131 // Function code
132 if pdu.FunctionCode, err = readHex(adu[3:]); err != nil {
133 return
134 }
135 // Data
136 dataEnd := len(adu) - 4
137 data := adu[5:dataEnd]
138 pdu.Data = make([]byte, hex.DecodedLen(len(data)))
139 if _, err = hex.Decode(pdu.Data, data); err != nil {
140 return
141 }
142 // LRC
143 lrcVal, err := readHex(adu[dataEnd:])
144 if err != nil {
145 return
146 }
147 // Calculate checksum
148 var lrc lrc
149 lrc.reset()
150 lrc.pushByte(address).pushByte(pdu.FunctionCode).pushBytes(pdu.Data)
151 if lrcVal != lrc.value() {
152 err = fmt.Errorf("modbus: response lrc '%v' does not match expected '%v'", lrcVal, lrc.value())
153 return
154 }
155 return
156 }
157
158 // asciiSerialTransporter implements Transporter interface.
159 type asciiSerialTransporter struct {
160 serialPort
161 }
162
163 func (mb *asciiSerialTransporter) Send(aduRequest []byte) (aduResponse []byte, err error) {
164 mb.serialPort.mu.Lock()
165 defer mb.serialPort.mu.Unlock()
166
167 // Make sure port is connected
168 if err = mb.serialPort.connect(); err != nil {
169 return
170 }
171 // Start the timer to close when idle
172 mb.serialPort.lastActivity = time.Now()
173 mb.serialPort.startCloseTimer()
174
175 // Send the request
176 mb.serialPort.logf("modbus: sending %q\n", aduRequest)
177 if _, err = mb.port.Write(aduRequest); err != nil {
178 return
179 }
180 // Get the response
181 var n int
182 var data [asciiMaxSize]byte
183 length := 0
184 for {
185 if n, err = mb.port.Read(data[length:]); err != nil {
186 return
187 }
188 length += n
189 if length >= asciiMaxSize || n == 0 {
190 break
191 }
192 // Expect end of frame in the data received
193 if length > asciiMinSize {
194 if string(data[length-len(asciiEnd):length]) == asciiEnd {
195 break
196 }
197 }
198 }
199 aduResponse = data[:length]
200 mb.serialPort.logf("modbus: received %q\n", aduResponse)
201 return
202 }
203
204 // writeHex encodes byte to string in hexadecimal, e.g. 0xA5 => "A5"
205 // (encoding/hex only supports lowercase string).
206 func writeHex(buf *bytes.Buffer, value []byte) (err error) {
207 var str [2]byte
208 for _, v := range value {
209 str[0] = hexTable[v>>4]
210 str[1] = hexTable[v&0x0F]
211
212 if _, err = buf.Write(str[:]); err != nil {
213 return
214 }
215 }
216 return
217 }
218
219 // readHex decodes hexa string to byte, e.g. "8C" => 0x8C.
220 func readHex(data []byte) (value byte, err error) {
221 var dst [1]byte
222 if _, err = hex.Decode(dst[:], data[0:2]); err != nil {
223 return
224 }
225 value = dst[0]
226 return
227 }