| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package modbus |
| 6 |
|
| 7 |
import ( |
| 8 |
"encoding/binary" |
| 9 |
"fmt" |
| 10 |
"io" |
| 11 |
"time" |
| 12 |
) |
| 13 |
|
| 14 |
const ( |
| 15 |
rtuMinSize = 4 |
| 16 |
rtuMaxSize = 256 |
| 17 |
|
| 18 |
rtuExceptionSize = 5 |
| 19 |
) |
| 20 |
|
| 21 |
|
| 22 |
type RTUClientHandler struct { |
| 23 |
rtuPackager |
| 24 |
rtuSerialTransporter |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
func NewRTUClientHandler(address string) *RTUClientHandler { |
| 29 |
handler := &RTUClientHandler{} |
| 30 |
handler.Address = address |
| 31 |
handler.Timeout = serialTimeout |
| 32 |
handler.IdleTimeout = serialIdleTimeout |
| 33 |
return handler |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
func RTUClient(address string) Client { |
| 38 |
handler := NewRTUClientHandler(address) |
| 39 |
return NewClient(handler) |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
type rtuPackager struct { |
| 44 |
SlaveId byte |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
func (mb *rtuPackager) Encode(pdu *ProtocolDataUnit) (adu []byte, err error) { |
| 53 |
length := len(pdu.Data) + 4 |
| 54 |
if length > rtuMaxSize { |
| 55 |
err = fmt.Errorf("modbus: length of data '%v' must not be bigger than '%v'", length, rtuMaxSize) |
| 56 |
return |
| 57 |
} |
| 58 |
adu = make([]byte, length) |
| 59 |
|
| 60 |
adu[0] = mb.SlaveId |
| 61 |
adu[1] = pdu.FunctionCode |
| 62 |
copy(adu[2:], pdu.Data) |
| 63 |
|
| 64 |
|
| 65 |
var crc crc |
| 66 |
crc.reset().pushBytes(adu[0 : length-2]) |
| 67 |
checksum := crc.value() |
| 68 |
|
| 69 |
adu[length-1] = byte(checksum >> 8) |
| 70 |
adu[length-2] = byte(checksum) |
| 71 |
return |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
func (mb *rtuPackager) Verify(aduRequest []byte, aduResponse []byte) (err error) { |
| 76 |
length := len(aduResponse) |
| 77 |
|
| 78 |
if length < rtuMinSize { |
| 79 |
err = fmt.Errorf("modbus: response length '%v' does not meet minimum '%v'", length, rtuMinSize) |
| 80 |
return |
| 81 |
} |
| 82 |
|
| 83 |
if aduResponse[0] != aduRequest[0] { |
| 84 |
err = fmt.Errorf("modbus: response slave id '%v' does not match request '%v'", aduResponse[0], aduRequest[0]) |
| 85 |
return |
| 86 |
} |
| 87 |
return |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
func (mb *rtuPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) { |
| 92 |
length := len(adu) |
| 93 |
|
| 94 |
var crc crc |
| 95 |
crc.reset().pushBytes(adu[0 : length-2]) |
| 96 |
checksum := uint16(adu[length-1])<<8 | uint16(adu[length-2]) |
| 97 |
if checksum != crc.value() { |
| 98 |
err = fmt.Errorf("modbus: response crc '%v' does not match expected '%v'", checksum, crc.value()) |
| 99 |
return |
| 100 |
} |
| 101 |
|
| 102 |
pdu = &ProtocolDataUnit{} |
| 103 |
pdu.FunctionCode = adu[1] |
| 104 |
pdu.Data = adu[2 : length-2] |
| 105 |
return |
| 106 |
} |
| 107 |
|
| 108 |
|
| 109 |
type rtuSerialTransporter struct { |
| 110 |
serialPort |
| 111 |
} |
| 112 |
|
| 113 |
func (mb *rtuSerialTransporter) Send(aduRequest []byte) (aduResponse []byte, err error) { |
| 114 |
|
| 115 |
if err = mb.serialPort.connect(); err != nil { |
| 116 |
return |
| 117 |
} |
| 118 |
|
| 119 |
mb.serialPort.lastActivity = time.Now() |
| 120 |
mb.serialPort.startCloseTimer() |
| 121 |
|
| 122 |
|
| 123 |
mb.serialPort.logf("modbus: sending % x\n", aduRequest) |
| 124 |
if _, err = mb.port.Write(aduRequest); err != nil { |
| 125 |
return |
| 126 |
} |
| 127 |
function := aduRequest[1] |
| 128 |
functionFail := aduRequest[1] & 0x80 |
| 129 |
bytesToRead := calculateResponseLength(aduRequest) |
| 130 |
time.Sleep(mb.calculateDelay(len(aduRequest) + bytesToRead)) |
| 131 |
|
| 132 |
var n int |
| 133 |
var n1 int |
| 134 |
var data [rtuMaxSize]byte |
| 135 |
|
| 136 |
|
| 137 |
n, err = io.ReadAtLeast(mb.port, data[:], rtuMinSize) |
| 138 |
if err != nil { |
| 139 |
return |
| 140 |
} |
| 141 |
|
| 142 |
if data[1] == function { |
| 143 |
|
| 144 |
if n < bytesToRead { |
| 145 |
if bytesToRead > rtuMinSize && bytesToRead <= rtuMaxSize { |
| 146 |
if bytesToRead > n { |
| 147 |
n1, err = io.ReadFull(mb.port, data[n:bytesToRead]) |
| 148 |
n += n1 |
| 149 |
} |
| 150 |
} |
| 151 |
} |
| 152 |
} else if data[1] == functionFail { |
| 153 |
|
| 154 |
if n < rtuExceptionSize { |
| 155 |
n1, err = io.ReadFull(mb.port, data[n:rtuExceptionSize]) |
| 156 |
} |
| 157 |
n += n1 |
| 158 |
} |
| 159 |
|
| 160 |
if err != nil { |
| 161 |
return |
| 162 |
} |
| 163 |
aduResponse = data[:n] |
| 164 |
mb.serialPort.logf("modbus: received % x\n", aduResponse) |
| 165 |
return |
| 166 |
} |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
func (mb *rtuSerialTransporter) calculateDelay(chars int) time.Duration { |
| 171 |
var characterDelay, frameDelay int |
| 172 |
|
| 173 |
if mb.BaudRate <= 0 || mb.BaudRate > 19200 { |
| 174 |
characterDelay = 750 |
| 175 |
frameDelay = 1750 |
| 176 |
} else { |
| 177 |
characterDelay = 15000000 / mb.BaudRate |
| 178 |
frameDelay = 35000000 / mb.BaudRate |
| 179 |
} |
| 180 |
return time.Duration(characterDelay*chars+frameDelay) * time.Microsecond |
| 181 |
} |
| 182 |
|
| 183 |
func calculateResponseLength(adu []byte) int { |
| 184 |
length := rtuMinSize |
| 185 |
switch adu[1] { |
| 186 |
case FuncCodeReadDiscreteInputs, |
| 187 |
FuncCodeReadCoils: |
| 188 |
count := int(binary.BigEndian.Uint16(adu[4:])) |
| 189 |
length += 1 + count/8 |
| 190 |
if count%8 != 0 { |
| 191 |
length++ |
| 192 |
} |
| 193 |
case FuncCodeReadInputRegisters, |
| 194 |
FuncCodeReadHoldingRegisters, |
| 195 |
FuncCodeReadWriteMultipleRegisters: |
| 196 |
count := int(binary.BigEndian.Uint16(adu[4:])) |
| 197 |
length += 1 + count*2 |
| 198 |
case FuncCodeWriteSingleCoil, |
| 199 |
FuncCodeWriteMultipleCoils, |
| 200 |
FuncCodeWriteSingleRegister, |
| 201 |
FuncCodeWriteMultipleRegisters: |
| 202 |
length += 4 |
| 203 |
case FuncCodeMaskWriteRegister: |
| 204 |
length += 6 |
| 205 |
case FuncCodeReadFIFOQueue: |
| 206 |
|
| 207 |
default: |
| 208 |
} |
| 209 |
return length |
| 210 |
} |