Beispiel #1
0
def run_custom_db_server():
    # ----------------------------------------------------------------------- # 
    # initialize your data store
    # ----------------------------------------------------------------------- # 
    block  = CustomDataBlock([0]*100)
    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 = '2.2.0'

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #

    # p = Process(target=device_writer, args=(queue,))
    # p.start()
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
Beispiel #2
0
def modbus_master(module, properties):
    log.debug('Modbus master module : '  + str(module))
    # Modbus Master
    #--------------------------------------------------------------------------#
    # initialize your data store
    #--------------------------------------------------------------------------#
    store = ModbusSlaveContext(
        co = ModbusSequentialDataBlock(0, [0]*100),
        hr = ModbusSequentialDataBlock(0, [0]*100))
    context = ModbusServerContext(slaves=store, single=True)

    #--------------------------------------------------------------------------#
    # initialize the server information
    #--------------------------------------------------------------------------#
    identity = ModbusDeviceIdentification()
    identity.VendorName  = 'ASO+AKO'
    identity.ProductCode = 'DYODE'
    identity.VendorUrl   = 'yoloswag'
    identity.ProductName = 'DYODE'
    identity.ModelName   = 'BSides LV release'
    identity.MajorMinorRevision = '0.9'

    #--------------------------------------------------------------------------#
    # run the server you want
    #--------------------------------------------------------------------------#
    time = 1 # 5 seconds delay
    loop = LoopingCall(f=modbus_master_update, a=(module, properties, context))
    loop.start(time, now=False) # initially delay by time
    StartTcpServer(context, identity=identity, address=("0.0.0.0", \
                   properties['port_out']))
def run_dbstore_update_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #

    block = ModbusSequentialDataBlock(0x00, [0] * 0xff)
    store = SqlSlaveContext(block)

    context = ModbusServerContext(slaves={1: store}, 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.2.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
    loop.stop()
    StartTcpServer(context, identity=identity, address=("", 5020))
Beispiel #4
0
def ServerThread(e):
	global server
	# Configure the service logging
	#import logging
	#logging.basicConfig()
	#log = logging.getLogger()
	#log.setLevel(logging.DEBUG)

	# 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 = '1.0'


	# Run the server 
	# StartTcpServer(context, identity=identity, address=(args.ip, 502))
	server = ModbusTcpServer(context, identity=identity, address=(ip, 502))
	print 'Server started'
	server.serve_forever(0.1)
	print 'Server stopped'
Beispiel #5
0
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  # 5 seconds delay
    loop = LoopingCall(f=updating_writer, a=(context,))
    loop.start(time, now=False) # initially delay by time
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
def main():
	
	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)
	identity = ModbusDeviceIdentification()
	identity.VendorName  = 'pymodbus'
	identity.ProductCode = 'PM'
	identity.VendorUrl   = 'http://github.com/simplyautomationized'
	identity.ProductName = 'pymodbus Server'
	identity.ModelName   = 'pymodbus Server'
	identity.MajorMinorRevision = '1.0'
	time = 5 # 5 seconds delaytime = 5 # 5 seconds delay
	writer = LoopingCall(read_context,a=(context,))
	loop = LoopingCall(updating_writer, a=(context,))
	loop.start(.5) # initially delay by time
	writer.start(.1)
	StartTcpServer(context, identity=identity)#, address=("localhost", 502))
	#cleanup async tasks
	temp.setEnabled(False)
	loop.stop()
	writer.stop()
	GPIO.cleanup()
Beispiel #7
0
def identity_factory():
    identity = ModbusDeviceIdentification()
    identity.VendorName  = 'pymodbus'
    identity.ProductCode = 'PM'
    identity.VendorUrl   = 'http://github.com/andreadanzi/pymodbus/'
    identity.ProductName = 'pymodbus Pump Server'
    identity.ModelName   = 'pymodbus Pump Server'
    identity.MajorMinorRevision = '1.0'
def run_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #
    store = ModbusSlaveContext()
    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'

    # ----------------------------------------------------------------------- #
    # Add an example which is long enough to force the ReadDeviceInformation
    # request / response to require multiple responses to send back all of the
    # information.
    # ----------------------------------------------------------------------- #

    identity[0x80] = "Lorem ipsum dolor sit amet, consectetur adipiscing " \
                     "elit. Vivamus rhoncus massa turpis, sit amet " \
                     "ultrices orci semper ut. Aliquam tristique sapien in " \
                     "lacus pharetra, in convallis nunc consectetur. Nunc " \
                     "velit elit, vehicula tempus tempus sed. "

    # ----------------------------------------------------------------------- #
    # Add an example with repeated object IDs. The MODBUS specification is
    # entirely silent on whether or not this is allowed. In practice, this
    # should be assumed to be contrary to the MODBUS specification and other
    # clients (other than pymodbus) might behave differently when presented
    # with an object ID occurring twice in the returned information.
    #
    # Use this at your discretion, and at the very least ensure that all
    # objects which share a single object ID can fit together within a single
    # ADU unit. In the case of Modbus RTU, this is about 240 bytes or so. In
    # other words, when the spec says "An object is indivisible, therefore
    # any object must have a size consistent with the size of transaction
    # response", if you use repeated OIDs, apply that rule to the entire
    # grouping of objects with the repeated OID.
    # ----------------------------------------------------------------------- #
    identity[0x81] = ['pymodbus {0}'.format(pymodbus_version),
                      'pyserial {0}'.format(pyserial_version)]

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- # 
    # Tcp:
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
def run_payload_server():
    # ----------------------------------------------------------------------- #
    # build your payload
    # ----------------------------------------------------------------------- #
    builder = BinaryPayloadBuilder(byteorder=Endian.Little,
                                   wordorder=Endian.Little)
    builder.add_string('abcdefgh')
    builder.add_bits([0, 1, 0, 1, 1, 0, 1, 0])
    builder.add_8bit_int(-0x12)
    builder.add_8bit_uint(0x12)
    builder.add_16bit_int(-0x5678)
    builder.add_16bit_uint(0x1234)
    builder.add_32bit_int(-0x1234)
    builder.add_32bit_uint(0x12345678)
    builder.add_32bit_float(22.34)
    builder.add_32bit_float(-22.34)
    builder.add_64bit_int(-0xDEADBEEF)
    builder.add_64bit_uint(0x12345678DEADBEEF)
    builder.add_64bit_uint(0xDEADBEEFDEADBEED)
    builder.add_64bit_float(123.45)
    builder.add_64bit_float(-123.45)

    
    # ----------------------------------------------------------------------- #
    # use that payload in the data store
    # ----------------------------------------------------------------------- #
    # Here we use the same reference block for each underlying store.
    # ----------------------------------------------------------------------- #
    
    block = ModbusSequentialDataBlock(1, builder.to_registers())
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    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/bashwork/pymodbus/'
    identity.ProductName = 'Pymodbus Server'
    identity.ModelName = 'Pymodbus Server'
    identity.MajorMinorRevision = '1.5'
    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
Beispiel #10
0
    def __init__(self, address, port = MODBUS_PORT):
        store = ModbusSlaveContext(
            di = ModbusSequentialDataBlock(0, [0]*100),
            co = ModbusSequentialDataBlock(0, [0]*100),
            hr = ModbusSequentialDataBlock(0, [0]*100),
            ir = ModbusSequentialDataBlock(0, [0]*100))
        
        self.context = ModbusServerContext(slaves=store, single=True)
        
        identity = ModbusDeviceIdentification()
        identity.VendorName         = 'MockPLCs'
        identity.ProductCode        = 'MP'
        identity.VendorUrl          = 'http://github.com/bashwork/pymodbus/'
        identity.ProductName        = 'MockPLC 3000'
        identity.ModelName          = 'MockPLC Ultimate'
        identity.MajorMinorRevision = '1.0'

        ModbusServerFactory.__init__(self, self.context, ModbusSocketFramer, identity)
Beispiel #11
0
def main():
    # initialize the four register types
    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)
    
    identity = ModbusDeviceIdentification()
    identity.VendorName  = 'SPARSA'
    identity.ProductCode = 'SP'
    identity.VendorUrl   = 'http://gentoocloud.com/bitchimabus'
    identity.ProductName = 'SPARSA Temperature Sensor'
    identity.ModelName   = 'SP_1337'
    identity.MajorMinorRevision = '1.0'
    pi.start()
    time = 5 # 5 seconds delaytime = 5 # 5 seconds delay
    loop = LoopingCall(f=updating_writer, a=(context,))
    loop.start(time, now=False) # initially delay by time
    StartTcpServer(context, identity=identity, address=(args.address, 502))
