from pymodbus.server.sync import StartTcpServer
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusBinaryFramer
from threading import Thread
import time
# Function to update values in the specified register
def update_values(context, register_address, value):
context[0x00].setValues(register_address, value, [0]*value)
# Function to continuously update the specified register
def update_thread(context, register_address):
while True:
update_values(context, register_address, 123) # Update the value
time.sleep(1) # Wait for 1 second before updating again
# Define the server settings
def run_server():
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [0]*100),
co=ModbusSequentialDataBlock(0, [0]*100),
hr=ModbusSequentialDataBlock(0, [0]*100),
ir=ModbusSequentialDataBlock(0, [0]*100))
context = ModbusServerContext(slaves=store, single=True)
# Start the Modbus TCP server
StartTcpServer(context, address=("localhost", 5020))
# Start the thread to continuously update the register
update_thread(context, 0x00)
if __name__ == "__main__":
run_server()
pymodbus
最新推荐文章于 2024-08-29 18:44:48 发布