我在下面的代码中从closeconnection()访问readholdingregisters()中的client.close()时遇到问题:
class EnergyMeter:
def __init__(self, model, gatewayipaddress, port ,deviceid):
self.model = model
self.gatewayipaddress = gatewayipaddress
self.port = port
self.deviceid = deviceid
def readholdingregisters(self, startingregister, numberofregisters):
from pymodbus3.client.sync import ModbusTcpClient as ModbusClient
client = ModbusClient(self.gatewayipaddress, port=self.port)
client.connect()
if #some code here:
#some other code here
return concatResult
else:
return otherResult
def closeconnection(self):
EnergyMeter.readholdingregisters().client.close()??????????????????
你能为我提供一个很好的解决方案吗?
答案 0 :(得分:0)
from pymodbus3.client.sync import ModbusTcpClient as ModbusClient
class EnergyMeter:
def __init__(self, model, gatewayipaddress, port ,deviceid):
self.model = model
self.gatewayipaddress = gatewayipaddress
self.port = port
self.deviceid = deviceid
self.client = ModbusClient(self.gatewayipaddress, port=self.port)
self.client.connect()
def readholdingregisters(self, startingregister, numberofregisters):
if #some code here:
#some other code here
return concatResult
else:
return otherResult
然后,要关闭,请致电energy_meter.client.close()
以查找要关闭的energy_meter
。
答案 1 :(得分:0)
通常的做法是,将客户端作为类的数据库。
self.client = ModbusClient(self.gatewayipaddress, port=self.port)
self.client.connect()
#some code here
def closeconnection(self):
self.readholdingregisters()
self.client.close()
但是,如果您想通过课程EnergyMeter.readholdingregisters()
然后它应声明为staticmethod
或classmethod
,此方法应返回客户端实例。 Link