//安装Modbus 相关的库
pip install pyserial
pip install pymodbus
定义基础参数
# 配置串口参数
serial_port = '/dev/ttyUSB0' #'COM4' # 串口号,根据实际情况修改
baudrate = 9600 # 波特率
parity = 'N' # 校验位,可选值有 'N', 'E', 'O'
stopbits = 1 # 停止位
bytesize = 8 # 数据位
timeout = 1 # 超时时间,单位为秒
client: ModbusClient
isConnect: bool = False # 标识是否连接
address: int = 1 # 从站地址
write_lock = None # 读写锁
创建串口链接
def Start(self) -> BaseResult:
"""连接串口"""
# 创建Modbus客户端
self.client = ModbusClient(framer=FramerType.RTU, port=self.serial_port, baudrate=self.baudrate,
parity=self.parity, stopbits=self.stopbits, bytesize=self.bytesize, timeout=self.timeout)
# 连接到设备
if self.client.connect():
self.isConnect = True
return BaseResult.Success()
else:
self.isConnect = False
return BaseResult.Failure()
读写示例: 线圈及寄存器的读写都有封装的方法,方便直接的调用
def Read_WriteProtect(self) -> int:
"""
读取写保护状态
------------
读/写,0打开写保护1:关闭写保护
"""
try:
if (self.isConnect):
with self.write_lock:
res = self.client.read_holding_registers(23, 1, self.address)
pass
return res.registers[0]
else:
return -1
except Exception as ex:
LogOperate.error("Read_WriteProtect", ex)
return -1
def Set_WriteProtect(self,state)->BaseResult:
"""
设置写保护状态
------------
state: 0打开写保护 1:关闭写保护
"""
try:
if (self.isConnect):
with self.write_lock:
res = self.client.write_register(23, state, self.address)
pass
return BaseResult.Success()
except Exception as ex:
LogOperate.error("Set_WriteProtect", ex)
return BaseResult.Failure()