def main():

    args = parse_settings()

    if args.verbose:
        print args

    # arduino_dev_port = "/dev/ttyUSB0"  # COM port on win
    # listen_conf = ("192.168.0.104", 10503)
    listen_conf = (args.listen_address, args.listen_port)

    store = ModbusSlaveContext(di=ModbusSequentialDataBlock(0, [False] * 20),
                               co=ModbusSequentialDataBlock(0, [False] * 20),
                               hr=ModbusSequentialDataBlock(0, [3] * 20),
                               ir=ModbusSequentialDataBlock(0, [4] * 20))

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

    identity = ModbusDeviceIdentification()
    identity.VendorName = 'SCADALiaris'
    # identity.ProductCode = 'RealPLC 1'
    identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
    identity.ProductName = 'pymodbus Server'
    identity.ModelName = 'pymodbus Server'
    identity.MajorMinorRevision = 'v0.5'

    time = args.poll_interval
    if not args.random:

        if args.rpi:
            rpi = Rpi1Wire()

            identity.ProductCode = 'RPiPLC 1'
            loop = LoopingCall(f=rpi_plc, a=(context, rpi, args))
            loop.start(time, now=False)
            StartTcpServer(context, identity=identity, address=listen_conf)

        else:

            try:
                serial_port = serial.Serial(port=args.serial_port,
                                            baudrate=115200,
                                            bytesize=8,
                                            parity=serial.PARITY_NONE,
                                            stopbits=1)
            except serial.SerialException as ex:
                print "ERROR", ex
                sys.exit(-1)
            identity.ProductCode = 'ArduinoPLC 1'
            loop = LoopingCall(f=arduino_plc, a=(context, serial_port, args))
            loop.start(time, now=False)
            StartTcpServer(context, identity=identity, address=listen_conf)

    else:
        identity.ProductCode = 'RandomPLC 1'
        loop = LoopingCall(f=random_plc, a=(context, args))
        loop.start(time, now=False)
        StartTcpServer(context, identity=identity, address=listen_conf)
Example #2
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 = '1.0'

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

    # p = Process(target=device_writer, args=(queue,))
    # p.start()
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
Example #3
0
def main():
    """ Server launcher """
    parser = OptionParser()
    parser.add_option("-c",
                      "--conf",
                      help="The configuration file to load",
                      dest="file")
    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:
            server_log.setLevel(logging.DEBUG)
            protocol_log.setLevel(logging.DEBUG)
        except Exception as e:
            print("Logging is not supported on this system")

    # parse configuration file and run
    try:
        conf = Configuration(opt.file)
        StartTcpServer(context=conf.parse())
    except ConfigurationException as err:
        print(err)
        parser.print_help()
Example #4
0
def run_async_server():
    store_feed1 = ModbusSlaveContext(
        di=ModbusSequentialDataBlock(0, [17]*100),
        co=ModbusSequentialDataBlock(0, [17]*100),
        hr=ModbusSequentialDataBlock(0, [17]*100),
        ir=ModbusSequentialDataBlock(0, [17]*100))
    context_feed1 = ModbusServerContext(slaves=store_feed1, single=True)
    
    # ----------------------------------------------------------------------- # 
    # initialize the server information
    # ----------------------------------------------------------------------- # 
    # If you don't set this or any fields, they are defaulted to empty strings.
    # ----------------------------------------------------------------------- # 
    identity_feed1 = ModbusDeviceIdentification()
    identity_feed1.VendorName = 'Pymodbus'
    identity_feed1.ProductCode = 'PM'
    identity_feed1.VendorUrl = 'http://github.com/bashwork/pymodbus/'
    identity_feed1.ProductName = 'Pymodbus Server'
    identity_feed1.ModelName = 'Pymodbus Server'
    identity_feed1.MajorMinorRevision = '1.0'
    
     
      
    # ----------------------------------------------------------------------- # 
    # run the server you want
    # ----------------------------------------------------------------------- # 
    
    StartTcpServer(context_feed1, identity=identity_feed1, address=("192.168.95.10", 502))