Beispiel #12
0
def main():
    logging.basicConfig()
    #server_log   = logging.getLogger("pymodbus.server")
    #protocol_log = logging.getLogger("pymodbus.protocol")

    """ Server launcher """
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option("-D", "--debug",
                    help="Turn on to enable tracing",
                    action="store_true", dest="debug", default=False)
    (opt, arg) = parser.parse_args()

    # enable debugging information
    if opt.debug:
        try:
            _logger.setLevel(logging.DEBUG)
        except Exception:
            print "Logging is not supported on this system"

    # Create store context
    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)

    identity = ModbusDeviceIdentification()
    identity.VendorName  = 'Pymodbus'
    identity.ProductCode = 'PM'
    identity.VendorUrl   = 'http://unipi.technology'
    identity.ProductName = 'Pymodbus Server on IOLoop'
    identity.ModelName   = 'Pymodbus Server'
    identity.MajorMinorRevision = '1.0'

    StartTcpServer(context, identity=identity, address=("localhost", 5020)) 
Beispiel #13
0
def init():
    slaves = {
        UNIT:
        ModbusSlaveContext(di=ModbusSequentialDataBlock(0, [17] * 100),
                           co=ModbusSequentialDataBlock(0, [17] * 100),
                           hr=ModbusSequentialDataBlock(0, [17] * 100),
                           ir=ModbusSequentialDataBlock(0, [17] * 100))
    }
    context = ModbusServerContext(slaves=slaves, single=False)

    identity = ModbusDeviceIdentification()
    identity.VendorName = 'HAXOM'
    identity.ProductCode = 'SIMU-ICS-PORTAIL'
    identity.VendorUrl = 'https://github.com/haxom/'
    identity.ProductName = 'SIMU-ICS'
    identity.ModelName = 'PORTAIL'
    identity.MajorMinorRevision = '1.0.0'

    print 'Launching Modbus server, listening on %s:%d' % (listen_int,
                                                           listen_port)
    StartTcpServer(context,
                   identity=identity,
                   address=(listen_int, listen_port))
Beispiel #14
0
def run_custom_db_server(address, port):
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #
    coil_block = ModbusSequentialDataBlock(1, [0] * 256)
    discrete_input_block = ModbusSequentialDataBlock(10001, [0] * 256)
    input_register_block = ModbusSequentialDataBlock(30001, register_data)
    holding_register_block = ModbusSequentialDataBlock(40001, register_data)
    store = ModbusSlaveContext(di=discrete_input_block,
                               co=coil_block,
                               hr=holding_register_block,
                               ir=input_register_block,
                               zero_mode=True)
    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.3.0'

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #

    # p = Process(target=device_writer, args=(queue,))
    # p.start()
    StartTcpServer(context,
                   identity=identity,
                   address=(address, port),
                   framer=ModbusRtuFramer)
Beispiel #15
0
def run_update_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #


    store = ModbusSlaveContext(
        di=ModbusSequentialDataBlock(0,range(1,101)),
        co=ModbusSequentialDataBlock(0,range(101,201)),
        hr=ModbusSequentialDataBlock(0,range(201,301)),
        ir=ModbusSequentialDataBlock(0,range(301,401)))

    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'

    # connect to simulation
    HOST = '127.0.0.1'
    PORT = 55555
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))
    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    time = 1  # 5 seconds delay
    loop = LoopingCall(f=updating_writer, a=(context,sock))
    loop.start(time, now=False)  # initially delay by time
    StartTcpServer(context, identity=identity, address=(product_ip_address, modbusTCP_port))
Beispiel #16
0
def run_updating_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #

    store = ModbusSlaveContext(
        di=ModbusSequentialDataBlock(0, [17] * 1),
        co=ModbusSequentialDataBlock(0, [17] * 1),
        hr=ModbusSequentialDataBlock(1, [17] * 20),
        ir=ModbusSequentialDataBlock(0, [17] * 1))




    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 = 5  # 5 seconds delay
    loop = LoopingCall(f=updating_writer, a=(context,))
    loop.start(time, now=False)  # initially delay by time
    StartSerialServer(context, identity=identity, port='/dev/ttyUSB0', framer=ModbusRtuFramer, stopbits=2, parity='none', baudrate=9600, UnitId=0x01, ignore_missing_slaves=True)
Beispiel #17
0
def run_server():

    cc_store = ModbusSlaveContext(
        di = ModbusSequentialDataBlock(0,  [30] * 100), # discrete input space
        co = ModbusSequentialDataBlock(0,  [40] * 100), # c  o  space
        hr = ModbusSequentialDataBlock(0, [0] * 81) , # 
        ir = ModbusSequentialDataBlock(0,  [50] * 100),
        ) # input registers space

    rb_store = ModbusSlaveContext(
        di = ModbusSequentialDataBlock(0,  [30] * 100), # discrete input space
        co = ModbusSequentialDataBlock(0,  [40] * 100), # c  o  space
        hr = ModbusSequentialDataBlock(0, [1] * 20) , # 
        ir = ModbusSequentialDataBlock(0,  [50] * 100),
        ) # input registers space


    store = {0x01 : cc_store , 0x09 : rb_store }

    context = ModbusServerContext(slaves=store, single=False)

    identity = ModbusDeviceIdentification()
    identity.VendorName  = 'Gionji'
    identity.ProductCode = 'AGB'
    identity.VendorUrl   = 'http://github.com/riptideio/pymodbus/'
    identity.ProductName = 'Pymodbus Server Sim'
    identity.ModelName   = 'Pymodbus  Sim '
    identity.MajorMinorRevision = '0.1'

    # UPDATER
    time = 1
    updater = updaterThread(context, updating_writer)
    updater.start()

    #updating_writer(context)

    StartTcpServer(context, identity=identity, address=("", 5020))
Beispiel #18
0
def run_payload_server():
    # ----------------------------------------------------------------------- #
    # build your payload
    # ----------------------------------------------------------------------- #
    builder = BinaryPayloadBuilder(byteorder=Endian.Little)
    # builder.add_string('abcdefgh')
    # builder.add_32bit_float(22.34)
    # builder.add_16bit_uint(4660)
    # builder.add_8bit_int(18)
    builder.add_bits([0, 1, 0, 1, 1, 0, 1, 0])

    # ----------------------------------------------------------------------- #
    # use that payload in the data store
    # ----------------------------------------------------------------------- #
    # Here we use the same reference block for each underlying store.
    # ----------------------------------------------------------------------- #

    block = ModbusSequentialDataBlock(1, builder.to_registers())
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    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/bashwork/pymodbus/'
    identity.ProductName = 'Pymodbus Server'
    identity.ModelName = 'Pymodbus Server'
    identity.MajorMinorRevision = '1.0'
    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
def run_server():

    slaves = {
        0x01: ModbusSlaveContext(
        di=ModbusSequentialDataBlock(0, [17]*100),
        co=ModbusSequentialDataBlock(0, [17]*100),
        hr=ModbusSequentialDataBlock(0, [17]*100),
        ir=ModbusSequentialDataBlock(0, [17]*100)),
        0x02: ModbusSlaveContext(
        di=ModbusSequentialDataBlock(0, [17]*100),
        co=ModbusSequentialDataBlock(0, [17]*100),
        hr=ModbusSequentialDataBlock(0, [17]*100),
        ir=ModbusSequentialDataBlock(0, [17]*100)),
        0x03: ModbusSlaveContext(
        di=ModbusSequentialDataBlock(0, [17]*100),
        co=ModbusSequentialDataBlock(0, [17]*100),
        hr=ModbusSequentialDataBlock(0, [17]*100),
        ir=ModbusSequentialDataBlock(0, [17]*100)),
    }
    
    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 = 'KMU'
    identity.ProductCode = 'PM'
    identity.VendorUrl = ''
    identity.ProductName = 'For packet sniffing test'
    identity.ModelName = ''
    identity.MajorMinorRevision = '2.3.0'

    StartTcpServer(context, identity=identity, address=("192.168.70.128", 502))
