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 小时前
Bluetooth® Mesh 网络:Friendship
网络·物联网
用户47949283569157 小时前
面试官:CNAME和A记录有什么区别?
网络协议
我要添砖java7 小时前
《JAVAEE》网络编程-什么是网络?
java·网络·java-ee
独行soc8 小时前
2025年渗透测试面试题总结-275(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
7ACE8 小时前
Wireshark TS | 关闭连接和超时重传
网络协议·tcp/ip·wireshark
中屹指纹浏览器10 小时前
指纹浏览器抗检测进阶:绕过深度风控的技术实践
服务器·网络·经验分享·笔记·媒体
wu_huashan10 小时前
环路造成的IP/MAC地址漂移说明
网络·yersinia攻击·ip地址漂移·mac地址漂移
txzz888811 小时前
网络应用netstart命令
网络·windows·计算机网络·microsoft
网安小白的进阶之路12 小时前
B模块 安全通信网络 第二门课 核心网路由技术-1-OSPF之特殊区域
网络·安全
JZZC213 小时前
33.PPP——CHAP认证
网络