]> git.giacomolli.uk - onehouse/blobdiff - driver/m31/tcp_client.go
Keep interrupted Modbus work a context stop
[onehouse] / driver / m31 / tcp_client.go
index 6484b101928a4c8a96f8d3bc66256c38d32acff0..972f6984e519180badad7959ada2e1ae16d0bebd 100644 (file)
@@ -8,6 +8,7 @@ import (
        "fmt"
        "io"
        "net"
+       "os"
        "time"
 )
 
@@ -204,6 +205,10 @@ func (c *tcpClient) exchange(ctx context.Context, function byte, data []byte) (r
                if !stop() {
                        <-interrupted
 
+                       if err == nil || deadlineOnly(err) {
+                               err = ctx.Err()
+                       }
+
                        err = errors.Join(err, interruptErr, ctx.Err())
                }
        }()
@@ -265,3 +270,28 @@ func operationDeadline(ctx context.Context, timeout time.Duration) time.Time {
 
        return deadline
 }
+
+func deadlineOnly(err error) bool {
+       joined, ok := err.(interface{ Unwrap() []error })
+       if ok {
+               found := false
+
+               for _, cause := range joined.Unwrap() {
+                       if cause != nil {
+                               found = true
+                               if !deadlineOnly(cause) {
+                                       return false
+                               }
+                       }
+               }
+
+               return found
+       }
+
+       wrapped, ok := err.(interface{ Unwrap() error })
+       if ok {
+               return deadlineOnly(wrapped.Unwrap())
+       }
+
+       return errors.Is(err, os.ErrDeadlineExceeded)
+}