def run_server():
    store = ModbusSlaveContext(di=ModbusSequentialDataBlock(0, [0] * 10000),
                               co=ModbusSequentialDataBlock(0, [0] * 10000),
                               hr=ModbusSequentialDataBlock(0, [0] * 10000),
                               ir=ModbusSequentialDataBlock(0, [0] * 10000))

    context = ModbusServerContext(slaves=store, single=True)
    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'
    #-----------------------------------------------------
    print("debug started\n\n")

    print(dir(store))
    store.setValues(3, 53, [30000])

    print("\n\ndebug finished")
    #-----------------------------------------------------
    print("Listening on {}:{}".format(HOST, PORT))
    StartTcpServer(context, identity=identity, address=(HOST, PORT))
Beispiel #21
0
##b2.pack()
##t = tk.Text(window,height=2)
##t.pack()
##window.mainloop()

from pymodbus.server. async import StartTcpServer
from pymodbus.server. async import StartUdpServer
from pymodbus.server. async 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 logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
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)
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Python Server'
identity.MajorMinorRevision = '1.0'
StartTcpServer(context, identity=identity, address=("127.0.0.1", 5020))
Beispiel #22
0
#########################################
# Modbus Server Code
#########################################

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)

identity = ModbusDeviceIdentification()
identity.VendorName = 'MockPLCs'
identity.ProductCode = 'MP'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'MockPLC 3000'
identity.ModelName = 'MockPLC Ultimate'
identity.MajorMinorRevision = '1.0'


def startModbusServer():

    StartTcpServer(context,
                   identity=identity,
                   address=("localhost", MODBUS_SERVER_PORT))


def main():
    reactor.callInThread(runWorld)
    startModbusServer()
Beispiel #23
0
    # enable debugging information
    if opt.debug:
        try:
            _logger.setLevel(logging.DEBUG)
        except Exception, e:
            print "Logging is not supported on this system"

    # Create store context
    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)

    identity = ModbusDeviceIdentification()
    identity.VendorName  = 'Pymodbus'
    identity.ProductCode = 'PM'
    identity.VendorUrl   = 'http://unipi.technology'
    identity.ProductName = 'Pymodbus Server on IOLoop'
    identity.ModelName   = 'Pymodbus Server'
    identity.MajorMinorRevision = '1.0'

    StartTcpServer(context, identity=identity, address=("localhost", 5020)) 


if __name__ == '__main__':
    main()

    if reactor.running:
        reactor.callFromThread(reactor.stop)

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)

# Modbus PLC server information
identity = ModbusDeviceIdentification()
identity.VendorName  = 'Simmons Oil Refining Platform'
identity.ProductCode = 'SORP'
identity.VendorUrl   = 'http://simmons.com/markets/oil-gas/pages/refining-industry.html'
identity.ProductName = 'SORP 3850'
identity.ModelName   = 'Simmons ORP 3850'
identity.MajorMinorRevision = '2.09.01'

def startModbusServer():
    # Run a modbus server on specified address and modbus port (5020)
    StartTcpServer(context, identity=identity, address=(args.server_addr, MODBUS_SERVER_PORT))

def main():
    reactor.callInThread(run_world)
    startModbusServer()

if __name__ == '__main__':
    sys.exit(main())
Beispiel #25
0
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 = '2.2.0'

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    # Tcp:
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
Beispiel #26
0
    def run_server(self):

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

        slaves = {
            0x00:
            ModbusSlaveContext(
                di=CustomModbusSequentialDataBlock(0, [17] * 100),
                co=CustomModbusSequentialDataBlock(0, [1] * 100),
                hr=CustomModbusSequentialDataBlock(0, [17] * 100),
                ir=CustomModbusSequentialDataBlock(0, [17] * 100)),
            0x01:
            ModbusSlaveContext(
                di=CustomModbusSequentialDataBlock(0, [17] * 100),
                co=CustomModbusSequentialDataBlock(0, [0] * 100),
                hr=CustomModbusSequentialDataBlock(0, [17] * 100),
                ir=CustomModbusSequentialDataBlock(0, [17] * 100)),
            0x02:
            ModbusSlaveContext(
                di=CustomModbusSequentialDataBlock(0, [30] * 100),
                co=CustomModbusSparseDataBlock({
                    0x00: 0,
                    0x05: 1
                }),
                hr=CustomModbusSequentialDataBlock(0, [17] * 100),
                ir=CustomModbusSequentialDataBlock.create()),
            0x03:
            ModbusSlaveContext(
                di=CustomModbusSequentialDataBlock(0, [13] * 1),
                co=CustomModbusSequentialDataBlock(0, [1] * 23),
                hr=CustomModbusSequentialDataBlock(0, [65] * 18),
                ir=CustomModbusSequentialDataBlock(0, [178] * 56)),
            0x04:
            ModbusSlaveContext(
                di=CustomModbusSequentialDataBlock(6, [17] * 100),
                co=CustomModbusSequentialDataBlock(2, [0] * 100),
                hr=CustomModbusSequentialDataBlock(45, [17] * 100),
                ir=CustomModbusSequentialDataBlock(33, [17] * 100)),
            0x05:
            ModbusSlaveContext(
                di=CustomModbusSequentialDataBlock(0, [42] * 100),
                co=CustomModbusSequentialDataBlock(0, [1] * 100),
                hr=CustomModbusSequentialDataBlock(0, [76] * 100),
                ir=CustomModbusSequentialDataBlock(0, [32] * 100)),
            0xFF:
            ModbusSlaveContext(
                di=CustomModbusSequentialDataBlock(0, [17] * 100),
                co=CustomModbusSequentialDataBlock(0, [1] * 100),
                hr=CustomModbusSequentialDataBlock(0, [17] * 100),
                ir=CustomModbusSequentialDataBlock(0, [17] * 100))
        }

        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 = Config.modbus.vendor_name
        identity.ProductCode = Config.modbus.product_code
        identity.VendorUrl = Config.modbus.vendor_url
        identity.ProductName = Config.modbus.product_name
        identity.ModelName = Config.modbus.model_name
        identity.MajorMinorRevision = Config.modbus.major_minor_revision
        identity.UserApplicationName = Config.modbus.user_application_name

        # ----------------------------------------------------------------------- #
        # run the server
        # ----------------------------------------------------------------------- #
        StartTcpServer(self,
                       context,
                       identity=identity,
                       address=(self._address, self._port),
                       transport=self._transport)
Beispiel #27
0
    def _start_rtu_server(self, framer=ModbusRtuFramer):
        # @req an open and existing /tmp/pts0 is required
        #---------------------------------------------------------------------------#
        # initialize your data store
        #---------------------------------------------------------------------------#
        # The datastores only respond to the addresses that they are initialized to.
        # Therefore, if you initialize a DataBlock to addresses from 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 you may use a seperate 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, [True] * 8),  # discrete inputs
            co=ModbusSequentialDataBlock(0, [False] * 8),  # coils
            hr=ModbusSequentialDataBlock(0, [0] * 8),  # holding regs
            ir=ModbusSequentialDataBlock(0, list(range(8))),  # input regs
            zero_mode=True)  # request(0-7) will map to the address (0-7)
        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/bashwork/pymodbus/'
        identity.ProductName = 'Pymodbus Server'
        identity.ModelName = 'Pymodbus Server'
        identity.MajorMinorRevision = '1.0'

        #---------------------------------------------------------------------------#
        # run the server you want
        #---------------------------------------------------------------------------#
        #StartTcpServer(context, identity=identity, address=("localhost", 5020))
        #StartUdpServer(context, identity=identity, address=("localhost", 502))
        StartSerialServer(context,
                          identity=identity,
                          port=self.serialPort,
                          baudrate=19200,
                          framer=framer,
                          broadcast_enable=True)
    context[slave_id].setValues(register, address, values)

#---------------------------------------------------------------------------# 
# initialize your data store
#---------------------------------------------------------------------------# 
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)

#---------------------------------------------------------------------------# 
# initialize the server information
#---------------------------------------------------------------------------# 
identity = ModbusDeviceIdentification()
identity.VendorName  = 'Christian Wichmann'
identity.ProductCode = 'TEMP2MB'
identity.VendorUrl   = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'Temperature sensor over Modbus'
identity.ModelName   = 'Temperature sensor over Modbus'
identity.MajorMinorRevision = '1.0'

#---------------------------------------------------------------------------# 
# run the server you want
#---------------------------------------------------------------------------# 
time = 1
loop = LoopingCall(f=updating_writer, a=(context,))
loop.start(time, now=False) # initially delay by time
StartTcpServer(context, identity=identity)#, address=('localhost', 5020))
Beispiel #29
0
def run_server(modbus_type, port):
    # ----------------------------------------------------------------------- #
    # 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 you may use a seperate 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)
    # ----------------------------------------------------------------------- #

    #block = ModbusSequentialDataBlock(0x00, [16]*0xff)
    coils_block = ModbusSparseDataBlock({1: 0, 2: 1, 3: 0, 4: 1})

    registers_block = ModbusSparseDataBlock({
        # this block is to test 32bits
        1: 0xC28F,  # PDU0 - BE
        2: 0xC20D,
        3: 0x8FC2,  # PDU2 - MBE
        4: 0x0DC2,
        5: 0xC20D,  # PDU4 - MLE
        6: 0xC28F,
        7: 0x0DC2,  # PDU6 - LE
        8: 0x8FC2,
        #
        9: 0xC28F,  # PDU8 - same as (PDU0 - BE)
        10: 0xC20D,
        11: 0xC28F,  # PDU0 - same as (PDU0 - BE)
        12: 0xC20D,

        # test int32
        13: 0xFFFF,  # PDU12
        14: 0xFDCE,

        # this block is to test 64bits
        # BE
        15: 0xBFBF,  # PDU14
        16: 0x9A6B,
        17: 0x50B0,
        18: 0xF27C,

        # LE
        19: 0x7CF2,  # PDU18
        20: 0xB050,
        21: 0x6B9A,
        22: 0xBFBF,

        # MLE
        23: 0xF27C,  # PDU22
        24: 0x50B0,
        25: 0x9A6B,
        26: 0xBFBF,

        # MBE
        27: 0xBFBF,  # PDU26
        28: 0x6B9A,
        29: 0xB050,
        30: 0x7CF2
    })
    store = ModbusSlaveContext(di=coils_block,
                               co=coils_block,
                               hr=registers_block,
                               ir=registers_block)

    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:
    if (modbus_type == 'TCP'):
        StartTcpServer(context, identity=identity, address=("0.0.0.0", port))
    elif (modbus_type == 'TCP_RTU'):
        # TCP with different framer
        StartTcpServer(context,
                       identity=identity,
                       framer=ModbusRtuFramer,
                       address=("0.0.0.0", port))
Beispiel #30
0
def run(host, port, database='modled', disable_ledstrip=False, debug=False):

    if debug:
        logger.setLevel(logging.DEBUG)

    # store = ModbusSlaveContext(
    #     hr=ModbusSequentialDataBlock(0, [17]*10)
    # )

    # context = ModbusServerContext(
    #     slaves=store,
    #     single=True
    # )

    # NOTE: currently we don't do anything with the block, although it's given in the
    # example usage at https://github.com/riptideio/pymodbus/blob/2ef91e9e565b10fc9abc0840c87cf4a29f3d9bbf/examples/common/dbstore_update_server.py
    # The code for initialization seems a bit off, because the block values are NOT used for initialisation of the
    # SQLite database when the SqlSlaveContext is created. Perhaps this requires a bug fix in the _create_db function?
    # We should probably parse all the kwargs for blocks, these should be added by default.
    block = ModbusSequentialDataBlock(
        1, [17] * 10)  # TODO: set some sensible defaults here

    # NOTE: below we're defining our modled.sqlite3 database (on disk) and table (modled) that
    # pymodbus should use to write its values to. Initialisation of the ModbusSequentialDataBlock is
    # ignored by the SqlSlaveContext for some reason (bug?). We don't have any values at the start,
    # so, trying to read and/or write from/to these addresses will fail. We can manually initialise the
    # database though. The schema is as follows:
    #
    # 1 table, with three columns: type, index and value
    #
    # type: varchar(1), h is for Holding Registers, which is what we need; others are d, c and i? See IModbusSlaveContext.
    # index: the address of the register; I've observed a difference of 1 between Modbus Doctor and SQLite (address = address + 1, unconditionally)
    # value: the value that is stored at the address
    #
    # So, as an example, we can read from register 1 using Modbus Doctor, we would need to
    # query for type 'h', address 1 (translated to 2 by SqlSlaveContext)
    #
    # Solutions to fixing the initialisation:
    #
    #  1) fix the SqlSlaveContext implementation (best), including the address mode
    #  2) override _create_db function locally and make sure that we can parse the block (good)
    #  3) prefil the SQLite database, with the values we want when it does not exist (easiest?)

    unit = 1  # NOTE: unit functions like an identifier for a slave
    store = ModLedSqlSlaveContext(database=database)
    store.initialize(
        hr=block
    )  # NOTE: we're initializing with a block for Holding Registers only now.
    context = ModbusServerContext(
        slaves={
            unit: store
        },  # NOTE: Currently the SqlSlaveContext does not seem to support multiple slaves? How to distinguish?
        single=False)

    def determine_configuration():

        function = 3  # read holding registers
        address = 0
        count = 10

        values = context[unit].getValues(function, address, count)
        logger.debug("Values from datastore: " + str(values))

        a40001, a40002, a40003, a40004, a40005, a40006, a40007, a40008 = values[
            1:9]  # take 8 values
        on = (a40001 & 1 << 0 != 0)  # zero'th bit
        fixed = (a40001 & 1 << 1 != 0)  # first bit set
        rainbow = (a40001 & 1 << 2 != 0)  # second bit set
        strand_test = (a40001 & 1 << 3 != 0)  # third bit set
        red = a40002
        green = a40003
        blue = a40004
        number_of_leds = a40005
        brightness = a40006
        pin = a40007

        # TODO: programs to add: theaterChase, theaterChaseRainbow, rainbowCycle?
        rainbow_cycle = False
        theater_chase = False
        theater_chase_rainbow = False

        program = None
        if fixed:
            program = 'fixed'
        if rainbow:
            program = 'rainbow'
        if strand_test:
            program = 'strand_test'
        if rainbow_cycle:
            program = 'rainbow_cycle'
        if theater_chase:
            program = 'theater_chase'
        if theater_chase_rainbow:
            program = 'theater_chase_rainbow'
        if not program:
            program = 'fixed'  # TODO: decide whether we should go off instead in case no program determined?

        configuration = {
            'on': on,
            'red': red,
            'green': green,
            'blue': blue,
            'number_of_leds': number_of_leds,
            'brightness': brightness,
            'pin': pin,
            'program': program
        }

        return configuration

    configuration = determine_configuration()

    # NOTE: initializing the Modbus server identification
    identity = ModbusDeviceIdentification()
    identity.VendorName = 'hslatman'
    identity.ProductCode = 'MLS'
    identity.VendorUrl = 'https://github.com/hslatman/modled'
    identity.ProductName = 'ModLed Server'
    identity.ModelName = 'ModLed X'
    identity.MajorMinorRevision = '0.1.0'

    signal_queue = queue.Queue()
    controller = ModLedController(configuration=configuration,
                                  queue=signal_queue,
                                  disable_ledstrip=disable_ledstrip)
    controller.start()

    def handler(sender, **kwargs):

        # TODO: do something with the address and value in kwargs
        # TODO: determine whether a reset of the ledstrip is required? e.g. first a clear, for some programs?
        # TODO: restart the controller process

        new_configuration = determine_configuration()
        old_configuration = controller.getConfiguration()

        logger.debug(f"Old configuration: {old_configuration}")
        logger.debug(f"New configuration: {new_configuration}")

        should_signal = False
        if new_configuration['on'] != old_configuration['on']:
            should_signal = True
        if new_configuration['program'] != old_configuration['program']:
            should_signal = True
        if new_configuration['program'] == 'fixed':
            if new_configuration['red'] != old_configuration['red']:
                should_signal = True
            if new_configuration['green'] != old_configuration['green']:
                should_signal = True
            if new_configuration['blue'] != old_configuration['blue']:
                should_signal = True

        # TODO: additional logic for signaling for the other programs to add

        program = new_configuration['program']
        logger.debug(f"program to run next: {program}")

        controller.updateConfiguration(
            new_configuration
        )  # NOTE: we're writing value to a thread, but it's pretty safe to do so at this point

        logger.debug(f"Should signal: {should_signal}")
        if should_signal:
            logger.debug('signaling to trigger an exception')
            value = {'address': kwargs['address'], 'value': kwargs['value']}
            signal_queue.put(value)

    control_signal.connect(handler)

    # NOTE: starting the server with custom LedstripControlRequest
    StartTcpServer(context,
                   identity=identity,
                   address=(host, port),
                   custom_functions=[
                       SingleLedstripControlRequest,
                       MultipleLedstripControlRequest
                   ],
                   defer_reactor_run=True)

    # NOTE: registering an additional looping task on the Twisted reactor
    # TODO: look into https://github.com/riptideio/pymodbus/blob/master/examples/common/dbstore_update_server.py
    # for an example using SQLite and reading values from the Modbus context; we could inject the context into
    # the controller.loop() call as an argument, read the values, react to that, store it in the controller.
    # Otherwise we could to a different loop, extract values and inject them into the controller. We need to
    # check whether the context is thread safe. We're only reading, so it's relatively safe. Otherwise we would
    # need to inject the values using a queue, for example. Downside is that it's not really reactive, but based
    # on polling the values. The custom LedstripControlRequest approach could lead to a more reactive integration.
    # controller_loop = task.LoopingCall(controller.loop)
    # controller_loop.start(5.0)

    def log_sigint(event):
        if event.get("log_text") == 'Received SIGINT, shutting down.':
            logger.debug("Stopping for: ", event)
            controller.stop()
            controller.join()
            # if reactor.running:
            #     reactor.stop()

    # NOTE: we're adding an observer that checks for SIGINT; we can then stop the controller properly
    log.addObserver(log_sigint)

    # NOTE: starting the Twisted reactor
    logger.debug('starting server')
    reactor.run()
