AdvancedClimateSystems / uModbus

Python implementation of the Modbus protocol.
Mozilla Public License 2.0
211 stars 82 forks source link

Multiple connections #63

Closed ruscito closed 5 years ago

ruscito commented 5 years ago

Hello, I was able to set a Modbus server application without problem. Is it possible for the server to handle multiple client connections? If so could you provide some example or suggestion on how to achieve this.

Thanks Ago

PS: great work

OrangeTux commented 5 years ago

Sorry for responding late. Due to some modifications in my notifications settings I missed this issue.

But yes, it should be possible by using the ThreadedMixIn or ForkingMixin.

Below a modified version of scripts/example/simple_tcp_server.py that includes multithreading:

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

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

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

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

class ThreadingServer(ThreadingMixIn, TCPServer):
    pass

app = get_server(ThreadingServer, ('localhost', 5020), RequestHandler)

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

@app.route(slave_ids=[1], function_codes=[5, 15], addresses=list(range(0, 10)))
def write_data_store(slave_id, function_code, address, value):
    """" Set value for address. """
    print('received request')
    data_store[address] = value
    time.sleep(2)
    print('finished request')

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

Closed due to inactivity. Feel free to reopen when needed.

azat385 commented 4 years ago

Thanks a lot! it works fine!

Please add multiple connections tcp server to examples