pymodbus: update context of running server - python

I have a running ModbusRTU server, following this example.
I know how to update the context, but I can't update the context of a running server.
When I update the context in the run_updating_server() function (before StartSerialServer()) then it works fine.
But when I try to update the running context by calling updating_writer(context) then it doesn't update.
Also calling my own function 'getUpdatedContext()' from withing updating_writer() does not work:
def updating_writer(a):
a =(getContext(),)
""" A worker process that runs every so often and
updates live values of the context. It should be noted
that there is a race condition for the update.
:param arguments: The input arguments to the call
"""
log.debug("updating the context")
context = a[0]
register = 3
slave_id = 0x41
address = 0x10
values = context[slave_id].getValues(register, address, count=5)
values = [v + 1 for v in values]
log.debug("new values: " + str(values))
context[slave_id].setValues(register, address, values)
getContext():
def getContext():
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [17]*100),
co=ModbusSequentialDataBlock(0, [17]*100),
hr=ModbusSequentialDataBlock(0, [17]*100),
ir=ModbusSequentialDataBlock(0, [17]*100))
store.setValues(5, 1, [0])
context = ModbusServerContext(slaves=store, single=True)
return context
my full code:
#!/usr/bin/env python
import os
import sys
"""
Pymodbus Server With Updating Thread
--------------------------------------------------------------------------
This is an example of having a background thread updating the
context while the server is operating. This can also be done with
a python thread::
from threading import Thread
thread = Thread(target=updating_writer, args=(context,))
thread.start()
"""
# --------------------------------------------------------------------------- #
# import the modbus libraries we need
# --------------------------------------------------------------------------- #
from pymodbus.server.asynchronous import StartSerialServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer
# --------------------------------------------------------------------------- #
# import the twisted libraries we need
# --------------------------------------------------------------------------- #
from twisted.internet.task import LoopingCall
# --------------------------------------------------------------------------- #
# configure the service logging
# --------------------------------------------------------------------------- #
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
# --------------------------------------------------------------------------- #
# define your callback process
# --------------------------------------------------------------------------- #
def updating_writer(a):
""" A worker process that runs every so often and
updates live values of the context. It should be noted
that there is a race condition for the update.
:param arguments: The input arguments to the call
"""
log.debug("updating the context")
context = a[0]
register = 3
slave_id = 0x41
address = 0x10
values = context[slave_id].getValues(register, address, count=5)
values = [v + 1 for v in values]
log.debug("new values: " + str(values))
context[slave_id].setValues(register, address, values)
def run_updating_server():
# ----------------------------------------------------------------------- #
# initialize your data store
# ----------------------------------------------------------------------- #
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [17]*100),
co=ModbusSequentialDataBlock(0, [17]*100),
hr=ModbusSequentialDataBlock(0, [17]*100),
ir=ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)
# ----------------------------------------------------------------------- #
# initialize the server information
# ----------------------------------------------------------------------- #
identity = ModbusDeviceIdentification()
identity.VendorName = 'pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'pymodbus Server'
identity.ModelName = 'pymodbus Server'
identity.MajorMinorRevision = '2.2.0'
# ----------------------------------------------------------------------- #
# run the server you want
# ----------------------------------------------------------------------- #
time = 5
loop = LoopingCall(f=updating_writer, a=(context,))
loop.start(time, now=False) # initially delay by time
log.debug("::: Starting Modbus RTU server :::")
# RTU:
StartSerialServer(context, framer=ModbusRtuFramer, identity=identity,
port='/dev/ttyUSB0',
timeout=2,
baudrate=115200,
parity='E',
bytesize=8,
stopbits=1)
def main():
pid = str(os.getpid())
filename = 'modbusUpdatingServer.pid'
pidfile = str(os.getcwd()) + '/' + filename
if os.path.isfile(pidfile):
print (filename + " already exists \n exiting")
sys.exit()
open(pidfile, 'w').write(pid)
try:
# run server
run_updating_server()
finally:
os.unlink(pidfile)
if __name__ == "__main__":
main()
I want to update the context from another python script, i tried:
calling updating_writer(a) from that 'other python script', where a = updatedContext.
calling getUpdatedContext(), from withing updating_writer(a), which is a function in 'that other python script' which returns the updatedContext
make the context global, add a function updateContext(a), call that function from another python script.
It all resulted in compiling code, but the context of the running server didn't get updated.
here the code from the 'other python script':
from pymodbus.datastore import ModbusSequentialDataBlock, ModbusSlaveContext, ModbusServerContext
from threading import Thread
import os
import subprocess
import sys
from modbusUpdatingServer import updating_writer, run_updating_server
def writeUpdatedContext():
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [17]*100),
co=ModbusSequentialDataBlock(0, [17]*100),
hr=ModbusSequentialDataBlock(0, [17]*100),
ir=ModbusSequentialDataBlock(0, [17]*100))
store.setValues(5, 1, [0])
context = ModbusServerContext(slaves=store, single=True)
updating_writer(a=(context,)
def main():
choice = input("press x if you want to update the context")
if choice == 'x' or choice == 'X':
writeUpdatedContext()
if __name__ == "__main__":
main()
How am I supposed to interact with updating_writer?
What I want to achieve is my modbusRTU server running, and updating the context from another threat, so my modbus client(master) can read the registers I've filled.

Related

Pymodbus Server write callback

i am setting up a ModbusServer with pymodbus.
i read a datalist over Serial port an write it into datastore of the server.
so i can see data f.e. in ModbusPoll
now i want write back datapoints f.e. dp 1, value 10 function 16 on my modbus server
is there any callback or method to catch which address and value hast changed?
Many Thanks
class CustomDataBlock(ModbusSparseDataBlock):
def setValues(self, address, value):
super(CustomDataBlock, self).setValues(address, value)
print("wrote {} to {}".format(value, address))
def setValuesInternal(self, address, value):
ModbusSparseDataBlock.setValues(CustomDataBlock, self).setValues(address, value)
def updating_writer(context):
context[0].setValuesInternal(16, 0, valueDataAct) #update Datastore with Serial values
def run_updating_server():
block = CustomDataBlock([0]*378)
store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
context = ModbusServerContext(slaves=store, single=True)
time = 1 #in seconds
loop = LoopingCall(f=updating_writer, context=(context))
loop.start(time, now=False)
StartTcpServer(context, address=('0.0.0.0', 502))
if __name__ == "__main__":
run_updating_server()
You can do this by implementing a custom datablock - see the example in the documentation. You can then do whatever you want in setValues; the relevant section from the example is:
# --------------------------------------------------------------------------- #
# import the modbus libraries we need
# --------------------------------------------------------------------------- #
from pymodbus.version import version
from pymodbus.server.asynchronous import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSparseDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer
# --------------------------------------------------------------------------- #
# import the twisted libraries we need
# --------------------------------------------------------------------------- #
from twisted.internet.task import LoopingCall
# --------------------------------------------------------------------------- #
# configure the service logging
# --------------------------------------------------------------------------- #
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
class CustomDataBlock(ModbusSparseDataBlock):
def setValues(self, address, value):
super(CustomDataBlock, self).setValues(address, value)
print("wrote {} to {}".format(value, address))
def setValuesInternal(self, address, value):
ModbusSparseDataBlock.setValues(self, address, value)
def updating_writer(context):
print("value before update: " + str(context[0].getValues(4, 1, 1)))
context[0].store['d'].setValuesInternal(2, [251]) #update Datastore with Serial values
print("value after update: " + str(context[0].getValues(4, 1, 1)))
def run_updating_server():
block = CustomDataBlock([0]*378)
store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
context = ModbusServerContext(slaves=store, single=True)
time = 1 #in seconds
loop = LoopingCall(f=updating_writer, context=(context))
loop.start(time, now=False)
StartTcpServer(context, address=('0.0.0.0', 502))
if __name__ == "__main__":
run_updating_server()

pymodbus Modbus Server implementation with multiple slave devices context - writing to a register overwrites to all slaves

I have an issue with a simple pymodbus server implementation. From what I have read in the docs, this implementation should have unique slave contexts for each slave device, i.e. writing to device 0x01, register address 1, should be a different register from device 0x02, register 1.
In my case, writing to register 1 writes to register 1 for ALL slave addresses. Could someone go over my server code to see if I am missing something, or perhaps clarify if my understanding of how the pymodbus server is supposed to work with the single flag set to False.
Cheers. Code here:
#!/usr/bin/env python3
"""
Pymodbus Synchronous Server
--------------------------------------------------------------------------
This synced server is implemented using TCP, with multiple slave contexts
"""
# --------------------------------------------------------------------------- #
# import the various server implementations
# --------------------------------------------------------------------------- #
from pymodbus.server.sync import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
def run_server():
slaves = {
0x01: ModbusSlaveContext(),
0x02: ModbusSlaveContext()
}
context = ModbusServerContext(slaves=slaves, single=False)
# ----------------------------------------------------------------------- #
# initialize the server information
# ----------------------------------------------------------------------- #
# If you don't set this or any fields, they are defaulted to empty strings.
# ----------------------------------------------------------------------- #
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/riptideio/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '2.3.0'
# ----------------------------------------------------------------------- #
# run the server
# ----------------------------------------------------------------------- #
StartTcpServer(context, identity=identity, address=("0.0.0.0", 5020))
if __name__ == "__main__":
run_server()
I had a similar issue with the RTU server and had more a less the same code as you otherwise.
But for me it was that I not had made separat ModbusSlaveContext objects in the slave dict. But that is not the case in your code.
I share my code here maybe it help someone.
Python code:
#!/usr/bin/env python
"""
Pymodbus Server With Updating Thread
--------------------------------------------------------------------------
This is an example of having a background thread updating the
context while the server is operating. This can also be done with
a python thread::
from threading import Thread
thread = Thread(target=updating_writer, args=(context,))
thread.start()
"""
# --------------------------------------------------------------------------- #
# import the modbus libraries we need
# --------------------------------------------------------------------------- #
from pymodbus.server.asynchronous import StartSerialServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer
# --------------------------------------------------------------------------- #
# import the payload builder
# --------------------------------------------------------------------------- #
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.payload import BinaryPayloadBuilder
# --------------------------------------------------------------------------- #
# import the twisted libraries we need
# --------------------------------------------------------------------------- #
from twisted.internet.task import LoopingCall
# --------------------------------------------------------------------------- #
# configure the service logging
# --------------------------------------------------------------------------- #
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
# --------------------------------------------------------------------------- #
# define your callback process
# --------------------------------------------------------------------------- #
def updating_writer(a):
""" A worker process that runs every so often and
updates live values of the context. It should be noted
that there is a race condition for the update.
:param arguments: The input arguments to the call
"""
context = a[0]
register = 3
#### Write to registers slave 1 ####
slave_id = 0x01
log.debug(f"::: Make payload to SLAVE={slave_id} :::")
# Total energy
builder = BinaryPayloadBuilder(
byteorder=Endian.Big,
wordorder=Endian.Little
)
builder.add_32bit_int(20000) # kWh Tot*10
energy = builder.to_registers()
# Phase 1 variables
builder = BinaryPayloadBuilder(
byteorder=Endian.Big,
wordorder=Endian.Little
)
builder.add_32bit_int(4000) # VL1L2*10
builder.add_32bit_int(2300) # VL1N*10
builder.add_32bit_int(1000) # AL1*1000
builder.add_32bit_int(2300) # kWL1*10
phase1 = builder.to_registers()
log.debug(f"::: Write registers to SLAVE={slave_id} :::")
context[slave_id].setValues(register, 0x0112, energy)
context[slave_id].setValues(register, 0x011e, phase1)
context[slave_id].setValues(register, 0x000b, [0x0155])
#### Write to registers slave 100 ####
slave_id = 0x64
log.debug(f"::: Make payload to SLAVE={slave_id} :::")
# Total energy
builder = BinaryPayloadBuilder(
byteorder=Endian.Big,
wordorder=Endian.Little
)
builder.add_32bit_int(20000) # kWh Tot*10
energy = builder.to_registers()
# Phase 1 variables
builder = BinaryPayloadBuilder(
byteorder=Endian.Big,
wordorder=Endian.Little
)
builder.add_32bit_int(4000) # VL1L2*10
builder.add_32bit_int(2300) # VL1N*10
builder.add_32bit_int(2000) # AL1*1000
builder.add_32bit_int(4600) # kWL1*10
phase1 = builder.to_registers()
log.debug(f"::: Write registers to SLAVE={slave_id} :::")
context[slave_id].setValues(register, 0x0112, energy)
context[slave_id].setValues(register, 0x011e, phase1)
context[slave_id].setValues(register, 0x000b, [0x0155])
def run_updating_server():
# ----------------------------------------------------------------------- #
# initialize your data store
# ----------------------------------------------------------------------- #
addresses = [1, 100]
slaves = {}
for adress in addresses:
store = ModbusSlaveContext(zero_mode=True)
slaves.update({adress: store})
context = ModbusServerContext(slaves=slaves, single=False)
# ----------------------------------------------------------------------- #
# initialize the server information
# ----------------------------------------------------------------------- #
identity = ModbusDeviceIdentification()
identity.VendorName = 'pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'pymodbus Server'
identity.ModelName = 'pymodbus Server'
identity.MajorMinorRevision = '2.3.0'
# ----------------------------------------------------------------------- #
# run the server you want
# ----------------------------------------------------------------------- #
time = 5 # 5 seconds delay
loop = LoopingCall(f=updating_writer, a=(context,))
loop.start(time, now=False) # initially delay by time
StartSerialServer(
context=context,
framer=ModbusRtuFramer,
identity=identity,
port='/dev/ttyUSB0',
timeout=0.0001,
baudrate=9600,
parity='N',
bytesize=8,
stopbits=1,
ignore_missing_slaves=True)
if __name__ == "__main__":
run_updating_server()

Is it possible 32bit data transfer using pymodbus and saving the data value in sql server?

from __future__ import print_function
from pymodbus.server.asynchronous import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.datastore.database import SqlSlaveContext
from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
class CustomDataBlock( ModbusSequentialDataBlock):
""" A datablock that stores the new value in memory
and performs a custom action after it has been stored.
"""
def setValues(self, address, value):
""" Sets the requested values of the datastore
:param address: The starting address
:param values: The new values to be set
"""
super( ModbusSequentialDataBlock, self).setValues(address, value)
print("wrote {} to {}".format(value, address))
def run_custom_db_server():
# ----------------------------------------------------------------------- #
# initialize your data store
# ----------------------------------------------------------------------- #
block = CustomDataBlock(0,[0]*100)
store = SqlSlaveContext(di=block, co=block, hr=block, ir=block)
context = ModbusServerContext(slaves=store, single=True)
# ----------------------------------------------------------------------- #
# initialize the server information
# ----------------------------------------------------------------------- #
identity = ModbusDeviceIdentification()
identity.VendorName = 'pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'pymodbus Server'
identity.ModelName = 'pymodbus Server'
identity.MajorMinorRevision = '2.2.0'
# ----------------------------------------------------------------------- #
# run the server you want
# ----------------------------------------------------------------------- #
# p = Process(target=device_writer, args=(queue,))
# p.start()
StartTcpServer(context, identity=identity, address=("192.168.1.12", 502))
if __name__ == "__main__":
run_custom_db_server()
I am sending command from modscan32 client to store 32bit unsigned integer in the pymodbus database. But it shows different value than the value I send from the modscan client. here is attached screenshot from modscan, pymodbus database and source code is also here.
Modscan32 view
pymodbusdb view

How do assign holding registers in pymodbus?

I am making a modbus server on a Raspberry Pi Zero to send data to a Modbus Client/Data Logger. I am trying to use pymodbus but I am having trouble following the documentation and was wondering if someone could show me how to assign specific values to holding register? I am using the Synchronous Server Example as my starting point. I am fairly new to Python and really need to understand what is going on in this code/program so if I need to make changes I can. Any help would be appreciated.
#!/usr/bin/env python
"""
Pymodbus Synchronous Server Example
--------------------------------------------------------------------------
The synchronous server is implemented in pure python without any third
party libraries (unless you need to use the serial protocols which require
pyserial). This is helpful in constrained or old environments where using
twisted is just not feasible. What follows is an example of its use:
"""
# --------------------------------------------------------------------------- #
# import the various server implementations
# --------------------------------------------------------------------------- #
from pymodbus.server.sync import StartTcpServer
from pymodbus.server.sync import StartUdpServer
from pymodbus.server.sync import StartSerialServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock, ModbusSparseDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusBinaryFramer
# --------------------------------------------------------------------------- #
# configure the service logging
# --------------------------------------------------------------------------- #
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s'
' %(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
def run_server():
# ----------------------------------------------------------------------- #
# initialize your data store
# ----------------------------------------------------------------------- #
# The datastores only respond to the addresses that they are initialized to
# Therefore, if you initialize a DataBlock to addresses of 0x00 to 0xFF, a
# request to 0x100 will respond with an invalid address exception. This is
# because many devices exhibit this kind of behavior (but not all)::
#
# block = ModbusSequentialDataBlock(0x00, [0]*0xff)
#
# Continuing, you can choose to use a sequential or a sparse DataBlock in
# your data context. The difference is that the sequential has no gaps in
# the data while the sparse can. Once again, there are devices that exhibit
# both forms of behavior::
#
# block = ModbusSparseDataBlock({0x00: 0, 0x05: 1})
# block = ModbusSequentialDataBlock(0x00, [0]*5)
#
# Alternately, you can use the factory methods to initialize the DataBlocks
# or simply do not pass them to have them initialized to 0x00 on the full
# address range::
#
# store = ModbusSlaveContext(di = ModbusSequentialDataBlock.create())
# store = ModbusSlaveContext()
#
# Finally, you are allowed to use the same DataBlock reference for every
# table or you may use a separate DataBlock for each table.
# This depends if you would like functions to be able to access and modify
# the same data or not::
#
# block = ModbusSequentialDataBlock(0x00, [0]*0xff)
# store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
#
# The server then makes use of a server context that allows the server to
# respond with different slave contexts for different unit ids. By default
# it will return the same context for every unit id supplied (broadcast
# mode).
# However, this can be overloaded by setting the single flag to False and
# then supplying a dictionary of unit id to context mapping::
#
# slaves = {
# 0x01: ModbusSlaveContext(...),
# 0x02: ModbusSlaveContext(...),
# 0x03: ModbusSlaveContext(...),
# }
# context = ModbusServerContext(slaves=slaves, single=False)
#
# The slave context can also be initialized in zero_mode which means that a
# request to address(0-7) will map to the address (0-7). The default is
# False which is based on section 4.4 of the specification, so address(0-7)
# will map to (1-8)::
#
# store = ModbusSlaveContext(..., zero_mode=True)
# ----------------------------------------------------------------------- #
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [17]*100),
co=ModbusSequentialDataBlock(0, [17]*100),
hr=ModbusSequentialDataBlock(0, [17]*100),
ir=ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)
# ----------------------------------------------------------------------- #
# initialize the server information
# ----------------------------------------------------------------------- #
# If you don't set this or any fields, they are defaulted to empty strings.
# ----------------------------------------------------------------------- #
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/riptideio/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '1.5'
# ----------------------------------------------------------------------- #
# run the server you want
# ----------------------------------------------------------------------- #
# Tcp:
StartTcpServer(context, identity=identity, address=("localhost", 5020))
# TCP with different framer
# StartTcpServer(context, identity=identity,
# framer=ModbusRtuFramer, address=("0.0.0.0", 5020))
# Udp:
# StartUdpServer(context, identity=identity, address=("0.0.0.0", 5020))
# Ascii:
# StartSerialServer(context, identity=identity,
# port='/dev/ttyp0', timeout=1)
# RTU:
# StartSerialServer(context, framer=ModbusRtuFramer, identity=identity,
# port='/dev/ttyp0', timeout=.005, baudrate=9600)
# Binary
# StartSerialServer(context,
# identity=identity,
# framer=ModbusBinaryFramer,
# port='/dev/ttyp0',
# timeout=1)
if __name__ == "__main__":
run_server()
Looks like I am using the wrong server and should be using the callback server but I am still unsure how to assign data to a input/holding register that is read in by a local sensor/device. Here is the Code to the Call back Server:
#!/usr/bin/env python
"""
Pymodbus Server With Callbacks
--------------------------------------------------------------------------
This is an example of adding callbacks to a running modbus server
when a value is written to it. In order for this to work, it needs
a device-mapping file.
"""
# --------------------------------------------------------------------------- #
# import the modbus libraries we need
# --------------------------------------------------------------------------- #
from pymodbus.server.async import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSparseDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer
# --------------------------------------------------------------------------- #
# import the python libraries we need
# --------------------------------------------------------------------------- #
from multiprocessing import Queue, Process
# --------------------------------------------------------------------------- #
# configure the service logging
# --------------------------------------------------------------------------- #
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
# --------------------------------------------------------------------------- #
# create your custom data block with callbacks
# --------------------------------------------------------------------------- #
class CallbackDataBlock(ModbusSparseDataBlock):
""" A datablock that stores the new value in memory
and passes the operation to a message queue for further
processing.
"""
def __init__(self, devices, queue):
"""
"""
self.devices = devices
self.queue = queue
values = {k: 0 for k in devices.keys()}
values[0xbeef] = len(values) # the number of devices
super(CallbackDataBlock, self).__init__(values)
def setValues(self, address, value):
""" Sets the requested values of the datastore
:param address: The starting address
:param values: The new values to be set
"""
super(CallbackDataBlock, self).setValues(address, value)
self.queue.put((self.devices.get(address, None), value))
# --------------------------------------------------------------------------- #
# define your callback process
# --------------------------------------------------------------------------- #
def rescale_value(value):
""" Rescale the input value from the range
of 0..100 to -3200..3200.
:param value: The input value to scale
:returns: The rescaled value
"""
s = 1 if value >= 50 else -1
c = value if value < 50 else (value - 50)
return s * (c * 64)
def device_writer(queue):
""" A worker process that processes new messages
from a queue to write to device outputs
:param queue: The queue to get new messages from
"""
while True:
device, value = queue.get()
scaled = rescale_value(value[0])
log.debug("Write(%s) = %s" % (device, value))
if not device: continue
# do any logic here to update your devices
# --------------------------------------------------------------------------- #
# initialize your device map
# --------------------------------------------------------------------------- #
def read_device_map(path):
""" A helper method to read the device
path to address mapping from file::
0x0001,/dev/device1
0x0002,/dev/device2
:param path: The path to the input file
:returns: The input mapping file
"""
devices = {}
with open(path, 'r') as stream:
for line in stream:
piece = line.strip().split(',')
devices[int(piece[0], 16)] = piece[1]
return devices
def run_callback_server():
# ----------------------------------------------------------------------- #
# initialize your data store
# ----------------------------------------------------------------------- #
queue = Queue()
devices = read_device_map("device-mapping")
block = CallbackDataBlock(devices, queue)
store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
context = ModbusServerContext(slaves=store, single=True)
# ----------------------------------------------------------------------- #
# initialize the server information
# ----------------------------------------------------------------------- #
identity = ModbusDeviceIdentification()
identity.VendorName = 'pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'pymodbus Server'
identity.ModelName = 'pymodbus Server'
identity.MajorMinorRevision = '1.0'
# ----------------------------------------------------------------------- #
# run the server you want
# ----------------------------------------------------------------------- #
p = Process(target=device_writer, args=(queue,))
p.start()
StartTcpServer(context, identity=identity, address=("localhost", 5020))
if __name__ == "__main__":
run_callback_server()
Again any help is appreciated.
from pymodbus.client.sync import ModbusTcpClient
address = 2 #register address
value = 12 #new value
unitId = 1
host = "127.0.0.1"
port = 502
client = ModbusTcpClient(host, port)
client.connect()
client.write_register(address,value,unit=unitId)
There is 2 basic function code here(for read,write coils/holding registers): https://github.com/omergunal/Modbus-Web-Interface/blob/master/app.py

