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')
相关推荐
秦奈1 天前
Unity学习复习随笔(12):网络开发基础
网络·笔记·学习·unity
大模型发展与战略研究中心1 天前
安全顶刊 | InstPro: 基于指令执行追踪和溯源的CPU漏洞利用攻击检测和调查
网络·安全
执行部之龙1 天前
HTTP常见面试题总结
网络·网络协议·http
tod1131 天前
Reactor反应堆模式
网络·网络协议·tcp/ip·reactor·多路转接·tcpdump
Codefengfeng1 天前
分辨压缩包的真加密与伪加密
linux·运维·网络
白太岁1 天前
通信:(3) 高并发网络通信:epoll + 边沿触发 + 非阻塞 IO + tcp
c语言·网络·c++·网络协议·tcp/ip
duration~1 天前
DHCP 协议详解
网络·网络协议·tcp/ip
代码改善世界2 天前
【C语言】线性表之顺序表、单链表、双向链表详解及实现
c语言·网络·链表
嵌入式×边缘AI:打怪升级日志2 天前
9.2.1 分析 Write File Record 功能(保姆级讲解)
java·开发语言·网络
天荒地老笑话么2 天前
Bridged 与虚拟机扫描:合规边界与自测范围说明
网络·网络安全