Modbus 服务器与 umodbus

问题描述 投票:0回答:1

我正在使用 umodbus python 模块创建一个 Modbus 服务器。 两个客户端正在连接到服务器。一种是读取寄存器,另一种是每 5 秒写入相同的寄存器。现在的问题是两个客户端无法同时读写。 '''

我后来发现我需要在两个客户端的每次读写后关闭连接。但有时客户端之一无法连接并且连接标志显示 False。

如何在服务器端处理这种情况,使其运行稳定,并且第一个客户端可以写入寄存器,而其他客户端可以轻松读取寄存器?

from socketserver import TCPServer
from collections import defaultdict

from umodbus import conf
from umodbus.server.tcp import RequestHandler, get_server
from umodbus.utils import log_to_stream

log_to_stream(level=logging.DEBUG)
data_store =defaultdict(int)

conf.SIGNED_VALUES = True

TCPServer.allow_reuse_address = True
app = get_server(TCPServer, ('0.0.0.0', 502), RequestHandler)

data_store[10]=0
data_store[11]=0
data_store[20]=0
data_store[21]=0

@app.route(slave_ids=[1], function_codes=[3,4], addresses=list(range(10,15)))
def read_data_store_power(slave_id, function_code, address):
   """" Return value of address. """
   print("Read Power: "+str(address))
   return data_store[address]

@app.route(slave_ids=[1], function_codes=[6, 16], addresses=list(range(10, 15)))
def write_data_store_power(slave_id, function_code, address, value):
   """" Set value for address. """
   print("Write Power: "+str(address)+" Value: "+str(value))
   data_store[address] = value


@app.route(slave_ids=[1], function_codes=[3,4], addresses=list(range(20,25)))
def read_data_store_energy(slave_id, function_code, address):
   """" Return value of address. """
   print("Read Request for Energy no:"+str(address))
   return data_store[address]

@app.route(slave_ids=[1], function_codes=[6, 16], addresses=list(range(20, 25)))
def write_data_store_power_energy(slave_id, function_code, address, value):
   """" Set value for address. """
   print("Write Request for: "+str(address)+" and Value: "+str(value))
   data_store[address] = value


if __name__ == '__main__':
   try:
       app.serve_forever()
   finally:
       app.shutdown()
       app.server_close()````







modbus socketserver modbus-tcp
1个回答
0
投票

答案在这里: https://github.com/AdvancedClimateSystems/uModbus/issues/119

这使用了 socketserver 模块中的 ThreadingMixin 来允许 get_server 处理多个 TCP 会话。

from socketserver import TCPServer, ThreadingMixIn
...

class ThreadingServer(ThreadingMixIn, TCPServer):
    pass

ThreadingServer.allow_reuse_address = True

try:
    app = get_server(ThreadingServer, (host, port), RequestHandler)
except PermissionError:
    print("You don't have permission to bind on {}".format(port))
    print("Hint: try with a different port (ex:  localhost:50200)")
    exit(1)

© www.soinside.com 2019 - 2024. All rights reserved.