17 connectTimeout = time.Second
18 writeTimeout = time.Second
19 readTimeout = 2 * time.Second
22 type tcpClient struct {
28 // NewTCPClient supplies Modbus TCP functions 01, 02, 03, 05, 15, and 16 without
29 // opening a connection. Connect has a one-second timeout. Writes have a
30 // one-second timeout, and reads have a two-second timeout. Earlier caller
31 // deadlines apply to each operation. The caller owns Close.
32 func NewTCPClient() Client {
36 func (c *tcpClient) Connect(ctx context.Context, address string, unit byte) error {
38 return fmt.Errorf("modbus connection is already open")
41 if unit == 0 || unit > 247 {
42 return fmt.Errorf("modbus unit must be from one through 247")
45 ctx, cancel := context.WithTimeout(ctx, connectTimeout)
48 conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", address)
50 return fmt.Errorf("connect Modbus transport: %w", err)
53 c.conn, c.unit = conn, unit
58 func (c *tcpClient) Close() error {
66 return fmt.Errorf("close Modbus transport: %w", err)
72 func (c *tcpClient) ReadInputs(ctx context.Context, count uint16) ([]bool, error) {
73 return c.readBits(ctx, 2, count)
76 func (c *tcpClient) ReadCoils(ctx context.Context, count uint16) ([]bool, error) {
77 return c.readBits(ctx, 1, count)
80 func (c *tcpClient) readBits(ctx context.Context, function byte, count uint16) ([]bool, error) {
81 if count == 0 || count > 2000 {
82 return nil, fmt.Errorf("bit read count must be from one through 2000")
85 data, err := c.exchange(ctx, function, words(0, count))
87 return nil, fmt.Errorf("read Modbus bits: %w", err)
90 size := (int(count) + 7) / 8
91 if len(data) != size+1 || int(data[0]) != size {
92 return nil, fmt.Errorf("modbus bit response has an invalid length")
95 values := make([]bool, count)
97 for index := range values {
98 values[index] = data[1+index/8]&(1<<uint(index%8)) != 0
104 func (c *tcpClient) ReadRegisters(ctx context.Context, address uint16, count uint16) ([]uint16, error) {
105 if count == 0 || count > 125 || uint32(address)+uint32(count) > 65536 {
106 return nil, fmt.Errorf("invalid register read range")
109 data, err := c.exchange(ctx, 3, words(address, count))
111 return nil, fmt.Errorf("read Modbus registers: %w", err)
114 if len(data) != int(count)*2+1 || int(data[0]) != int(count)*2 {
115 return nil, fmt.Errorf("modbus register response has an invalid length")
118 values := make([]uint16, count)
120 for index := range values {
121 values[index] = binary.BigEndian.Uint16(data[1+2*index:])
127 func (c *tcpClient) WriteCoil(ctx context.Context, address uint16, value bool) error {
134 return c.write(ctx, 5, words(address, encoded), words(address, encoded))
137 func (c *tcpClient) WriteCoils(ctx context.Context, address uint16, values []bool) error {
138 if len(values) == 0 || len(values) > 1968 || uint32(address)+uint32(len(values)) > 65536 {
139 return fmt.Errorf("invalid coil write range")
142 data := append(words(address, uint16(len(values))), byte((len(values)+7)/8))
143 data = append(data, make([]byte, (len(values)+7)/8)...)
145 for index, value := range values {
147 data[5+index/8] |= 1 << uint(index%8)
151 return c.write(ctx, 15, data, words(address, uint16(len(values))))
154 func (c *tcpClient) WriteRegister(ctx context.Context, address uint16, value uint16) error {
155 data := append(words(address, 1), 2)
156 data = append(data, words(value)...)
158 return c.write(ctx, 16, data, words(address, 1))
161 func (c *tcpClient) write(ctx context.Context, function byte, request []byte, expected []byte) error {
162 data, err := c.exchange(ctx, function, request)
164 return fmt.Errorf("write Modbus value: %w", err)
167 if !bytes.Equal(data, expected) {
168 return fmt.Errorf("modbus write acknowledgement differs from request")
174 func (c *tcpClient) exchange(ctx context.Context, function byte, data []byte) (response []byte, err error) {
175 if ctx.Err() != nil {
176 return nil, ctx.Err()
180 return nil, fmt.Errorf("modbus transport is closed")
184 request := append(words(c.transaction, 0, uint16(len(data)+2)), c.unit, function)
185 request = append(request, data...)
186 err = c.conn.SetWriteDeadline(operationDeadline(ctx, writeTimeout))
188 return nil, fmt.Errorf("set Modbus write deadline: %w", err)
191 interrupted := make(chan struct{})
195 deadlineMu sync.Mutex
198 stop := context.AfterFunc(ctx, func() {
200 defer deadlineMu.Unlock()
202 interruptErr = c.conn.SetDeadline(time.Now())
210 if err == nil || deadlineOnly(err) {
214 err = errors.Join(err, interruptErr, ctx.Err())
218 count, err := c.conn.Write(request)
220 return nil, fmt.Errorf("write Modbus request: %w", err)
223 if count != len(request) {
224 return nil, fmt.Errorf("write Modbus request: %w", io.ErrShortWrite)
229 if ctx.Err() != nil {
232 return nil, ctx.Err()
235 err = c.conn.SetReadDeadline(operationDeadline(ctx, readTimeout))
239 return nil, fmt.Errorf("set Modbus read deadline: %w", err)
244 _, err = io.ReadFull(c.conn, header[:])
246 return nil, fmt.Errorf("read Modbus header: %w", err)
249 length := binary.BigEndian.Uint16(header[4:6])
250 if binary.BigEndian.Uint16(header[:2]) != c.transaction || binary.BigEndian.Uint16(header[2:4]) != 0 || header[6] != c.unit || length < 2 || length > 254 {
251 return nil, fmt.Errorf("invalid Modbus response header")
254 body := make([]byte, length-1)
255 _, err = io.ReadFull(c.conn, body)
257 return nil, fmt.Errorf("read Modbus body: %w", err)
260 if body[0] == function|0x80 && len(body) == 2 {
261 return nil, fmt.Errorf("modbus exception %d", body[1])
264 if body[0] != function {
265 return nil, fmt.Errorf("invalid Modbus response function")
271 func words(values ...uint16) []byte {
272 data := make([]byte, 2*len(values))
274 for index, value := range values {
275 binary.BigEndian.PutUint16(data[2*index:], value)
281 func operationDeadline(ctx context.Context, timeout time.Duration) time.Time {
282 deadline := time.Now().Add(timeout)
283 caller, exists := ctx.Deadline()
284 if exists && caller.Before(deadline) {
291 func deadlineOnly(err error) bool {
292 joined, ok := err.(interface{ Unwrap() []error })
296 for _, cause := range joined.Unwrap() {
299 if !deadlineOnly(cause) {
308 wrapped, ok := err.(interface{ Unwrap() error })
310 return deadlineOnly(wrapped.Unwrap())
313 return errors.Is(err, os.ErrDeadlineExceeded)