How to stop a pymodbus async ModbusTcpServer?

I want to stop a pymodbus async ModbusTcpServer then start a new server. Therefore, I've tried with the following simplified code snippet, but I got an error:
from pymodbus.server.async import StartTcpServer, StopServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from time import sleep
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
def main(name='Pymodbus'):
store = ModbusSlaveContext(hr=ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)
identity = ModbusDeviceIdentification()
identity.VendorName = name
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'
StartTcpServer(
context,
identity=identity,
address=("localhost", 5020),
defer_reactor_run=True
)
sleep(3)
name += 'stuff'
StopServer()
sleep(3)
main(name) # Recursive
main()
Out:
INFO:pymodbus.server.async:Starting Modbus TCP Server on localhost:5020
DEBUG:pymodbus.server.async:Running in Main thread
Traceback (most recent call last):
File "stack.py", line 42, in <module>
main()
File "stack.py", line 38, in main
StopServer()
File "/usr/local/lib/python3.6/dist-packages/pymodbus/server/async.py", line 328, in StopServer
reactor.stop()
File "/usr/local/lib/python3.6/dist-packages/twisted/internet/base.py", line 630, in stop
"Can't stop reactor that isn't running.")
twisted.internet.error.ReactorNotRunning: Can't stop reactor that isn't running.
[UPDATE]
Also, I've tried with another thread to stop the ModbusTcpServer with the defer_reactor_run=False argument (as default) in ModbusTcpServer, but despite that, the behavior remains the same:
import threading
import logging
from pymodbus.server.async import StartTcpServer, StopServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
def stop():
StopServer()
def main(name='Pymodbus'):
store = ModbusSlaveContext(hr=ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)
identity = ModbusDeviceIdentification()
identity.VendorName = name
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'
t = threading.Timer(5, stop)
t.daemon = True
t.start()
StartTcpServer(
context,
identity=identity,
address=("localhost", 5020),
defer_reactor_run=False
)
name += 'stuff'
main(name) # Recursive
main()
Out:
INFO:pymodbus.server.async:Starting Modbus TCP Server on localhost:5020
DEBUG:pymodbus.server.async:Running in Main thread
DEBUG:pymodbus.server.async:Running in spawned thread
DEBUG:pymodbus.server.async:Stopping Server from another thread
INFO:pymodbus.server.async:Starting Modbus TCP Server on localhost:5020
DEBUG:pymodbus.server.async:Running in Main thread
Traceback (most recent call last):
File "stack.py", line 41, in <module>
main()
File "stack.py", line 39, in main
main() # Recursive
File "stack.py", line 35, in main
defer_reactor_run=False
File "/usr/local/lib/python3.6/dist-packages/pymodbus/server/async.py", line 257, in StartTcpServer
reactor.run(installSignalHandlers=_is_main_thread())
File "/usr/local/lib/python3.6/dist-packages/twisted/internet/base.py", line 1260, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "/usr/local/lib/python3.6/dist-packages/twisted/internet/base.py", line 1240, in startRunning
ReactorBase.startRunning(self)
File "/usr/local/lib/python3.6/dist-packages/twisted/internet/base.py", line 748, in startRunning
raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable
I found an alternative solution to stop and start an Async ModbusTcpServer by another Python code because apparently, we cannot restart a reactor event-loop.
This is the runner.py code:
import subprocess
python_version = '3'
path_to_run = './'
py_name = 'async_server.py'
def run():
args = [f"python{python_version}", f"{path_to_run}{py_name}"]
sub_process = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = sub_process.communicate()
if not error_:
print(output)
else:
print(error_)
run() # Recursively.
if __name__ == '__main__':
run()
This is the async_server.py code snippet:
from pymodbus.server.async import StartTcpServer, StopServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
import threading
import sys
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s'
' %(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
def stop():
print('Process will be down.')
StopServer() # Stop server.
sys.exit(0) # Kill the server code.
def run_async_server():
store = ModbusSlaveContext(hr=ModbusSequentialDataBlock(0, [17] * 100))
slaves = {
0x01: store,
0x02: store,
0x03: store,
}
context = ModbusServerContext(slaves=slaves, single=False)
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '1.5'
from twisted.internet import reactor
StartTcpServer(context, identity=identity, address=("localhost", 5020),
defer_reactor_run=True)
print('Start an async server.')
t = threading.Timer(5, stop)
t.daemon = True
t.start()
reactor.run()
print('Server was stopped.')
if __name__ == "__main__":
run_async_server()
Out:
$ python3 runner.py
2019-01-24 12:45:05,126 MainThread INFO async :254 Starting Modbus TCP Server on localhost:5020
2019-01-24 12:45:10,129 Thread-1 DEBUG async :222 Running in spawned thread
2019-01-24 12:45:10,129 Thread-1 DEBUG async :332 Stopping Server from another thread
b'Start an async server.\nProcess will be down.\nServer was stopped.\n'
2019-01-24 12:45:13,389 MainThread INFO async :254 Starting Modbus TCP Server on localhost:5020
2019-01-24 12:45:18,392 Thread-1 DEBUG async :222 Running in spawned thread
2019-01-24 12:45:18,392 Thread-1 DEBUG async :332 Stopping Server from another thread
b'Start an async server.\nProcess will be down.\nServer was stopped.\n'
2019-01-24 12:45:21,653 MainThread INFO async :254 Starting Modbus TCP Server on localhost:5020
2019-01-24 12:45:26,656 Thread-1 DEBUG async :222 Running in spawned thread
2019-01-24 12:45:26,657 Thread-1 DEBUG async :332 Stopping Server from another thread
b'Start an async server.\nProcess will be down.\nServer was stopped.\n'
.
.
.
In the first example, the TCP server is not run since you setted param defer_reactor_run to True, but you have not explicitely run it . Thus , when you try stopping it , it fails since it has not been started.
In the second example, you run it, but are calling it a next time recursively with the main(name) call ! so, it fails with error since it is already started !
the next code should work :
from pymodbus.server.async import StartTcpServer, StopServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from time import sleep
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
def main(name='Pymodbus'):
store = ModbusSlaveContext(hr=ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)
identity = ModbusDeviceIdentification()
identity.VendorName = name
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'
StartTcpServer(
context,
identity=identity,
address=("localhost", 5020),
defer_reactor_run=False
)
sleep(3) # for the fun ?
# and do your stuff
StopServer()
main()
If you want to defer run, you have to call :
from twisted.internet import reactor
StartTcpServer(context, identity=identity, address=("localhost", 5020),
defer_reactor_run=True)
reactor.run()
You can use the example included in library folders: asynchronous-server.py
in python3.7 async was included as a keyword, but in pymodbus 2.3.0 pymodbus.server.async was changed to pymodbus.server.asynchronous
i share you a example that works fine for me:
If you have any more questions, write me at e-mail:Danielsalazr#hotmail.com
#Este codigo funciona ingresando a la direccion esclavo 16 en decimal
#la Ip debe ser la misma que esta asignada en el dispositivo
#los datos se actualizan a patir del registro #15
#Aparentemente la direcion del esclavo no tiene importancia, debido a que
#al realizar la conexion desde el software QModMaster, el numero ingresado
#em el campo SlaveAddr, no afecta la posibilidad de conexion
'''
Pymodbus Server With Updating Thread
--------------------------------------------------------------------------
This is an example of having a background thread updating the
context while the server is operating. This can also be done with
a python thread::
from threading import Thread
thread = Thread(target=updating_writer, args=(context,))
thread.start()
'''
#---------------------------------------------------------------------------#
# import the modbus libraries we need
#---------------------------------------------------------------------------#
from pymodbus.server.asynchronous import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer
#---------------------------------------------------------------------------#
# import the twisted libraries we need
#---------------------------------------------------------------------------#
from twisted.internet.task import LoopingCall
#---------------------------------------------------------------------------#
# configure the service logging
#---------------------------------------------------------------------------#
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
#---------------------------------------------------------------------------#
# define your callback process
#---------------------------------------------------------------------------#
def updating_writer(a):
''' A worker process that runs every so often and
updates live values of the context. It should be noted
that there is a race condition for the update.
:param arguments: The input arguments to the call
'''
log.debug("updating the context")
context = a[0]
register = 3
slave_id = 0x01
address = 0x10
values = context[slave_id].getValues(register, address, count=5)
#el valor count = 5 modifica los datos de los siguientes 5 registros
#continuos al registro especificado en la variable address = 0x10, 16 en decimal
values = [v + 1 for v in values]
log.debug("new values: " + str(values))
context[slave_id].setValues(register, address, values)
#---------------------------------------------------------------------------#
# initialize your data store
#---------------------------------------------------------------------------#
store = ModbusSlaveContext(
di = ModbusSequentialDataBlock(0, [17]*100),
co = ModbusSequentialDataBlock(0, [17]*100),
hr = ModbusSequentialDataBlock(0, [17]*100),
ir = ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)
#ModbusSlaveContext.setValues("lol",hr,3,25)
#context = ModbusServerContext(slaves=store, single=True)
#---------------------------------------------------------------------------#
# initialize the server information
#---------------------------------------------------------------------------#
identity = ModbusDeviceIdentification()
identity.VendorName = 'pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'pymodbus Server'
identity.ModelName = 'pymodbus Server'
identity.MajorMinorRevision = '1.0'
#---------------------------------------------------------------------------#
# run the server you want
#---------------------------------------------------------------------------#
time = 1 # 5 seconds delay
loop = LoopingCall(f=updating_writer, a=(context,))
loop.start(time, now=False) # initially delay by time
StartTcpServer(context, identity= identity, address=("192.168.0.40", 502)) #here you need
#change the ip for the ip address of your device
Greetings from Colombia

Categories

Resources