A simple context manager to manage the connection to a TCP Modbus slave using pymodbus
.
Last active
April 13, 2022 03:55
-
-
Save wcheek/35599f2db14592129c358f3b35988d16 to your computer and use it in GitHub Desktop.
pymodbus context manager - manage TCP connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymodbus.client.sync import ModbusTcpClient | |
class ModbusConnection: | |
def __init__(self, host, port): | |
self.host = host | |
self.port = port | |
def __enter__(self): | |
self.client = ModbusTcpClient(host=self.host, port=self.port) | |
self.client.connect | |
return self.client | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if self.client: | |
self.client.close() | |
with ModbusConnection(host=..., port=...) as client: | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment