使用umodbus模块的Python ModBus服务器

时间:2018-03-25 17:17:02

标签: python server modbus modbus-tcp

我想创建一个modbus服务器(本地主机:IP地址:152.168.96.11 - 与系统相同),modbus客户端(ip地址:152.168.96.32)。我的客户端应用程序正在运行,我正在使用umodbus服务器应用程序创建modbus服务器应用程序。 32位数据交换(读或写用于测试目的)。

如何配置python umodbus服务器,服务器能够读取和写入客户端IP地址数据

这是umodbus服务器应用程序 -

#!/usr/bin/env python
# scripts/examples/simple_tcp_server.py
import random
import logging
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

# Create Random Values
rndata = []
for i in range(32):
    rndata.append(random.randint(1,32))

# Add stream handler to logger 'uModbus'.
log_to_stream(level=logging.DEBUG)

# A very simple data store which maps addresss against their values.
data_store = defaultdict(int)

# Enable values to be signed (default is False).
conf.SIGNED_VALUES = True

TCPServer.allow_reuse_address = True
app = get_server(TCPServer, ('152.168.96.11', 255), RequestHandler)


@app.route(slave_ids=[1], function_codes=[3, 4], addresses=list(range(0, 32)))
def read_data_store(slave_id, function_code, address):
    """" Return value of address. """
    return data_store[address]


@app.route(slave_ids=[1], function_codes=[6, 16], addresses=list(range(0, 32)))
def write_data_store(slave_id, function_code, address, value):
    """" Set value for address. """
    data_store[address] = value

# Configuring the Data
write_data_store(1,16,3,784)
write_data_store(1,16,24,678)
rdata1 = read_data_store(1,4,3)
print(rdata1)
rdata2 = read_data_store(1,4,24)
print(rdata2)

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

0 个答案:

没有答案