Beispiel #31
0
# initialize your data store
#---------------------------------------------------------------------------#
store = ModbusSlaveContext(di=ModbusSequentialDataBlock(0, [9] * 100),
                           co=ModbusSequentialDataBlock(0, [9] * 100),
                           hr=ModbusSequentialDataBlock(0, [9] * 100),
                           ir=ModbusSequentialDataBlock(0, [9] * 100))
context = ModbusServerContext(slaves=store, single=True)

#---------------------------------------------------------------------------#
# initialize the server information
#---------------------------------------------------------------------------#
identity = ModbusDeviceIdentification()
identity.VendorName = 'San Joaquin Valley Air Pollution Control District and pymodbus'
identity.ProductCode = 'ZAG'
identity.VendorUrl = ' www.valleyair.org and http://github.com/bashwork/pymodbus/'
identity.ProductName = 'ZAG Server'
identity.ModelName = 'pymodbus ZAG Server'
identity.MajorMinorRevision = '1.0'

#---------------------------------------------------------------------------#
# run the server you want
#---------------------------------------------------------------------------#
x = 0
time = 0.5  # 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.1.135",
    502))  #because port 502 is being used this program must be ran as sudo

#Agilaire IP Address: 192.168.1.135 Port:502
Beispiel #32
0
# Modbus Server Code
#########################################

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)

identity = ModbusDeviceIdentification()
identity.VendorName  = 'IO ANALYTICA'
identity.ProductCode = 'IOMP'
identity.VendorUrl   = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'IOPLC 3000'
identity.ModelName   = 'IOPLC Ultimate'
identity.MajorMinorRevision = '1.0'

context = ModbusServerContext(slaves=store, single=True)

def startModbusServer():
    StartTcpServer(context, identity=identity, address=(MODBUS_SERVER_IP, MODBUS_SERVER_PORT))

def main():
    reactor.callInThread(runWorld)
    startModbusServer()
    log.info("QUIT")
    return 0

Beispiel #33
0
from pymodbus.server.sync import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext

import logging

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

identity = ModbusDeviceIdentification()
identity.VendorName = 'Joac-Automation'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/joac/ArakurWW/'
identity.ProductName = 'Servidor Test Arakur'
identity.ModelName = 'Servidor Test Arakur'
identity.MajorMinorRevision = '0.1'

marcas = ModbusSequentialDataBlock(0, [0] * 34)
registros = ModbusSequentialDataBlock(0, [0] * 34)



store = ModbusSlaveContext(di = marcas, co= marcas, hr = registros, ir =registros)

context = ModbusServerContext(slaves=store, single=True)


StartTcpServer(context, identity=identity, address=("localhost", 5020))
Beispiel #34
0
def run_server(host, port):
    store = ModbusDynamicSlaveContext()
    # around 1300 rpm
    lambda_functions_rpm = [
        lambda t: floor(1240 + (t.timestamp() % 120 + random.randint(-2, 5))) *
        1000 >> 16, lambda t: floor(1240 +
                                    (t.timestamp() % 120 + random.randint(
                                        -2, 5))) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51300, lambda_functions_rpm)

    # around 60c
    lambda_functions_oiltemp = [
        lambda t: floor(55 + (t.timestamp() % 120 + random.randint(-2, 5))
                        / 12) * 1000 >> 16, lambda t: floor(55 + (t.timestamp(
                        ) % 120 + random.randint(-2, 5)) / 12) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51460, lambda_functions_oiltemp)

    # around 5 bar
    lambda_functions_oilpressure = [
        lambda t: floor(490 + (t.timestamp() % 120 + random.randint(
            -2, 5) / 10)) * 1000 >> 16, lambda t: floor(490 + (t.timestamp(
            ) % 120 + random.randint(-2, 5) / 10)) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51426, lambda_functions_oilpressure)

    # constantly running since 2019-11-04
    lambda_functions_engine_hours = [
        lambda t: floor((t.timestamp() - 1572869165) / 36) >> 16,
        lambda t: floor((t.timestamp() - 1572869165) / 36) & 0xFFFF
    ]
    store.setLambda(4, 51360, lambda_functions_engine_hours)

    # around 80c
    lambda_functions_coolanttemp = [
        lambda t: floor(90 - (t.timestamp() % 120 + random.randint(-2, 5))
                        / 12) * 1000 >> 16, lambda t: floor(90 - (t.timestamp(
                        ) % 120 + random.randint(-2, 5)) / 12) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51414, lambda_functions_coolanttemp)

    # around 1 bar
    lambda_functions_coolantpressure = [
        lambda t: floor(110 - (t.timestamp() % 120 + random.randint(-2, 5))
                        / 10) * 1000 >> 16, lambda t: floor(110 - (t.timestamp(
                        ) % 120 + random.randint(-2, 5)) / 10) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51606, lambda_functions_coolantpressure)

    # around 2 bar
    lambda_functions_boostpressure = [
        lambda t: floor(190 + (t.timestamp() % 120 + random.randint(
            -2, 5) / 10)) * 1000 >> 16, lambda t: floor(190 + (t.timestamp(
            ) % 120 + random.randint(-2, 5) / 10)) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51408, lambda_functions_boostpressure)

    # around 20c
    lambda_functions_intaketemp = [
        lambda t: 0, lambda t: floor(19500 + t.timestamp() % 1000)
    ]
    store.setLambda(4, 51440, lambda_functions_intaketemp)

    # around 50%
    lambda_functions_load = [
        lambda t: 0, lambda t: floor((1240 +
                                      (t.timestamp() % 120)) / 2600 * 1000)
    ]
    store.setLambda(4, 51422, lambda_functions_load)

    # around 350c
    lambda_functions_exhaust_temp = [
        lambda t: floor(340 + (t.timestamp() % 120 + random.randint(-2, 5))
                        / 10) * 1000 >> 16, lambda t: floor(340 + (t.timestamp(
                        ) % 120 + random.randint(-2, 5)) / 10) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51442, lambda_functions_exhaust_temp)

    # around 60c
    lambda_functions_transmissionoiltemp = [
        lambda t: floor(50 + (t.timestamp() % 240 + random.randint(-2, 5))
                        / 12) * 1000 >> 16, lambda t: floor(50 + (t.timestamp(
                        ) % 240 + random.randint(-2, 5)) / 12) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51454, lambda_functions_transmissionoiltemp)

    # around 15bar
    lambda_functions_transmissionoilpressure = [
        lambda t: floor(1490 + (t.timestamp() % 120 + random.randint(
            -2, 5) / 10)) * 1000 >> 16, lambda t: floor(1490 + (t.timestamp(
            ) % 120 + random.randint(-2, 5) / 10)) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51452, lambda_functions_transmissionoilpressure)

    # using 100l/h since 2019-11-04
    lambda_functions_fuelused = [
        lambda t: floor((t.timestamp() - 1572869165) / 36 * 1000) >> 16,
        lambda t: floor((t.timestamp() - 1572869165) / 36 * 1000) & 0xFFFF
    ]
    store.setLambda(4, 51372, lambda_functions_fuelused)

    # around 100l/h
    lambda_functions_fuelrate = [
        lambda t: floor(97 + (t.timestamp() % 120 + random.randint(-2, 5))
                        / 20) * 1000 >> 16, lambda t: floor(97 + (t.timestamp(
                        ) % 120 + random.randint(-2, 5)) / 20) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51436, lambda_functions_fuelrate)

    # around 2.8 bar
    lambda_functions_fuelpressure = [
        lambda t: floor(290 - (t.timestamp() % 120 + random.randint(
            -2, 5) / 10)) * 1000 >> 16, lambda t: floor(290 - (t.timestamp(
            ) % 120 + random.randint(-2, 5) / 10)) * 1000 & 0xFFFF
    ]
    store.setLambda(4, 51432, lambda_functions_fuelpressure)

    context = ModbusServerContext(slaves=store, single=True)

    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.2.0'

    StartTcpServer(context, identity=identity, address=(host, port))
