And there it is, it took me two days with the help of ChatGPT (which makes quite a few mistakes by the way) to come up with a trial version that runs on my Windows PC. Now I just need to adapt it to run on Rpi+Neuron.
from pymodbus.client import ModbusSerialClient
from pymodbus.server import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext, ModbusSequentialDataBlock
from pymodbus.exceptions import ModbusIOException
from threading import Thread, Lock
import time
# Configuration of the PLC IP address and port
PLC_IP = '127.0.0.1'
PLC_PORT = 503
# Configuration of the USB port for the sensor
SENSOR_PORT = 'COM6' # Port of the sensor, adjusted for COM6
BAUDRATE = 57600
# Addresses of the holding registers that the PLC will read
READ_START_REGISTER = 64
READ_NUM_REGISTERS = 8
# Address of the holding register that the PLC will write to
WRITE_REGISTER = 82
# Reading interval in seconds
INTERVAL = 0.01 # 10 ms
# Slave ID
SLAVE_ID = 1
# Create a Modbus RTU client for the sensor
sensor_client = ModbusSerialClient(
method='rtu',
port=SENSOR_PORT,
baudrate=BAUDRATE,
timeout=0.1,
parity='N',
stopbits=1,
bytesize=8
)
# Check connection to the sensor
if not sensor_client.connect():
print("Error connecting to the sensor.")
exit(1)
else:
print("Connection to the sensor successful.")
# Create a datastore to store the sensor data
store = ModbusSlaveContext(
hr=ModbusSequentialDataBlock(0, [0]*100)) # Example with 100 registers
context = ModbusServerContext(slaves=store, single=True)
# Create a lock to synchronize access to shared resources
access_lock = Lock()
# Store the previous value of the register written by the PLC
previous_write_value = None
# Function to read sensor data
def read_sensor_data():
while True:
try:
# Read holding registers from the sensor with the slave ID
with access_lock:
response = sensor_client.read_holding_registers(READ_START_REGISTER, READ_NUM_REGISTERS, SLAVE_ID)
if not response.isError():
# Update the datastore with the read values from the sensor
store.setValues(3, READ_START_REGISTER, response.registers)
else:
print("Error reading sensor registers:", response)
except ModbusIOException as e:
print("Error connecting to the sensor:", e)
except Exception as e:
print("Error reading sensor registers:", e)
# Wait before reading again
time.sleep(INTERVAL)
# Function to write to the sensor
def write_to_sensor(value):
try:
# Write the value to the sensor using function code 06 (Write Single Register)
with access_lock:
response = sensor_client.write_register(WRITE_REGISTER, value, SLAVE_ID)
if response.isError():
print("Error writing to the sensor:", response)
else:
print("Write to sensor:", value)
except ModbusIOException as e:
print("Error connecting to the sensor:", e)
# Function to check for write requests from the PLC
def check_for_write_request(context):
global previous_write_value
while True:
# Get the value of the register written by the PLC
write_value = context[SLAVE_ID].getValues(3, WRITE_REGISTER, count=1)[0]
# Check if the value has changed since the last check
if write_value != previous_write_value:
# Update the value on the sensor
write_to_sensor(write_value)
# Update the previous value for the next check
previous_write_value = write_value
# Wait before checking again
time.sleep(INTERVAL)
# Modbus server identification
identity = ModbusDeviceIdentification()
identity.VendorName = 'MyCompany'
identity.ProductCode = 'MyProduct'
identity.VendorUrl = 'http://example.com'
identity.ProductName = 'MyModbusDevice'
identity.ModelName = 'MyModel'
identity.MajorMinorRevision = '1.0'
# Function to start the Modbus server
def start_server():
print("Starting the server...")
try:
StartTcpServer(context=context, identity=identity, address=(PLC_IP, PLC_PORT))
except Exception as e:
print(f"Error starting the server: {e}")
if __name__ == "__main__":
# Start a thread to read sensor data
sensor_thread = Thread(target=read_sensor_data)
sensor_thread.daemon = True
sensor_thread.start()
# Start a thread to check for write requests from the PLC
write_thread = Thread(target=check_for_write_request, args=(context,))
write_thread.daemon = True
write_thread.start()
# Start the Modbus server
start_server()