16 connectTimeout = 2 * time.Second
17 writeTimeout = time.Second
18 readTimeout = 2 * time.Second
21 type tcpClient struct {
27 // NewTCPClient supplies Modbus TCP functions 01, 02, 03, 05, 15, and 16 without
28 // opening a connection. Connect has a two-second timeout. Writes have a
29 // one-second timeout, and reads have a two-second timeout. Earlier caller
30 // deadlines apply to each operation. The caller owns Close.
31 func NewTCPClient() Client {
35 func (c *tcpClient) Connect(ctx context.Context, address string, unit byte) error {
37 return fmt.Errorf("modbus connection is already open")
40 if unit == 0 || unit > 247 {
41 return fmt.Errorf("modbus unit must be from one through 247")
44 ctx, cancel := context.WithTimeout(ctx, connectTimeout)
47 conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", address)
49 return fmt.Errorf("connect Modbus transport: %w", err)
52 c.conn, c.unit = conn, unit
57 func (c *tcpClient) Close() error {
65 return fmt.Errorf("close Modbus transport: %w", err)
71 func (c *tcpClient) ReadInputs(ctx context.Context, count uint16) ([]bool, error) {
72 return c.readBits(ctx, 2, count)
75 func (c *tcpClient) ReadCoils(ctx context.Context, count uint16) ([]bool, error) {
76 return c.readBits(ctx, 1, count)
79 func (c *tcpClient) readBits(ctx context.Context, function byte, count uint16) ([]bool, error) {
80 if count == 0 || count > 2000 {
81 return nil, fmt.Errorf("bit read count must be from one through 2000")
84 data, err := c.exchange(ctx, function, words(0, count))
86 return nil, fmt.Errorf("read Modbus bits: %w", err)
89 size := (int(count) + 7) / 8
90 if len(data) != size+1 || int(data[0]) != size {
91 return nil, fmt.Errorf("modbus bit response has an invalid length")
94 values := make([]bool, count)
96 for index := range values {
97 values[index] = data[1+index/8]&(1<<uint(index%8)) != 0
103 func (c *tcpClient) ReadRegisters(ctx context.Context, address uint16, count uint16) ([]uint16, error) {
104 if count == 0 || count > 125 || uint32(address)+uint32(count) > 65536 {
105 return nil, fmt.Errorf("invalid register read range")
108 data, err := c.exchange(ctx, 3, words(address, count))
110 return nil, fmt.Errorf("read Modbus registers: %w", err)
113 if len(data) != int(count)*2+1 || int(data[0]) != int(count)*2 {
114 return nil, fmt.Errorf("modbus register response has an invalid length")
117 values := make([]uint16, count)
119 for index := range values {
120 values[index] = binary.BigEndian.Uint16(data[1+2*index:])
126 func (c *tcpClient) WriteCoil(ctx context.Context, address uint16, value bool) error {
133 return c.write(ctx, 5, words(address, encoded), words(address, encoded))
136 func (c *tcpClient) WriteCoils(ctx context.Context, address uint16, values []bool) error {
137 if len(values) == 0 || len(values) > 1968 || uint32(address)+uint32(len(values)) > 65536 {
138 return fmt.Errorf("invalid coil write range")
141 data := append(words(address, uint16(len(values))), byte((len(values)+7)/8))
142 data = append(data, make([]byte, (len(values)+7)/8)...)
144 for index, value := range values {
146 data[5+index/8] |= 1 << uint(index%8)
150 return c.write(ctx, 15, data, words(address, uint16(len(values))))
153 func (c *tcpClient) WriteRegister(ctx context.Context, address uint16, value uint16) error {
154 data := append(words(address, 1), 2)
155 data = append(data, words(value)...)
157 return c.write(ctx, 16, data, words(address, 1))
160 func (c *tcpClient) write(ctx context.Context, function byte, request []byte, expected []byte) error {
161 data, err := c.exchange(ctx, function, request)
163 return fmt.Errorf("write Modbus value: %w", err)
166 if !bytes.Equal(data, expected) {
167 return fmt.Errorf("modbus write acknowledgement differs from request")
173 func (c *tcpClient) exchange(ctx context.Context, function byte, data []byte) (response []byte, err error) {
174 if ctx.Err() != nil {
175 return nil, ctx.Err()
179 return nil, fmt.Errorf("modbus transport is closed")
183 request := append(words(c.transaction, 0, uint16(len(data)+2)), c.unit, function)
184 request = append(request, data...)
185 err = c.conn.SetWriteDeadline(operationDeadline(ctx, writeTimeout))
187 return nil, fmt.Errorf("set Modbus write deadline: %w", err)
190 err = c.conn.SetReadDeadline(operationDeadline(ctx, readTimeout))
192 return nil, fmt.Errorf("set Modbus read deadline: %w", err)
195 interrupted := make(chan struct{})
197 var interruptErr error
199 stop := context.AfterFunc(ctx, func() {
200 interruptErr = c.conn.SetDeadline(time.Now())
208 if err == nil || deadlineOnly(err) {
212 err = errors.Join(err, interruptErr, ctx.Err())
216 count, err := c.conn.Write(request)
218 return nil, fmt.Errorf("write Modbus request: %w", err)
221 if count != len(request) {
222 return nil, fmt.Errorf("write Modbus request: %w", io.ErrShortWrite)
227 _, err = io.ReadFull(c.conn, header[:])
229 return nil, fmt.Errorf("read Modbus header: %w", err)
232 length := binary.BigEndian.Uint16(header[4:6])
233 if binary.BigEndian.Uint16(header[:2]) != c.transaction || binary.BigEndian.Uint16(header[2:4]) != 0 || header[6] != c.unit || length < 2 || length > 254 {
234 return nil, fmt.Errorf("invalid Modbus response header")
237 body := make([]byte, length-1)
238 _, err = io.ReadFull(c.conn, body)
240 return nil, fmt.Errorf("read Modbus body: %w", err)
243 if body[0] == function|0x80 && len(body) == 2 {
244 return nil, fmt.Errorf("modbus exception %d", body[1])
247 if body[0] != function {
248 return nil, fmt.Errorf("invalid Modbus response function")
254 func words(values ...uint16) []byte {
255 data := make([]byte, 2*len(values))
257 for index, value := range values {
258 binary.BigEndian.PutUint16(data[2*index:], value)
264 func operationDeadline(ctx context.Context, timeout time.Duration) time.Time {
265 deadline := time.Now().Add(timeout)
266 caller, exists := ctx.Deadline()
267 if exists && caller.Before(deadline) {
274 func deadlineOnly(err error) bool {
275 joined, ok := err.(interface{ Unwrap() []error })
279 for _, cause := range joined.Unwrap() {
282 if !deadlineOnly(cause) {
291 wrapped, ok := err.(interface{ Unwrap() error })
293 return deadlineOnly(wrapped.Unwrap())
296 return errors.Is(err, os.ErrDeadlineExceeded)