| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package modbus |
| 9 |
|
| 10 |
import ( |
| 11 |
"fmt" |
| 12 |
) |
| 13 |
|
| 14 |
const ( |
| 15 |
|
| 16 |
FuncCodeReadDiscreteInputs = 2 |
| 17 |
FuncCodeReadCoils = 1 |
| 18 |
FuncCodeWriteSingleCoil = 5 |
| 19 |
FuncCodeWriteMultipleCoils = 15 |
| 20 |
|
| 21 |
|
| 22 |
FuncCodeReadInputRegisters = 4 |
| 23 |
FuncCodeReadHoldingRegisters = 3 |
| 24 |
FuncCodeWriteSingleRegister = 6 |
| 25 |
FuncCodeWriteMultipleRegisters = 16 |
| 26 |
FuncCodeReadWriteMultipleRegisters = 23 |
| 27 |
FuncCodeMaskWriteRegister = 22 |
| 28 |
FuncCodeReadFIFOQueue = 24 |
| 29 |
) |
| 30 |
|
| 31 |
const ( |
| 32 |
ExceptionCodeIllegalFunction = 1 |
| 33 |
ExceptionCodeIllegalDataAddress = 2 |
| 34 |
ExceptionCodeIllegalDataValue = 3 |
| 35 |
ExceptionCodeServerDeviceFailure = 4 |
| 36 |
ExceptionCodeAcknowledge = 5 |
| 37 |
ExceptionCodeServerDeviceBusy = 6 |
| 38 |
ExceptionCodeMemoryParityError = 8 |
| 39 |
ExceptionCodeGatewayPathUnavailable = 10 |
| 40 |
ExceptionCodeGatewayTargetDeviceFailedToRespond = 11 |
| 41 |
) |
| 42 |
|
| 43 |
|
| 44 |
type ModbusError struct { |
| 45 |
FunctionCode byte |
| 46 |
ExceptionCode byte |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
func (e *ModbusError) Error() string { |
| 51 |
var name string |
| 52 |
switch e.ExceptionCode { |
| 53 |
case ExceptionCodeIllegalFunction: |
| 54 |
name = "illegal function" |
| 55 |
case ExceptionCodeIllegalDataAddress: |
| 56 |
name = "illegal data address" |
| 57 |
case ExceptionCodeIllegalDataValue: |
| 58 |
name = "illegal data value" |
| 59 |
case ExceptionCodeServerDeviceFailure: |
| 60 |
name = "server device failure" |
| 61 |
case ExceptionCodeAcknowledge: |
| 62 |
name = "acknowledge" |
| 63 |
case ExceptionCodeServerDeviceBusy: |
| 64 |
name = "server device busy" |
| 65 |
case ExceptionCodeMemoryParityError: |
| 66 |
name = "memory parity error" |
| 67 |
case ExceptionCodeGatewayPathUnavailable: |
| 68 |
name = "gateway path unavailable" |
| 69 |
case ExceptionCodeGatewayTargetDeviceFailedToRespond: |
| 70 |
name = "gateway target device failed to respond" |
| 71 |
default: |
| 72 |
name = "unknown" |
| 73 |
} |
| 74 |
return fmt.Sprintf("modbus: exception '%v' (%s), function '%v'", e.ExceptionCode, name, e.FunctionCode) |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
type ProtocolDataUnit struct { |
| 79 |
FunctionCode byte |
| 80 |
Data []byte |
| 81 |
} |
| 82 |
|
| 83 |
|
| 84 |
type Packager interface { |
| 85 |
Encode(pdu *ProtocolDataUnit) (adu []byte, err error) |
| 86 |
Decode(adu []byte) (pdu *ProtocolDataUnit, err error) |
| 87 |
Verify(aduRequest []byte, aduResponse []byte) (err error) |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
type Transporter interface { |
| 92 |
Send(aduRequest []byte) (aduResponse []byte, err error) |
| 93 |
} |