| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 22 |
tcpHeaderSize = 7 |
| 23 |
tcpMaxLength = 260 |
| 24 |
|
| 25 |
tcpTimeout = 10 * time.Second |
| 26 |
tcpIdleTimeout = 60 * time.Second |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
type TCPClientHandler struct { |
| 31 |
tcpPackager |
| 32 |
tcpTransporter |
| 33 |
} |
| 34 |
|
| 35 |
|
| 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 |
|
| 45 |
func TCPClient(address string) Client { |
| 46 |
handler := NewTCPClientHandler(address) |
| 47 |
return NewClient(handler) |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
type tcpPackager struct { |
| 52 |
|
| 53 |
transactionId uint32 |
| 54 |
|
| 55 |
SlaveId byte |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
func (mb *tcpPackager) Encode(pdu *ProtocolDataUnit) (adu []byte, err error) { |
| 66 |
adu = make([]byte, tcpHeaderSize+1+len(pdu.Data)) |
| 67 |
|
| 68 |
|
| 69 |
transactionId := atomic.AddUint32(&mb.transactionId, 1) |
| 70 |
binary.BigEndian.PutUint16(adu, uint16(transactionId)) |
| 71 |
|
| 72 |
binary.BigEndian.PutUint16(adu[2:], tcpProtocolIdentifier) |
| 73 |
|
| 74 |
length := uint16(1 + 1 + len(pdu.Data)) |
| 75 |
binary.BigEndian.PutUint16(adu[4:], length) |
| 76 |
|
| 77 |
adu[6] = mb.SlaveId |
| 78 |
|
| 79 |
|
| 80 |
adu[tcpHeaderSize] = pdu.FunctionCode |
| 81 |
copy(adu[tcpHeaderSize+1:], pdu.Data) |
| 82 |
return |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
func (mb *tcpPackager) Verify(aduRequest []byte, aduResponse []byte) (err error) { |
| 87 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
func (mb *tcpPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) { |
| 115 |
|
| 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 |
|
| 124 |
pdu.FunctionCode = adu[tcpHeaderSize] |
| 125 |
pdu.Data = adu[tcpHeaderSize+1:] |
| 126 |
return |
| 127 |
} |
| 128 |
|
| 129 |
|
| 130 |
type tcpTransporter struct { |
| 131 |
|
| 132 |
Address string |
| 133 |
|
| 134 |
Timeout time.Duration |
| 135 |
|
| 136 |
IdleTimeout time.Duration |
| 137 |
|
| 138 |
Logger *log.Logger |
| 139 |
|
| 140 |
|
| 141 |
mu sync.Mutex |
| 142 |
conn net.Conn |
| 143 |
closeTimer *time.Timer |
| 144 |
lastActivity time.Time |
| 145 |
} |
| 146 |
|
| 147 |
|
| 148 |
func (mb *tcpTransporter) Send(aduRequest []byte) (aduResponse []byte, err error) { |
| 149 |
mb.mu.Lock() |
| 150 |
defer mb.mu.Unlock() |
| 151 |
|
| 152 |
|
| 153 |
if err = mb.connect(); err != nil { |
| 154 |
return |
| 155 |
} |
| 156 |
|
| 157 |
mb.lastActivity = time.Now() |
| 158 |
mb.startCloseTimer() |
| 159 |
|
| 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 |
|
| 168 |
mb.logf("modbus: sending % x", aduRequest) |
| 169 |
if _, err = mb.conn.Write(aduRequest); err != nil { |
| 170 |
return |
| 171 |
} |
| 172 |
|
| 173 |
var data [tcpMaxLength]byte |
| 174 |
if _, err = io.ReadFull(mb.conn, data[:tcpHeaderSize]); err != nil { |
| 175 |
return |
| 176 |
} |
| 177 |
|
| 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 |
|
| 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 |
|
| 200 |
|
| 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 |
|
| 232 |
func (mb *tcpTransporter) Close() error { |
| 233 |
mb.mu.Lock() |
| 234 |
defer mb.mu.Unlock() |
| 235 |
|
| 236 |
return mb.close() |
| 237 |
} |
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
func (mb *tcpTransporter) flush(b []byte) (err error) { |
| 242 |
if err = mb.conn.SetReadDeadline(time.Now()); err != nil { |
| 243 |
return |
| 244 |
} |
| 245 |
|
| 246 |
if _, err = mb.conn.Read(b); err != nil { |
| 247 |
|
| 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 |
|
| 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 |
|
| 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 |
} |