Example #5
0
def run_callback_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #
    queue = Queue()
    devices = {}
    temp = get_temp_c()

    devices[1] = temp  # thermostat BT
    devices[2] = 0  # heater
    devices[3] = 0  # fan

    block = CallbackDataBlock(devices, queue)
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    context = ModbusServerContext(slaves=store, single=True)

    identity = ModbusDeviceIdentification()
    identity.VendorName = 'nick_labs'
    identity.ProductCode = 'PM'
    identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
    identity.ProductName = 'poppycock Server'
    identity.ModelName = 'poppycock Server'
    identity.MajorMinorRevision = '1.0'

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    p = Process(target=device_handler, args=(queue, ))
    p.start()
    StartTcpServer(context, identity=identity, address=("0.0.0.0", 5020))
Example #6
0
def run_updating_server():
    # ----------------------------------------------------------------------- # 
    # 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 = 'dreams by Eqinov'
    identity.ProductName = 'demo pilotage wattsense'
    identity.MajorMinorRevision = '1.0'
    
    # ----------------------------------------------------------------------- # 
    # run the server you want
    # ----------------------------------------------------------------------- # 
    timeRead = 1  # 1 second delay
    readLoop = LoopingCall(f=read_context, a=(context,))
    readLoop.start(timeRead, now=False) # initially delay by time	
	
    timeWrite = 30  # 1 second delay
    writeLoop = LoopingCall(f=write_context, a=(context,))
    writeLoop.start(timeWrite, now=False) # initially delay by time	
    StartTcpServer(context, identity=identity, address=("0.0.0.0", 5020))
Example #7
0
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 = '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
    StartTcpServer(context, identity=identity, address=("", 5020))
Example #8
0
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()
Example #9
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']))
Example #10
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 = 'DYODEv2'
    identity.VendorUrl = 'http://github.com/wavestone-cdt/dyode'
    identity.ProductName = 'DYODE'
    identity.ModelName = 'Very Low Cost @ BlackHat Arsenal'
    identity.MajorMinorRevision = '1.0'

    #--------------------------------------------------------------------------#
    # run the server you want
    #--------------------------------------------------------------------------#
    time = 1  # 1 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_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 = '1.0'

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    time = 1  # 1 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.3", 502))
Example #12
0
 def start(self):
     context = ModbusServerContext(slaves={1: self._store}, single=False)
     loop = LoopingCall(f=self.updating_writer,
                        modbus_server_context=(context, ))
     loop.start(self.time, now=False)  # initially delay by time
     StartTcpServer(context,
                    address=(self.config["modbusserver"]["ip"],
                             self.config["modbusserver"]["port"]))
Example #13
0
 def testTcpServerStartup(self):
     ''' Test that the modbus tcp async server starts correctly '''
     with patch('twisted.internet.reactor') as mock_reactor:
         if IS_PYTHON3:
             console = False
             call_count = 1
         else:
             console = True
             call_count = 2
         StartTcpServer(context=None, console=console)
         self.assertEqual(mock_reactor.listenTCP.call_count, call_count)
         self.assertEqual(mock_reactor.run.call_count, 1)
    def run(self, mode, tcpport=5020, baud=9600, rtuport=None):

        # ----------------------------------------------------------------------- #
        # run the server you want
        # ----------------------------------------------------------------------- #
        # time = 1  # 5 seconds delay
        # loop = LoopingCall(f=updating_writer, a=(context,))
        # loop.start(time, now=False)  # initially delay by time

        if mode == MODBUS_MODE_RTU:
            print("@@@@@@@ Starting ModBus Server  %s @ %d" % (rtuport, baud))
            StartSerialServer(self.serverContext,
                              framer=ModbusRtuFramer,
                              identity=self.modbusIdentity,
                              port=rtuport,
                              timeout=.05,
                              baudrate=baud)

        elif modbus_server_mode == MODBUS_MODE_TCP:
            StartTcpServer(self.serverContext,
                           identity=self.modbusIdentity,
                           address=("", tcpport))
Example #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=(tank_ip_address, modbusTCP_port))
Example #16
0
    def main(self):

        log.debug("[PLC][%s] Initialized" % self.name)
        while not self.registered:
            log.debug("[PLC][%s] Trying to register with scadasim rpc" %
                      self.name)
            try:
                self._registerPLC()
            except KeyError:
                log.warn(
                    """[PLC][%s] PLC not found within scadasim. Verify Docker
                     Compose container names match list of plcs in scadasim
                     config""")

            time.sleep(1)

        log.debug("[PLC][%s] Starting update service" % self.name)
        self.update()

        log.debug("[PLC][%s] Starting MODBUS Server" % self.name)
        StartTcpServer(self.context,
                       identity=self.identity,
                       address=("0.0.0.0", 502))
Example #17
0
        rr = client.read_input_registers(0, IR_NUM)
        context[SLAVE_ID].store['i'] = ModbusSequentialDataBlock(
            0, [
                0,
            ] + rr.registers[:IR_NUM])
        print context[SLAVE_ID].store['i'].values
    except:
        log.warn('Cannot read IR')
    log.info('Copied from modbus server #1')


# Override ModbusSlaveContext to hook our function
class myModbusSlaveContext(ModbusSlaveContext):
    def setValues(self, fx, address, values):
        super(myModbusSlaveContext, self).setValues(fx, address, values)
        log.warn('Someone set values! %s, %s, %s', str(fx), str(address),
                 str(values))


# Initialize ModBus Context
store = myModbusSlaveContext(di=ModbusSequentialDataBlock(0, [0] * DI_NUM),
                             co=ModbusSequentialDataBlock(0, [0] * CO_NUM),
                             hr=ModbusSequentialDataBlock(0, [0] * HR_NUM),
                             ir=ModbusSequentialDataBlock(0, [0] * IR_NUM))
context = ModbusServerContext(slaves=store, single=True)

# Start loop
loop = LoopingCall(f=copy_modbus_source, a=(context, ))
loop.start(TIME_TO_COPY, now=True)
StartTcpServer(context, identity=identity(), address=('192.168.42.2', 502))
Example #18
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))
Example #19
0
                      action="store_true",
                      dest="debug",
                      default=False)
    (opt, arg) = parser.parse_args()

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

    # parse configuration file and run
    try:
        conf = Configuration(opt.file)
        StartTcpServer(context=conf.parse())
    except ConfigurationException, err:
        print err
        parser.print_help()


#---------------------------------------------------------------------------#
# Main jumper
#---------------------------------------------------------------------------#
if __name__ == "__main__":
    if root_test():
        main()
    else:
        print "This script must be run as root!"
Example #20
0
def startModbusServer():

    StartTcpServer(context,
                   identity=identity,
                   address=("localhost", MODBUS_SERVER_PORT))
def run_async_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 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) # 0-255
    #
    # 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(  # creates modbus data model, each data access stored in own personal block
        di=(0, [17] * 100),  # discrete inputs init
        co=ModbusSequentialDataBlock(0, [17] * 100),  # coils 
        hr=ModbusSequentialDataBlock(0, [17] * 100),  # holding reg
        ir=ModbusSequentialDataBlock(0, [17] * 100))  # input reg
    context = ModbusServerContext(slaves=store, single=True)
    # if single is set to true, it will be treated as a single context so every unit-id returns the same context. If single is set to false, it will be interpreted as a collection of slave contexts.

    # ----------------------------------------------------------------------- #
    # initialize the server information
    # ----------------------------------------------------------------------- #
    # If you don't set this or any fields, they are defaulted to empty strings.
    # ----------------------------------------------------------------------- #
    identity = ModbusDeviceIdentification(
    )  # used to supply the readDevice function
    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
    # ----------------------------------------------------------------------- #

    # TCP Server

    StartTcpServer(context, identity=identity, address=("localhost", 5020))
Example #22
0
def startModbusServer():
    # Run a modbus server on specified address and modbus port (5020)
    StartTcpServer(context,
                   identity=identity,
                   address=(args.server_addr, MODBUS_SERVER_PORT))
Example #23
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
Example #24
0
class OutputCallbackDataBlock(ModbusSparseDataBlock):
    '''
    Outputs incoming data...
    '''
    def __init__(self, values):
        super(OutputCallbackDataBlock, self).__init__(values)

    def setValues(self, address, value):
        global CURRENT_TEMP
        print(CURRENT_TEMP, address, value)
        super(OutputCallbackDataBlock, self).setValues(address, value)
        if address == 1:
            CURRENT_TEMP = float(value[0]) / 10
            print('Value: {value}'.format(value=value))


