AdvancedClimateSystems / uModbus

Python implementation of the Modbus protocol.
Mozilla Public License 2.0
209 stars 80 forks source link

Online uModbus tcp server #119

Open azat385 opened 3 years ago

azat385 commented 3 years ago

I have started the uModbus tcp server on 89.223.127.70:502 for online debuging of the clients.

Available registers from 0-150 for reading and 6-150 for writing.

Code:

import logging
from socketserver import TCPServer, ThreadingMixIn
from collections import defaultdict

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

from datetime import datetime

log_to_stream(level=logging.DEBUG)
data_store = defaultdict(int)
conf.SIGNED_VALUES = True

host = '0.0.0.0'
port = 502

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)

@app.route(slave_ids=[1], function_codes=[3, 4], addresses=list(range(0, 150)))
def read_data_store(slave_id, function_code, address):
    """" Return value of address. """
    ts = datetime.now()
    data_store[0] = ts.year
    data_store[1] = ts.month
    data_store[2] = ts.day
    data_store[3] = ts.hour
    data_store[4] = ts.minute
    data_store[5] = ts.second
    return data_store[address]

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

if __name__ == '__main__':
    try:
        app.serve_forever()
    finally:
        app.shutdown()
        app.server_close()
azat385 commented 3 years ago

Is it possible to run rtu over tcp server (via raw socket or even RFC 2217) with a same data_store?

some how like that:

import serial
from umodbus.client.serial import rtu

serial_port = serial.serial_for_url("socket://0.0.0.0:5020")
azat385 commented 3 years ago

in fact i need to start tcp ThreadingServer with rtu ADU on a different port.

is it possible