import traceback import click from modbus_tk import modbus_tcp class ModbusConnection: ''' Modbus连接管理器 ''' def __init__(self, host: str, port: int) -> None: self.host = host self.port = port self.master = None def __enter__(self) -> modbus_tcp.TcpMaster: self.master = modbus_tcp.TcpMaster(self.host, self.port) self.master.set_timeout(5.0) return self.master def __exit__(self, exc_type, exc_value, _traceback) -> None: try: if self.master: self.master.close() if exc_type is not None: click.echo("发生异常:") click.echo(f"类型: {exc_type}") click.echo(f"值: {exc_value}") click.echo("调用栈:") traceback.print_tb(_traceback) except Exception as e : print('PLC通信异常:::',str(e))