|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Pymodbus Synchronous Client Example. |
| 3 | +
|
| 4 | +Modified to test long term connection. |
| 5 | +
|
| 6 | +""" |
| 7 | +import logging |
| 8 | +from time import sleep |
| 9 | + |
| 10 | +from pymodbus import pymodbus_apply_logging_config |
| 11 | + |
| 12 | +# --------------------------------------------------------------------------- # |
| 13 | +# import the various client implementations |
| 14 | +# --------------------------------------------------------------------------- # |
| 15 | +from pymodbus.client import ModbusTcpClient |
| 16 | +from pymodbus.exceptions import ModbusException |
| 17 | +from pymodbus.transaction import ModbusSocketFramer |
| 18 | + |
| 19 | + |
| 20 | +logging.basicConfig() |
| 21 | +_logger = logging.getLogger(__file__) |
| 22 | +_logger.setLevel(logging.DEBUG) |
| 23 | + |
| 24 | + |
| 25 | +def main(): |
| 26 | + """Run client setup.""" |
| 27 | + pymodbus_apply_logging_config(logging.DEBUG) |
| 28 | + _logger.info("### Client starting") |
| 29 | + client = ModbusTcpClient( |
| 30 | + "modbusServer.lan", |
| 31 | + port=502, |
| 32 | + # Common optional paramers: |
| 33 | + framer=ModbusSocketFramer, |
| 34 | + timeout=1, |
| 35 | + retry_on_empty=True, |
| 36 | + close_comm_on_error=True, |
| 37 | + ) |
| 38 | + client.connect() |
| 39 | + _logger.info("### Client connected") |
| 40 | + sleep(5) |
| 41 | + _logger.info("### Client starting") |
| 42 | + sleep_time = 2 |
| 43 | + for count in range(int(60 / sleep_time) * 60 * 3): # 3 hours |
| 44 | + _logger.info(f"Running loop {count}") |
| 45 | + solar_calls(client) |
| 46 | + sleep(sleep_time) # scan_interval |
| 47 | + client.close() |
| 48 | + _logger.info("### End of Program") |
| 49 | + |
| 50 | + |
| 51 | +def solar_calls(client): |
| 52 | + """Test connection works.""" |
| 53 | + for addr, count in ( |
| 54 | + (32008, 1), |
| 55 | + (32009, 1), |
| 56 | + (32010, 1), |
| 57 | + (32016, 1), |
| 58 | + (32017, 1), |
| 59 | + (32018, 1), |
| 60 | + (32019, 1), |
| 61 | + (32064, 2), |
| 62 | + (32078, 2), |
| 63 | + (32080, 2), |
| 64 | + (32114, 2), |
| 65 | + (37113, 2), |
| 66 | + (32078, 2), |
| 67 | + (32078, 2), |
| 68 | + ): |
| 69 | + lazy_error_count = 15 |
| 70 | + while lazy_error_count > 0: |
| 71 | + try: |
| 72 | + rr = client.read_coils(addr, count, slave=1) |
| 73 | + except ModbusException as exc: |
| 74 | + _logger.debug(f"TEST: exception lazy({lazy_error_count}) {exc}") |
| 75 | + lazy_error_count -= 1 |
| 76 | + continue |
| 77 | + if not hasattr(rr, "registers"): |
| 78 | + _logger.debug(f"TEST: no registers lazy({lazy_error_count})") |
| 79 | + lazy_error_count -= 1 |
| 80 | + continue |
| 81 | + break |
| 82 | + if not lazy_error_count: |
| 83 | + raise RuntimeError("HARD ERROR, more than 15 retries!") |
| 84 | + |
| 85 | + |
| 86 | +if __name__ == "__main__": |
| 87 | + main() # pragma: no cover |
0 commit comments