Skip to content

Instantly share code, notes, and snippets.

@boseji
Last active September 15, 2024 06:54
Show Gist options
  • Save boseji/316bb5f330f1e35201a78fa716cebaf2 to your computer and use it in GitHub Desktop.
Save boseji/316bb5f330f1e35201a78fa716cebaf2 to your computer and use it in GitHub Desktop.
Python MODBUS/IP Server and Client

Python MODBUS/IP Server and Client

This example builds upon the umodbus library.

PyPi https://pypi.org/project/uModbus/

Sources https://github.com/AdvancedClimateSystems/uModbus/

Documents https://umodbus.readthedocs.io/en/latest/

License

SPDX: MIT

MIT License

Copyright (C) 2024 Abhijit Bose (aka. Boseji)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#!/usr/bin/env bash
# Copyright (C) 2024 Abhijit Bose (aka. Boseji)
# SPDX: MIT
rm -rf venv
#!/usr/bin/env python
# Copyright (C) 2024 Abhijit Bose (aka. Boseji)
# SPDX: MIT
import socket
from umodbus import conf
from umodbus.client import tcp
# Enable values to be signed (default is False).
conf.SIGNED_VALUES = True
# Server Detail
svr = ('localhost', 50222)
# Create the Socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("\n Connecting to", svr)
sock.connect(svr)
# Returns a message or Application Data Unit (ADU) specific for doing
# Modbus TCP/IP.
message = tcp.write_single_register(
slave_id=1,
address=1,
value=23,
)
# Return a Write Registers
# message = tcp.write_multiple_registers(
# slave_id=1,
# starting_address=2,
# values=[14, 13, 67],
# )
# Response depends on Modbus function code. This particular returns the
# amount of coils written, in this case it is.
response = tcp.send_message(message, sock)
sock.close()

Python MODBUS/IP Server and Client

This example builds upon the umodbus library.

PyPi https://pypi.org/project/uModbus/

Sources https://github.com/AdvancedClimateSystems/uModbus/

Documents https://umodbus.readthedocs.io/en/latest/

License

MIT License

Copyright (C) 2024 Abhijit Bose (aka. Boseji)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pyserial==3.5
uModbus==1.0.4
#!/usr/bin/env python
# Copyright (C) 2024 Abhijit Bose (aka. Boseji)
# SPDX: MIT
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
# Add stream handler to logger 'uModbus'.
log_to_stream(level=logging.DEBUG)
# Server Detail
svr = ('localhost', 50222)
# A very simple data store which maps address against their values.
data_store = defaultdict(int)
# Enable values to be signed (default is False).
conf.SIGNED_VALUES = True
TCPServer.allow_reuse_address = True
# Open Socket
app = get_server(TCPServer, svr, RequestHandler)
@app.route(slave_ids=[1], function_codes=[3, 4], addresses=list(range(0, 10)))
def read_data_store(slave_id, function_code, address):
"""" Return value of address. """
print("Fetch ADDR:", address)
return data_store[address]
@app.route(slave_ids=[1], function_codes=[6, 16], addresses=list(range(0, 10)))
def write_data_store(slave_id, function_code, address, value):
"""" Set value for address. """
print("Store ADDR:", address, " Data:", value)
data_store[address] = value
if __name__ == '__main__':
print("\n Starting Sever ", svr)
try:
app.serve_forever()
finally:
print("\n\n Closing down server...\n")
app.shutdown()
app.server_close()
#!/usr/bin/env bash
# Copyright (C) 2024 Abhijit Bose (aka. Boseji)
# SPDX: MIT
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment