Debian Codegraph @

modbus.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 /*
6 Package modbus provides a client for MODBUS TCP and RTU/ASCII.
7 */
8 package modbus
9
10 import (
11 "fmt"
12 )
13
14 const (
15 // Bit access
16 FuncCodeReadDiscreteInputs = 2
17 FuncCodeReadCoils = 1
18 FuncCodeWriteSingleCoil = 5
19 FuncCodeWriteMultipleCoils = 15
20
21 // 16-bit access
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 // ModbusError implements error interface.
44 type ModbusError struct {
45 FunctionCode byte
46 ExceptionCode byte
47 }
48
49 // Error converts known modbus exception code to error message.
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 // ProtocolDataUnit (PDU) is independent of underlying communication layers.
78 type ProtocolDataUnit struct {
79 FunctionCode byte
80 Data []byte
81 }
82
83 // Packager specifies the communication layer.
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 // Transporter specifies the transport layer.
91 type Transporter interface {
92 Send(aduRequest []byte) (aduResponse []byte, err error)
93 }