Beispiel #35
0
def run_server():
    store = ModbusSlaveContext(di=ModbusSequentialDataBlock(0, [0] * 10000),
                               co=ModbusSequentialDataBlock(0, [0] * 10000),
                               hr=ModbusSequentialDataBlock(0, [0] * 10000),
                               ir=ModbusSequentialDataBlock(0, [0] * 10000))

    context = ModbusServerContext(slaves=store, single=True)
    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'
    #-----------------------------------------------------
    # print("debug started\n\n")

    # print(dir(store))
    store.setValues(3, 53, [30000])
    store.setValues(3, 32, [14373])
    store.setValues(3, 33, [28911])
    store.setValues(3, 61, [59626])
    store.setValues(3, 26, [22288])
    store.setValues(3, 89, [59530])
    store.setValues(3, 90, [22198])
    store.setValues(3, 2, [27306])
    store.setValues(3, 10, [24285])
    store.setValues(3, 52, [9160])
    store.setValues(3, 32, [8707])
    store.setValues(3, 74, [41718])
    store.setValues(3, 78, [40553])
    store.setValues(3, 93, [44444])
    store.setValues(3, 65, [45136])
    store.setValues(3, 24, [39191])

    store.setValues(2, 1, [1])
    store.setValues(2, 12, [1])
    store.setValues(2, 101, [1])
    store.setValues(2, 8, [1])
    store.setValues(2, 94, [1])
    store.setValues(2, 23, [1])
    store.setValues(2, 34, [1])
    store.setValues(2, 65, [1])
    store.setValues(2, 66, [1])
    store.setValues(2, 67, [1])
    store.setValues(2, 97, [1])
    store.setValues(2, 99, [1])
    store.setValues(2, 14, [1])
    store.setValues(2, 76, [1])

    store.setValues(1, 1, [1])
    store.setValues(1, 11, [1])
    store.setValues(1, 21, [1])
    store.setValues(1, 31, [1])
    store.setValues(1, 41, [1])
    store.setValues(1, 42, [1])
    store.setValues(1, 101, [1])
    store.setValues(1, 129, [1])
    store.setValues(1, 259, [1])
    store.setValues(1, 111, [1])
    store.setValues(1, 192, [1])

    store.setValues(4, 0, [22])
    store.setValues(4, 19, [69])
    store.setValues(4, 40, [99])
    store.setValues(4, 51, [14])
    store.setValues(4, 17, [35])
    store.setValues(4, 28, [24])
    store.setValues(4, 54, [31])
    store.setValues(4, 7, [84])
    store.setValues(4, 12, [31])
    store.setValues(4, 43, [7])
    store.setValues(4, 53, [54])
    store.setValues(4, 2, [69])
    store.setValues(4, 35, [38])
    store.setValues(4, 53, [50])
    store.setValues(4, 17, [99])

    # print("\n\ndebug finished")
    #-----------------------------------------------------
    print("Listening on {}:{}".format(HOST, PORT))
    StartTcpServer(context, identity=identity, address=(HOST, PORT))
def main(args):
    # for test get the server parameters and test data from the test database
    db = dbfn.db("../db.sqlite3")
    test_params = db.getParams(site=args.site)
    db.close()

    db = dbfn.db("../test.sqlite3")
    #q_test_params = "SELECT {cols} from test_params where id  = ?"
    #cols = ["id","modbus_servers", "field_name"]
    #test_params = db.getColDict( q_test_params, cols, (args.test, ) )
    #print(test_params)
    q_data = "select key, value from test_data where site = ? and test = ? order by seq"
    test_val = db.getRowDict(q_data, (args.site, args.test))
    #print(test_val)
    #q_limit = "select key, match_type from test_data where test = ?"
    #test_limit = db.getRowDict(q_limit, (args.test, ) )
    #print(test_limit)
    db.close()

    # based on test server parameter load the serer details from the main database
    #load server details
    db = dbfn.db("../db.sqlite3")
    #print(params)
    #db.close()
    store = dict()
    #registers = dict()
    unit_map = dict()

    print(test_params["modbus_servers"])

    for s in test_params["modbus_servers"].split(","):
        server = int(s)
        params = db.getConnectionParams(server)
        if params["unit"] not in unit_map:
            unit_map[params["unit"]] = dict()

        section = db.getDataFormat(server, 0)

        registers = make_block(section, test_val, test_params,
                               params['start_address'])
        unit_map[params["unit"]][params['start_address']] = registers

    print(unit_map)
    data = dict()
    for u in unit_map:
        for start_address in unit_map[u]:
            print("Address:", u, start_address)
            for x in range(len(unit_map[u][start_address])):
                print(x, unit_map[u][start_address][x])
                data[start_address + x + 1] = unit_map[u][start_address][x]

        print(data)
        block = ModbusSparseDataBlock(data)

        store1 = ModbusSlaveContext(
            di=ModbusSequentialDataBlock(0, [15] * 10),
            co=ModbusSequentialDataBlock(0, [115] * 10),
            hr=block,
            ir=ModbusSequentialDataBlock(0, [215] * 10))

        store[params["unit"]] = store1
    db.close()

    context = ModbusServerContext(slaves=store, single=False)

    #for k in store:
    #    print(k)
    #    print(context[k])

    #print("CTX", context)
    for s in context:
        print("********************Slave", s)

    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.2.0'
    print("Starting Server at:", params["port"])
    StartTcpServer(context,
                   identity=identity,
                   address=("localhost", params["port"]))
Beispiel #37
0
        'VendorUrl': "",
        'ProductName': "",
        'ModelName': "Model",
        'MajorMinorRevision': "1.0"
    },
}

print "Liste des signature : "
affichagesignature(dico)
i = demandeobligatoire("Quelle signature voulez vous utiliser ?", "int")

identity = ModbusDeviceIdentification()
identity.VendorName = dico[i]['VendorName']
identity.ProductCode = dico[i]['ProductCode']
identity.VendorUrl = dico[i]['VendorUrl']
identity.ProductName = dico[i]['ProductName']
identity.ModelName = dico[i]['ModelName']
identity.MajorMinorRevision = dico[i]['MajorMinorRevision']

#---------------------------------------------------------------------------#
# run the server you want
#---------------------------------------------------------------------------#
# Tcp:
StartTcpServer(context, identity=identity, address=("localhost", 502))

# Udp:
#StartUdpServer(context, identity=identity, address=("localhost", 502))

# Ascii:
#StartSerialServer(context, identity=identity, port='/dev/pts/3', timeout=1)
Beispiel #38
0
#     }
#     context = ModbusServerContext(slaves=slaves, single=False)
# ---------------------------------------------------------------------------#
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/bashwork/pymodbus/"
identity.ProductName = "Pymodbus Server"
identity.ModelName = "Pymodbus Server"
identity.MajorMinorRevision = "1.0"

# ---------------------------------------------------------------------------#
# run the server you want
# ---------------------------------------------------------------------------#
StartTcpServer(context, identity=identity, address=("localhost", 5020))
# StartUdpServer(context, identity=identity, address=("localhost", 502))
# StartSerialServer(context, identity=identity, port='/dev/pts/3', timeout=1)
Beispiel #39
0
            ir = ir)
        context = ModbusServerContext(slaves=store, single=True)
        
        return context  


#---------------------------------------------------------------------------# 
# initialize the server information
#---------------------------------------------------------------------------# 
# If you don't set this or any fields, they are defaulted to empty strings.
#---------------------------------------------------------------------------# 
identity = ModbusDeviceIdentification()
identity.VendorName  = 'VOLTTRON'
identity.ProductCode = 'VT'
identity.VendorUrl   = 'http://github.com/VOLTTRON/volttron'
identity.ProductName = 'VOLTTRON Modbus Test Device'
identity.ModelName   = 'VOLTTRON Modbus Test Device'
identity.MajorMinorRevision = '1.0'

abstraction = DeviceAbstraction(args.config)

#Create the deamon as soon as we've loaded the device configuration.
if not args.no_daemon:
    createDaemon()
    
context = abstraction.get_server_context()

#---------------------------------------------------------------------------# 
# run the server you want
#---------------------------------------------------------------------------# 
StartTcpServer(context, identity=identity, address=(args.interface, args.port))
#---------------------------------------------------------------------------# 
# initialize 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 = 'ZXL'
identity.ProductCode = 'PLC'
identity.VendorUrl = 'https://github.com/zxlin/Modbus-PLC-Simulator'
identity.ProductName = 'PLC-Sim'
identity.ModelName = 'Modbus-Server'
identity.MajorMinorRevision = '1.0'

#---------------------------------------------------------------------------# 
# Start running the server
#---------------------------------------------------------------------------#
# time = 5
# loop = LoopingCall(f=updating_writer, a=(context,))
# loop.start(time, now=False)
StartTcpServer(context, identity=identity, address=(server_address, server_port))
Beispiel #41
0
import logging

from pymodbus.datastore import ModbusServerContext
from pymodbus.device import ModbusDeviceIdentification

import a40
import tcp_gateway

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)

slaves = {
    0x01: a40.create(),
    0x02: a40.create(),
    0x03: a40.create()
}

context = ModbusServerContext(slaves=slaves, single=False)

identity = ModbusDeviceIdentification()
identity.VendorName  = 'Socomec'
identity.ProductName = 'Dirus'
identity.ModelName   = 'A40'

tcp_gateway.start(context, identity=identity, address=("localhost", 5020))
                                 number_of_registers_to_populate),
    ir=ModbusSequentialDataBlock(starting_register_offset,
                                 [default_register_value] *
                                 number_of_registers_to_populate))

# Populate the modbus server with this single modbus slave
simulated_modbus_server_context = ModbusServerContext(
    slaves=simulated_modbus_slave_context,
    single=create_only_a_single_modbus_slave)

# Initialize the server information
simulated_modbus_server_identity = ModbusDeviceIdentification()
simulated_modbus_server_identity.VendorName = 'pymodbus'
simulated_modbus_server_identity.ProductCode = 'PM'
simulated_modbus_server_identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
simulated_modbus_server_identity.ProductName = 'pymodbus Server'
simulated_modbus_server_identity.ModelName = 'pymodbus Server'
simulated_modbus_server_identity.MajorMinorRevision = '1.0'

try:
    # Print Bluetooth scanning status
    log.debug("'Bluetooth device scanning enabled' setting:")
    log.debug(BLUETOOTH_DEVICE_SCANNING_ENABLED)

    # Initialize the thread that will start updating our Modbus server's registers
    CONTINUE_UPDATING_MODBUS_REGISTERS = True
    update_registers_thread = Thread(target=update_modbus_registers,
                                     args=(simulated_modbus_server_context, ))
    update_registers_thread.daemon = True
    update_registers_thread.start()
Beispiel #43
0
server_ip = {}
client_ip = {}

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)


identity = ModbusDeviceIdentification()
identity.VendorName  = 'Facility Sensor System'
identity.ProductCode = 'FSS'
identity.VendorUrl   = 'http://www.wehaveyourback.com'
identity.ProductName = 'PLC Sensor Server'
identity.ModelName   = 'Sensor Server 5000'
identity.MajorMinorRevision = '3.a1'



def controller_server():
    StartTcpServer(context, identity=identity, address=(server_ip['ip'], int(server_ip['port'])))

def controller_client():
    print "Client"
    depend = {}
    if "actuators" in arduino_modules['config']:
        for i in arduino_modules['config']["actuators"]:
            b = arduino_modules['config']["actuators"][i]
            print i
Beispiel #44
0
        reactor.callFromThread(reactor.stop)


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)

# Modbus PLC server information
identity = ModbusDeviceIdentification()
identity.VendorName = 'Simmons Oil Refining Platform'
identity.ProductCode = 'SORP'
identity.VendorUrl = 'http://simmons.com/markets/oil-gas/pages/refining-industry.html'
identity.ProductName = 'SORP 3850'
identity.ModelName = 'Simmons ORP 3850'
identity.MajorMinorRevision = '2.09.01'


def startModbusServer():
    # Run a modbus server on specified address and modbus port (5020)
    StartTcpServer(context,
                   identity=identity,
                   address=(args.server_addr, MODBUS_SERVER_PORT))


def main():
    reactor.callInThread(run_world)
    startModbusServer()
Beispiel #45
0
#! /usr/bin/env python3
"""Asynchronous Modbus Server Build in Python3 using the pyModbus module."""

from pymodbus.server.asynchronous import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext

# create a datastore and populate it with test data
store = ModbusSlaveContext(
    di=ModbusSequentialDataBlock(0, [17] * 100),  # Discrete inputs initializer
    co=ModbusSequentialDataBlock(0, [17] * 100),  # Coils initializer
    hr=ModbusSequentialDataBlock(0,
                                 [17] * 100),  # Holding register initializer
    ir=ModbusSequentialDataBlock(0, [17] * 100))  # Input register initializer

context = ModbusServerContext(slaves=store, single=True)

# Populate the Modbus server information fields, these gert returned as responses to identity queries
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'https://github.com/riptideio/pyModbus'
identity.ProductName = 'Modbus Server'
identity.MajorMinorRevision = '1.0'

# Start the listening server
print('Starting Modbus server...')
StartTcpServer(context, identity=identity, address=('0.0.0.0', 502))
from pymodbus.server.async import StartTcpServer
from pymodbus.server.async import StartUdpServer
from pymodbus.server.async import StartSerialServer

from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer

#Logging
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

#Slave addresses to store data.
store = ModbusSlaveContext(
    di = ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)

identity = ModbusDeviceIdentification()
identity.VendorName  = 'TTC'
identity.ProductCode = 'PredixPark'
identity.ProductName = 'PredixPark'
identity.ModelName   = 'PredixPark'
identity.MajorMinorRevision = '1.0'

#Might require sudo.
StartTcpServer(context, identity=identity, address=("localhost", 502))
Beispiel #47
0
            pass
        except Exception, E:
            logger.debug(str(E))
            pass

    def status_callback(self, device):
        try:
            device._modbus_handle.sync(device, self.bits, self.regs)
        except AttributeError:
            pass
        except Exception,e :
            #print str(e)
            pass


## small version of Modbus map, limited to Gpio devices
class UnipiContextGpio(UnipiContext):

    devicemap = { # count coil-pos reg-pos  alt-reg-pos 
    'ao'    : (AoHandle   (1,      0,      1),),
    'input' : (InputHandle(14,     1,      2,      3),),
    }

identity = ModbusDeviceIdentification()
identity.VendorName  = 'Unipi Technology'
identity.ProductCode = 'Evok'
identity.VendorUrl   = 'http://unipi.technology'
identity.ProductName = 'Evok Modbus/TCP Server on Tornado'
identity.ModelName   = 'Evok Modbus'
identity.MajorMinorRevision = '1.1'
Beispiel #48
0
        start += 1
        print "byte", False, start, count
        hr = ModbusSequentialDataBlock(start, [0] * count)

        store = ModbusSlaveContext(di=di, co=co, hr=hr, ir=ir)
        context = ModbusServerContext(slaves=store, single=True)

        return context


#---------------------------------------------------------------------------#
# initialize the server information
#---------------------------------------------------------------------------#
# If you don't set this or any fields, they are defaulted to empty strings.
#---------------------------------------------------------------------------#
identity = ModbusDeviceIdentification()
identity.VendorName = 'VOLTTRON'
identity.ProductCode = 'VT'
identity.VendorUrl = 'http://github.com/VOLTTRON/volttron'
identity.ProductName = 'VOLTTRON Modbus Test Device'
identity.ModelName = 'VOLTTRON Modbus Test Device'
identity.MajorMinorRevision = '1.0'

abstraction = DeviceAbstraction(args.config)
context = abstraction.get_server_context()

