How to stop a pymodbus async ModbusTcpServer? - python

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

Related

Is my pymodbus slave code usable or have i done something wrong?

The code is the following. I apologise in advance if ive done something silly. I have imported time as i want to have a delay in my final code
from pymodbus.version import version
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
import time
#-----------------------------------------------------------------------------------------------
import logging
from twisted.names import client
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():
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [17] * 100), #adresse, verdi( di = digital inputs)
co=ModbusSequentialDataBlock(0, [17] * 100), #--_-- (Coils)
hr=ModbusSequentialDataBlock(0, [17] * 100), #--_-- (Holding registers)
ir=ModbusSequentialDataBlock(0, [17] * 100)) #--_-- (input registers)
context = ModbusServerContext(slaves=store, single=True)
#Dette under mås til og måte være fast(slik jeg forstod det) ellers ville du bare få tomme 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 = version.short()
StartSerialServer(context,
framer=ModbusRtuFramer,
identity=identity,
port='COM1',
timeout=1,
baudrate=9600)
#if client.connect():
# print("det funker bro, u good homie")
run_server()
As I have no access to a modbus master, it is very difficult for me to know if it will work or not. I will happily be guided.
What I want is the code to connect to a master/client trough RTU and send some messages if possible

Pymodbus: After StopServer -> StartSerialServer doesn't work (could not open port: PermissionError)

Versions: Python: 3.9 | Pymodbus: 2.5.1
Pymodbus Specific: Server: rtu - sync/async | Client: rtu - sync/async
Description:
In my application I want to start a SerialServer, which can be read by a client connected over RTU. After the client has read the values I want to stop the server. At this point the user should be able to change some values himself and start the SerialServer again.
Exactly the second start of the SerialServer doesn't work, because the server can't open the port.
from pymodbus.version import version
from pymodbus.server.asynchronous import StartSerialServer, StopServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSparseDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer
import time
import sys
import threading
from qtpy import QtWidgets
app = QtWidgets.QApplication(sys.argv)
def modbus_server_start():
print("Modbus-Server start:")
class CustomDataBlock(ModbusSparseDataBlock):
def setValues(self, address, value):
super(CustomDataBlock, self).setValues(0, value_1)
super(CustomDataBlock, self).setValues(1, 11)
super(CustomDataBlock, self).setValues(2, 12)
block = CustomDataBlock({0: [0] * 100})
store = ModbusSlaveContext(hr=block)
context = ModbusServerContext(slaves=store)
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 = version.short()
StartSerialServer(context, framer=ModbusRtuFramer, identity=identity, port='COM6', timeout=0.05, baudrate=19200)
def server_start():
print("Start an async server.")
t = threading.Thread(target=modbus_server_start)
t.daemon = True
t.start()
def modbus_server_stop():
stopthread = threading.Thread(target=stop)
stopthread.daemon = True
stopthread.start()
print("Server was stopped.")
def stop():
print("Process will be down.")
StopServer() # Stop server.
sys.exit(0) # Kill the server code.
window = QtWidgets.QMainWindow()
window.setWindowTitle("StartSerialServer")
window.setGeometry(500, 500, 400, 125)
button = QtWidgets.QPushButton(window)
button.setText("Start")
button.setGeometry(0, 0, 60, 30)
button.show()
button.clicked.connect(server_start)
button2 = QtWidgets.QPushButton(window)
button2.setText("Stop")
button2.setGeometry(100, 0, 60, 30)
button2.show()
button2.clicked.connect(modbus_server_stop)
combobox = QtWidgets.QComboBox(window)
combobox.setGeometry(50, 40, 60, 30)
combobox.addItem("")
combobox.addItem("")
combobox.addItem("")
combobox.addItem("")
combobox.addItem("")
combobox.setItemText(0, "0")
combobox.setItemText(1, "10")
combobox.setItemText(2, "20")
combobox.setItemText(3, "30")
combobox.setItemText(4, "40")
combobox.show()
global value_1
value_1 = combobox.currentText()
window.show()
sys.exit(app.exec_())
Error code:
Start an async server.
Modbus-Server start:
Process will be down.
Server was stopped.
Exception in thread Thread-4:
Traceback (most recent call last):
File "C:\Python32\lib\threading.py", line 954, in _bootstrap_inner
Start an async server.
Modbus-Server start:
self.run()
File "C:\Python32\lib\threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "C:\Python32\Projekte\Pymodbus-Test\github_issue.py", line 36, in modbus_server_start
StartSerialServer(context, framer=ModbusRtuFramer, identity=identity, port='COM6', timeout=0.05, baudrate=19200)
File "C:\Python32\Projekte\Pymodbus-Test\venv\lib\site-packages\pymodbus\server\asynchronous.py", line 340, in StartSerialServer
SerialPort(protocol, port, reactor, baudrate=baudrate, parity=parity,
File "C:\Python32\Projekte\Pymodbus-Test\venv\lib\site-packages\twisted\internet\_win32serialport.py", line 44, in __init__
self._serial = self._serialFactory(
File "C:\Python32\Projekte\Pymodbus-Test\venv\lib\site-packages\serial\serialwin32.py", line 33, in __init__
super(Serial, self).__init__(*args, **kwargs)
File "C:\Python32\Projekte\Pymodbus-Test\venv\lib\site-packages\serial\serialutil.py", line 244, in __init__
self.open()
File "C:\Python32\Projekte\Pymodbus-Test\venv\lib\site-packages\serial\serialwin32.py", line 64, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM6': PermissionError(13, 'Zugriff verweigert', None, 5)
I thought about closing and reopen the server but this also doesn't work.
Maybe somebody could help me to fix the problem. :)

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()

pymodbus: update context of running server

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.

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

Categories

Resources