pymodubs TCP 无链接报错: pymodbus.exceptions.ConnectionException: Modbus Error

报错内容

pymodbus.exceptions.ConnectionException: Modbus Error: [Connection] ModbusTcpClient 192.168.2.99:502: Connection unexpectedly closed 0.000 seconds into read of unbounded read bytes without response from slave before it closed connection

背景

  • 使用摄像头对下位机持续控制, 第一次发信后成功, 第二次就报错

解决办法

  • 每次发信后关闭链接

控制代码

python 复制代码
import time
from pymodbus.client import ModbusTcpClient


class WorkstationControl:
    def __init__(self, host, port):
        self.ip_address = host
        self.port = port
        self.client = ModbusTcpClient(host=host, port=port)
        self.delay_time = 2

    def is_connect(self):
        return self.client.connect()

    def start(self):
        self.client.write_register(address=0, value=1)
        # Wait for 2 seconds
        time.sleep(self.delay_time)
        self.client.write_register(address=1, value=0)
        self.client.close()

    def update_speed(self, speed):
        self.client.connect()
        self.client.write_register(address=1, value=speed)
        self.client.close()

    def stop(self):
        self.client.write_register(address=1, value=0)
        # Wait for 2 seconds
        time.sleep(self.delay_time)
        self.client.write_register(address=0, value=2)
        self.client.close()

    def close(self):
        """关闭与 Modbus 服务器的连接"""
        self.client.close()


# 示例用法
if __name__ == '__main__':
    workstation = WorkstationControl(host='192.168.2.99', port=502)
    if workstation.is_connect():
        workstation.start()
        workstation.update_speed(speed=2)
        time.sleep(5)
        workstation.update_speed(speed=3)
        time.sleep(5)
        workstation.stop()
    else:
        print('Failed to connect to the workstation')
相关推荐
捷米研发三部6 小时前
ProfiNet转Modbus TCP协议转换网关实现西门子PLC与工控机通讯在智能交通系统的应用案例
网络·网络协议
dreamtm1236 小时前
通俗理解 TCP 拥塞控制:像 “快递员看路况调速”,避免网络 “堵车”
网络·tcp/ip·php
Cult Of6 小时前
TCP 与 UDP 的区别
网络协议·tcp/ip·udp
2301_803554529 小时前
https
网络协议·http·https
倦王10 小时前
Linux看ip,改用户名字加权限,在单独用户下设置miniconda
linux·服务器·tcp/ip
ASKED_201911 小时前
常用 Linux 命令大全(文件、网络、时间、进程、数据库、工具全覆盖)
linux·网络·数据库
我还可以再学点12 小时前
八股文面试攻略四:网络篇
网络·面试·职场和发展
q***766612 小时前
显卡(Graphics Processing Unit,GPU)架构详细解读
大数据·网络·架构
网安小白的进阶之路12 小时前
B模块 安全通信网络 第一门课 园区网实现与安全-1
网络·安全