block = OutputCallbackDataBlock([0] * 10)
store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
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 = 'pymodbus Server'
identity.MajorMinorRevision = '1.0'

StartTcpServer(context, identity=identity)  # , address=('192.168.24.40', 503))
Example #25
0
 def create_server(self, context_id=0):
     StartTcpServer(self.context[context_id],
                    identity=self.identity[context_id],
                    address=("0.0.0.0", 5020 + context_id))
Example #26
0
        hr=ModbusSequentialDataBlock(0, [0] * args.holding_registers),
        zero_mode=False,
    )

    # NOTE: use 0-based addressing mapped internally to 1-based
    context = ModbusServerContext(slaves=store, single=True)

    # TODO: server id 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'

    # NOTE: currently only implements mode 1
    if args.mode == 1:
        # NOTE: ip is a str, port is an int
        StartTcpServer(context,
                       identity=identity,
                       address=(args.ip, args.port))

    else:
        pass
    # StartUdpServer(context, identity=identity, address=("localhost", 502))
    # StartSerialServer(context, identity=identity, port='/dev/pts/3',
    #     framer=ModbusRtuFramer)
    # StartSerialServer(context, identity=identity, port='/dev/pts/3',
    #     framer=ModbusAsciiFramer)
Example #27
0
    #    values2[1] = 55
    log.debug("Valores esclavo2: " + str(values2))
    context[slave_id].setValues(register, address2, values2)


#---------------------------------------------------------------------------#
# inicializa el almacenamiento de datos
#---------------------------------------------------------------------------#
store = ModbusSlaveContext(
    di=ModbusSequentialDataBlock(
        0,
        [0] * 1),  #1 espacio de memoria reservado para las entradas discretas
    co=ModbusSequentialDataBlock(
        0, [0] * 1),  #Reserva la memoria rellenando con el valor [n]
    hr=ModbusSequentialDataBlock(
        0, [0] *
        1000),  #1000 espacios de memoria reservados para los holding register
    ir=ModbusSequentialDataBlock(0, [0] * 1))
context = ModbusServerContext(slaves=store, single=True)

#---------------------------------------------------------------------------#
# Corre el servidor
#---------------------------------------------------------------------------#
id = 1

time = 5  # 5 seconds delay
loop = LoopingCall(f=Actualizar_datos, a=(context, ))
loop.start(time, now=False)  # initially delay by time
StartTcpServer(context, address=("192.168.0.101", 502))
#StartTcpServer(context, address=("192.168.1.11", 5020))
Example #28
0
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

store = ModbusSlaveContext(
    di=ModbusSequentialDataBlock(0, [17] * 100),  # Discrete inputs initializer
    co=ModbusSequentialDataBlock(0, [17] * 100),  # Coild initializer
    hr=ModbusSequentialDataBlock(0,
                                 [17] * 100),  # Holding register initializer
    ir=ModbusSequentialDataBlock(0, [17] * 100))  # Input registers initializer
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

# Modbus over Ethernet via IP
StartTcpServer(context, identity=identity, address=("localhost", 502))
#StartUdpServer(context, identity=identity, address=("127.0.0.1", 502))

# Serial
#StartSerialServer(context, identity=identity, port='/dev/pts/3', framer=ModbusRtuFramer)
#StartSerialServer(context, identity=identity, port='/dev/pts/3', framer=ModbusAsciiFramer)
Example #29
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)
Example #30
0
    value = list()
    value.append(random.randint(1, 100))
    # print address, value[0]
    # values[1] = 20

    context[slave_id].setValues(4, address, value)

    ci_val = i % 2
    # print ci_val
    context[slave_id].setValues(2, 1, [ci_val])

    values = context[slave_id].getValues(4, 1, count=10)
    print "IR:", values, "(" + str(len(values)) + ")"

    output_registers = context[slave_id].getValues(3, 0, count=10)
    print "HR:", output_registers

    input_coils = context[slave_id].getValues(1, 0, count=10)
    print "DI:", input_coils

    output_coils = context[slave_id].getValues(2, 0, count=10)
    print "CO:", output_coils

    print "_" * 100


time = 2
loop = LoopingCall(f=update_writer, a=(context, ))
loop.start(time, now=False)
StartTcpServer(context, identity=identity, address=("192.168.0.104", 10502))