Skip to content

Automatic reconnection with configurable retry/backoff #626

@gijzelaerr

Description

@gijzelaerr

Summary

Add automatic reconnection support so the client transparently recovers from connection drops without requiring manual intervention.

Background

In production environments, PLC connections can drop due to network issues, PLC restarts, or maintenance. Currently, users must implement their own reconnection logic. Built-in reconnection with configurable retry and backoff would make production deployments more robust.

What needs to be done

  • Implement reconnection logic that triggers on connection loss (socket errors, timeout)
  • Add configurable retry parameters: max retries, initial delay, backoff factor, max delay
  • Implement exponential backoff with optional jitter
  • Re-establish session state after reconnection (PDU size, connection type, etc.)
  • Add connection state callbacks (on_disconnect, on_reconnect, on_give_up)
  • Make reconnection opt-in (disabled by default to preserve backward compatibility)
  • Handle reconnection during in-flight operations (retry the operation or raise)
  • Add tests simulating connection drops
  • Add documentation

API Design Ideas

client = snap7.Client(
    auto_reconnect=True,
    max_retries=5,
    retry_delay=1.0,       # initial delay in seconds
    backoff_factor=2.0,    # exponential backoff multiplier
    max_delay=30.0,        # cap on delay between retries
)

# Optional callbacks
client.on_disconnect = lambda: logger.warning("Connection lost")
client.on_reconnect = lambda: logger.info("Reconnected")

client.connect("192.168.1.10", 0, 1)

# If connection drops during this read, client will automatically retry
data = client.db_read(1, 0, 4)

Notes

  • Must be backward compatible — default behavior should remain unchanged
  • Consider thread safety for reconnection in multi-threaded applications
  • Should work with both sync and future async clients

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions