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')
相关推荐
Predestination王瀞潞20 分钟前
计科-计网4-数据链路层「整理」
网络·智能路由器
Xzq21050921 分钟前
部分重要协议或技术(DNS,ICMP,NAT,代理服务器)
运维·服务器·网络
小吴编程之路1 小时前
TCP/IP 协议:从分层原理到核心机制
网络·网络协议·tcp/ip
Wcbddd1 小时前
好靶场上新 2026年3月15日
网络
小杰帅气1 小时前
网络层IP理解
服务器·网络·tcp/ip
ht巷子2 小时前
asio::ip::tcp学习
网络·c++·tcp/ip
Insist7532 小时前
Kingbase 彻底卸载+重装全流程(保姆级)
网络·数据库
会编程的土豆2 小时前
【从零学javase 第六天】网络编程(+多线程)
开发语言·网络·php
简宸~2 小时前
FPGA(十一)DataMover 自编辑IP
网络协议·tcp/ip·fpga开发·开源
marsh02063 小时前
7 OpenClaw工作流程详解:从请求到响应的完整生命周期
网络·ai·编程·技术