#---------------------------------------------------------------------------#
# run the server you want
#---------------------------------------------------------------------------#
StartTcpServer(context, identity=identity, address=("localhost", args.port))
Beispiel #49
0
def run_server(opt):
    global gp10block
    global gp40block

    store = {}
    if opt['gp10']['enable'] is True:
        gp10block = Gp10ModbusSlave(opt['gp10']['deviceid'], **opt['gp10'])
        store[opt['gp10']['deviceid']] = gp10block.store

    if opt['gp40']['enable'] is True:
        gp40block = Gp40ModbusSlave(opt['gp40']['deviceid'], **opt['gp40'])
        store[opt['gp40']['deviceid']] = gp40block.store

    if 0 == len(store):
        print("ERR: enable GP10 or GP40.")
        return

    context = ModbusServerContext(slaves=store, 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         = 'RatocSystems, Inc.'
    identity.ProductCode        = 'RPi-Modbus'
    identity.VendorUrl          = 'https://github.com/ratocsystems'
    identity.ProductName        = 'RasPi Modbus Server'
    identity.ModelName          = 'RasPi Modbus Server'
    identity.MajorMinorRevision = '1.0'

    # ----------------------------------------------------------------------- #
    # updater
    # ----------------------------------------------------------------------- #
    updater_500ms = LoopingCall(f=write_context_500ms, a=(context,))
    updater_500ms.start(.5)
    updater_1000ms = LoopingCall(f=write_context_1000ms, a=(context,))
    updater_1000ms.start(1)
    writer = LoopingCall(f=read_context, a=(context,))
    writer.start(.1)

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    if 'tcp' == opt['common']['protocol']:
        # Tcp:
        StartTcpServer(context, identity=identity, address=(opt['tcp']['host'], opt['tcp']['port']))

    elif 'ascii' == opt['common']['protocol']:
        # Ascii:
        StartSerialServer(context, identity=identity, port=opt['serial']['device'], timeout=1, baudrate=opt['serial']['baudrate'])

    elif 'rtu' == opt['common']['protocol']:
        # RTU:
        StartSerialServer(context, framer=ModbusRtuFramer, identity=identity, port=opt['serial']['device'], timeout=.005, baudrate=opt['serial']['baudrate'])

    else:
        print("ERR: select protocol tcp, rtu or ascii")

    # ----------------------------------------------------------------------- #
    # end proc
    # ----------------------------------------------------------------------- #
    updater_500ms.stop()
    updater_1000ms.stop()
    writer.stop()

    if gp10block is not None:
        del gp10block
    if gp40block is not None:
        del gp40block
Beispiel #50
0
    from pymodbus.server.async import ModbusServerFactory
    from pymodbus.constants import Defaults
    from pymodbus.device import ModbusDeviceIdentification
    from pymodbus.datastore import ModbusSequentialDataBlock
    from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
    from twisted.internet import reactor

    # ------------------------------------------------------------
    # initialize the identity
    # ------------------------------------------------------------

    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'

    # ------------------------------------------------------------
    # initialize the datastore
    # ------------------------------------------------------------
    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 factory 
###############################################################################
# Modbus Datastore Configuration
###############################################################################

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)

identity = ModbusDeviceIdentification()
identity.VendorName = 'ITI'
identity.ProductCode = 'PM'
identity.VendorUrl = 'code.iti.illinois.edu'
identity.ProductName = 'Server Instance'
identity.ModelName = 'ITI Test'
identity.MajorMinorRevision = '1.0'

###############################################################################
# Functions
###############################################################################



def validateIface(iface):
    if not (iface in netifaces.interfaces()):
        print iface + " is not a valid interface"
        exit()

"""validateIP
Beispiel #52
0
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 devs 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 devs 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 = '2.3.0'

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    # Tcp:
    # StartTcpServer(context, identity=identity, address=("192.168.0.119", 5020))
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
    MODBUS_DATA_COLLECTIONS['COILS_COLLECTION'] = CB_CONFIG['outputCoilsCollection']
    MODBUS_DATA_COLLECTIONS['CONTACTS_COLLECTION'] = CB_CONFIG['inputContactsCollection']
    MODBUS_DATA_COLLECTIONS['INPUT_REGISTERS_COLLECTION'] = CB_CONFIG['inputRegisterCollection']
    MODBUS_DATA_COLLECTIONS['OUTPUT_REGISTERS_COLLECTION'] = CB_CONFIG['outputRegisterCollection']

    #Start Modbus Server
    # 1. Create Modbus Server Context
    context = ClearBladeModbusServerContext(cbsystem=CB_SYSTEM, cbauth=CB_AUTH, \
        zero_mode=CB_CONFIG['modbusZeroMode'])

    # 2. Create Modbus Device Identification
    identity = ModbusDeviceIdentification()
    identity.VendorName = 'ClearBlade'
    identity.ProductCode = 'CB'
    identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
    identity.ProductName = 'ClearBlade Modbus Server Adapter'
    identity.ModelName = 'ClearBlade Modbus Server Adapter'
    identity.MajorMinorRevision = '1.0'

    try:
        # 3. Run the Start TCP Server Command
        logging.info("Starting Modbus TCP server")
        StartTcpServer(context, identity=identity, address=("localhost", CB_CONFIG['modbusPort']))
        pass
    except KeyboardInterrupt:
        EXIT_APP = True
        #CB_MQTT.disconnect()
        sys.exit(0)
    except Exception as e:
        logging.info("EXCEPTION:: %s", str(e))
Beispiel #54
0
def run_callback_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #
    log.info(
        "MQTT2Modbus Server initing---------------------------------------------------"
    )
    config.read('config.ini')
    redis_srv = config.get('redis', 'url')
    mqtt_srv = (config.get('mqtt', 'host'), config.getint('mqtt', 'port'),
                config.getint('mqtt', 'keepalive'), config.get('mqtt', 'user'),
                config.get('mqtt', 'pwd'))
    mbs_cfg = (config.get('mbServ', 'host'), config.getint('mbServ', 'port'))
    log_level = config.get('log', 'level')
    Authcode = config.get('cloud', 'Authcode')

    level = logging.getLevelName(log_level)
    log.setLevel(level)
    redis_rtdb = redis.Redis.from_url(redis_srv + "/12")

    gates_list = get_devices_list("device_mapping.csv")
    # print("gates_list", gates_list)
    queue = Queue()
    devices = read_device_map("device_mapping.csv")
    # print("devices", devices)
    tag_addr = tag_addr_map("device_mapping.csv")
    tag_datatype = tag_datatype_map("device_mapping.csv")
    tag_rw = tag_rw_map("device_mapping.csv")
    # print("tag_addr", tag_addr)
    # print("tag_datatype", tag_datatype)

    writer = Worker(log, "http://ioe.thingsroot.com", Authcode)
    writer.start()
    block = CallbackDataBlock(devices, (tag_addr, tag_datatype, tag_rw),
                              redis_rtdb, gates_list, writer)

    # block = CallbackDataBlock(devices, (tag_addr, tag_datatype, tag_rw), redis_rtdb, gates_list, queue)
    # print("block", block)
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    context = ModbusServerContext(slaves=store, single=True)

    redis_rtdb.connection_pool.disconnect()
    # ----------------------------------------------------------------------- #
    # initialize the server information
    # ----------------------------------------------------------------------- #
    identity = ModbusDeviceIdentification()
    identity.VendorName = 'thingsroot'
    identity.ProductCode = 'MBS'
    identity.VendorUrl = 'http://cloud.thingsroot.com/'
    identity.ProductName = 'thingsroot modbus Server'
    identity.ModelName = 'thingsroot modbus Server'
    identity.MajorMinorRevision = '1.0'

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    # time = 2  # 5 seconds delay
    # loop = LoopingCall(f=updating_writer, a=(block, tag_addr, tag_datatype, redis_rtdb, gates_list))
    # loop.start(time, now=False)  # initially delay by time

    # sub = SubClient(mqttcfg=mqtt_srv, mbcfg=(block, tag_addr, tag_datatype, gates_list))
    # sub.start()

    # p = Process(target=device_writer, args=(queue, tag_datatype))
    # p.start()

    log.info("Starting the MQTT2Modbus Server")
    StartTcpServer(context, identity=identity, address=mbs_cfg)
Beispiel #55
0
#########################################
# Modbus Server Code
#########################################

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)

identity = ModbusDeviceIdentification()
identity.VendorName  = 'MockPLCs'
identity.ProductCode = 'MP'
identity.VendorUrl   = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'MockPLC 3000'
identity.ModelName   = 'MockPLC Ultimate'
identity.MajorMinorRevision = '1.0'

def startModbusServer():

    StartTcpServer(context, identity=identity, address=("localhost", MODBUS_SERVER_PORT))

def main():
    reactor.callInThread(runWorld)
    startModbusServer()

if __name__ == '__main__':
    sys.exit(main())