コード例 #1
0
 def testSerialServerClose(self):
     ''' test that the synchronous serial server closes correctly '''
     with patch.object(serial, 'Serial') as mock_serial:
         instance = mock_serial.return_value
         server = ModbusSerialServer(None)
         server.server_close()
         instance.close.assert_any_call()
コード例 #2
0
ファイル: test_server_sync.py プロジェクト: Biondoap/pymodbus
 def testSerialServerClose(self):
     ''' test that the synchronous serial server closes correctly '''
     with patch.object(serial, 'Serial') as mock_serial:
         instance = mock_serial.return_value
         server = ModbusSerialServer(None)
         server.server_close()
         instance.close.assert_any_call()
コード例 #3
0
ファイル: mock_tracerbn.py プロジェクト: jim-park/MontorHome
class MockTracerBN(threading.Thread):
    def __init__(self,
                 serial_port='/dev/pts/4',
                 json_device_desc_path=DEVICE_JSON_DESC_PATH):
        threading.Thread.__init__(self, name='MockTracerBN2')
        self._serial_port = serial_port

        # Build data backing store from json file.
        mappings = json_mapping_parser(json_device_desc_path)
        store = ModbusSlaveContext(di=ModbusSparseDataBlock(mappings['di']),
                                   co=ModbusSparseDataBlock(mappings['co']),
                                   ir=ModbusSparseDataBlock(mappings['ir']),
                                   hr=ModbusSparseDataBlock(mappings['hr']))
        identity = initialise_device_identity(mappings)
        context = ModbusServerContext(slaves=store, single=True)

        # RTU:
        self.server = ModbusSerialServer(context,
                                         framer=ModbusRtuFramer,
                                         identity=identity,
                                         port=self._serial_port,
                                         timeout=0.001,
                                         baudrate=115200)

    def run(self):
        self.server.serve_forever()

    def stop(self):
        if self.server.is_running:
            self.server.server_close()
            del self.server
コード例 #4
0
ファイル: modbussim.py プロジェクト: tiropp/cumulocity-sdk-c
class MBSerialServer(QThread):
    def __init__(self, port, unit, data, baud, par, sec, parent):
        super(MBSerialServer, self).__init__(parent)
        self.slave = MBSlave(ModbusSequentialDataBlock(1, data[0]),
                             ModbusSequentialDataBlock(1, data[1]),
                             ModbusSequentialDataBlock(1, data[2]),
                             ModbusSequentialDataBlock(1, data[3]))
        self.ctx = ModbusServerContext(slaves={unit: self.slave}, single=False)
        sb = par == 'N' and 2 or 1
        self.server = ModbusSerialServer(self.ctx,
                                         framer=MRF,
                                         port=port,
                                         stopbits=sb,
                                         bytesize=8,
                                         parity=par,
                                         baudrate=baud,
                                         timeout=sec)
        print(self.server)

    def run(self):
        self.server.serve_forever()

    def quit(self):
        self.server.server_close()
        super(MBSerialServer, self).quit()
コード例 #5
0
ファイル: modbusslave.py プロジェクト: GaryHsu77/modbus-utils
def run_rtu(args, server_context):
    server = ModbusSerialServer(
        context=server_context,
        framer=ModbusRtuFramer,
        port=args.path,
        baudrate=args.baud,
        timeout=0.005)
    server.serve_forever()
コード例 #6
0
 def testSerialServerServeForever(self):
     ''' test that the synchronous serial server closes correctly '''
     with patch.object(serial, 'Serial') as mock_serial:
         with patch('pymodbus.server.sync.ModbusSingleRequestHandler') as mock_handler:
             server = ModbusSerialServer(None)
             instance = mock_handler.return_value
             instance.handle.side_effect = server.server_close
             server.serve_forever()
             instance.handle.assert_any_call()
コード例 #7
0
ファイル: test_server_sync.py プロジェクト: vincsdev/pymodbus
 def testSerialServerServeForever(self):
     ''' test that the synchronous serial server closes correctly '''
     with patch.object(serial, 'Serial') as mock_serial:
         with patch('pymodbus.server.sync.ModbusSingleRequestHandler') as mock_handler:
             server = ModbusSerialServer(None)
             instance = mock_handler.return_value
             instance.handle.side_effect = server.server_close
             server.serve_forever()
             instance.handle.assert_any_call()
コード例 #8
0
    def testSerialServerConnect(self):
        with patch.object(serial, 'Serial') as mock_serial:
            mock_serial.return_value = "socket"
            identity = ModbusDeviceIdentification(info={0x00: 'VendorName'})
            server = ModbusSerialServer(context=None, identity=identity)
            self.assertEqual(server.socket, "socket")
            self.assertEqual(server.control.Identity.VendorName, 'VendorName')

            server._connect()
            self.assertEqual(server.socket, "socket")

        with patch.object(serial, 'Serial') as mock_serial:
            mock_serial.side_effect = serial.SerialException()
            server = ModbusSerialServer(None)
            self.assertEqual(server.socket, None)
コード例 #9
0
def main():
    """ The main body of the emulator.

    This listens for incoming requests and processes them. It starts by
    initializing the context from config, then listening on the given
    serial device.
    """
    slaves = dict()
    for device in emulator_config['devices']:
        # for each device (unit), create an EmulatorDataBlock that has the register
        # map defined in config

        def _convert_register(v):  # pylint: disable=missing-docstring
            if isinstance(v, list):
                # return a list of converted values
                return [int(x, 16) for x in v]
            # convert single value to int
            return int(v, 16)

        block = EmulatorDataBlock({
            int(k, 16): _convert_register(v)
            for k, v in device['holding_registers'].items()
        })

        logger.error('Device: {} Block: {}'.format(device['device_address'],
                                                   block.values))
        store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
        slaves[device['device_address']] = store

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

    for slave in context:
        logger.error('Slaves: {}'.format(slave[0]))

    identity = ModbusDeviceIdentification()
    identity.VendorName = 'Vapor IO'
    identity.ProductName = 'Synse Modbus Emulator'
    identity.MajorMinorRevision = '1.4'

    # this is done to allow us to actually use RTU framing which the Start shortcut prevents
    server = ModbusSerialServer(context,
                                framer=ModbusRtuFramer,
                                identity=identity,
                                port=emulator_config['serial_device'],
                                timeout=0.01)
    server.serve_forever()
コード例 #10
0
 def __configureServer(self):
     if self.cfg["method"] == "tcp":
         self.servTCP = ModbusTcpServer(self.context,
                                        identity=self.identity,
                                        address=(self.__getIPAddress(),
                                                 self.cfg["tcpPort"]))
     elif self.cfg["method"] == "rtu":
         self.servRTU = ModbusSerialServer(self.context,
                                           framer=ModbusRtuFramer,
                                           identity=self.identity,
                                           port=self.cfg["rtuPort"],
                                           stopbits=self.cfg["stopbits"],
                                           bytesize=self.cfg["bytesize"],
                                           parity=self.cfg["parity"],
                                           baudrate=self.cfg["baudrate"],
                                           timeout=self.cfg["timeout"])
     else:
         raise ReferenceError("Invalid server type")
コード例 #11
0
    def testSerialServerConnect(self):
        with patch.object(serial, 'Serial') as mock_serial:
                # mock_serial.return_value = "socket"
                mock_serial.write = lambda x: len(x)
                mock_serial.read = lambda size: '\x00' * size
                identity = ModbusDeviceIdentification(info={0x00: 'VendorName'})
                server = ModbusSerialServer(context=None, identity=identity, port="dummy")
                # # mock_serial.return_value = "socket"
                # self.assertEqual(server.socket.port, "dummy")
                self.assertEquals(server.handler.__class__.__name__, "CustomSingleRequestHandler")
                self.assertEqual(server.control.Identity.VendorName, 'VendorName')

                server._connect()
                # self.assertEqual(server.socket, "socket")

        with patch.object(serial, 'Serial') as mock_serial:
            mock_serial.write = lambda x: len(x)
            mock_serial.read = lambda size: '\x00' * size
            mock_serial.side_effect = serial.SerialException()
            server = ModbusSerialServer(None, port="dummy")
            self.assertEqual(server.socket, None)
コード例 #12
0
 def __configureServer(self):
     if self.cfg["method"] == "tcp":
         self.servTCP = ModbusTcpServer(self.context, 
                                        identity=self.identity, 
                                        address=(self.__getIPAddress(),
                                                 self.cfg["tcpPort"]))
     elif self.cfg["method"] == "rtu":
         self.servRTU = ModbusSerialServer(self.context,
                                          framer=ModbusRtuFramer,
                                          identity=self.identity,
                                          port=self.cfg["rtuPort"],
                                          stopbits=self.cfg["stopbits"],
                                          bytesize=self.cfg["bytesize"],
                                          parity=self.cfg["parity"],
                                          baudrate=self.cfg["baudrate"],
                                          timeout=self.cfg["timeout"])
     else:
         raise ReferenceError("Invalid server type")
コード例 #13
0
ファイル: test_server_sync.py プロジェクト: vincsdev/pymodbus
    def testSerialServerConnect(self):
        with patch.object(serial, 'Serial') as mock_serial:
            mock_serial.return_value = "socket"
            identity = ModbusDeviceIdentification(info={0x00: 'VendorName'})
            server = ModbusSerialServer(context=None, identity=identity)
            self.assertEqual(server.socket, "socket")
            self.assertEqual(server.control.Identity.VendorName, 'VendorName')

            server._connect()
            self.assertEqual(server.socket, "socket")

        with patch.object(serial, 'Serial') as mock_serial:
            mock_serial.side_effect = serial.SerialException()
            server = ModbusSerialServer(None)
            self.assertEqual(server.socket, None)
コード例 #14
0
ファイル: test_server_sync.py プロジェクト: Biondoap/pymodbus
    def testSerialServerConnect(self):
        with patch.object(serial, 'Serial') as mock_serial:
            # mock_serial.return_value = "socket"
            mock_serial.write = lambda x: len(x)
            mock_serial.read = lambda size: '\x00' * size
            identity = ModbusDeviceIdentification(info={0x00: 'VendorName'})
            server = ModbusSerialServer(context=None,
                                        identity=identity,
                                        port="dummy")
            # # mock_serial.return_value = "socket"
            # self.assertEqual(server.socket.port, "dummy")
            self.assertEquals(server.handler.__class__.__name__,
                              "CustomSingleRequestHandler")
            self.assertEqual(server.control.Identity.VendorName, 'VendorName')

            server._connect()
            # self.assertEqual(server.socket, "socket")

        with patch.object(serial, 'Serial') as mock_serial:
            mock_serial.write = lambda x: len(x)
            mock_serial.read = lambda size: '\x00' * size
            mock_serial.side_effect = serial.SerialException()
            server = ModbusSerialServer(None, port="dummy")
            self.assertEqual(server.socket, None)
コード例 #15
0
class modbusServer():

    def __init__(self):
        self.__logging()
        self.cfg = yamlImport.importYAML("./cfg/modbusSettings.yaml")
        self.builder = BinaryPayloadBuilder(endian=Endian.Little)
        self.__setupContext()
        self.__serverInfo()
        self.__configureServer()

    def __logging(self):
        import logging
        logging.basicConfig()
        log = logging.getLogger()
        log.setLevel(logging.INFO)
    
    def __setupContext(self):
        #Setup Coils
        co = ModbusSequentialDataBlock(1, [0]*1)
        di = ModbusSequentialDataBlock(1, [0]*6)
        
        #Setup Registers (Inc floats)
        for i in range(0,3):
            self.builder.add_32bit_float(0.0)
        ir = ModbusSequentialDataBlock(1, self.builder.to_registers())
        
        for i in range(0,3):
            self.builder.add_32bit_float(0.0)
        hr = ModbusSequentialDataBlock(1, self.builder.to_registers())
        
        #Setup datastore
        store = ModbusSlaveContext(co=co,di=di,hr=hr,ir=ir)
        self.context = ModbusServerContext(slaves=store, single=True)


    def __serverInfo(self):
        self.identity = ModbusDeviceIdentification()
        self.identity.VendorName  = self.cfg["VendorName"]
        self.identity.VendorUrl   = self.cfg["VendorUrl"]
        self.identity.ProductName = self.cfg["ProductName"]
        self.identity.ModelName   = self.cfg["ModelName"]
        self.identity.MajorMinorRevision = self.cfg["Revision"]
    
    def __getIPAddress(self):
        if self.cfg["manualIP"] == "N":
            return socket.gethostbyname(socket.gethostname())
        return self.cfg["ip"]
    
    def __configureServer(self):
        if self.cfg["method"] == "tcp":
            self.servTCP = ModbusTcpServer(self.context, 
                                           identity=self.identity, 
                                           address=(self.__getIPAddress(),
                                                    self.cfg["tcpPort"]))
        elif self.cfg["method"] == "rtu":
            self.servRTU = ModbusSerialServer(self.context,
                                             framer=ModbusRtuFramer,
                                             identity=self.identity,
                                             port=self.cfg["rtuPort"],
                                             stopbits=self.cfg["stopbits"],
                                             bytesize=self.cfg["bytesize"],
                                             parity=self.cfg["parity"],
                                             baudrate=self.cfg["baudrate"],
                                             timeout=self.cfg["timeout"])
        else:
            raise ReferenceError("Invalid server type")
            
    def runServer(self):
        if self.cfg["method"] == "tcp":
            self.servTCP.serve_forever()
        elif self.cfg["method"] == "rtu":
            self.servRTU.serve_forever()
        else:
            raise ReferenceError("Invalid server type")
    
    def stopServer(self):
        if self.cfg["method"] == "tcp":
            self.servTCP.server_close()
            self.servTCP.shutdown()
        elif self.cfg["method"] == "rtu":
            self.servRTU.server_close()
        else:
            raise ReferenceError("Invalid server type")
        
    def encodeData(self,data):
        self.builder.reset()
        try:
            for i in range(0,len(data)):
                self.builder.add_32bit_float(data[i])
        except TypeError:
            self.builder.add_32bit_float(data)
        return self.builder.to_registers()
    
    def decodeData(self,data):
        returnData = [0]*(len(data)/2)
        decoder = BinaryPayloadDecoder.fromRegisters(data, endian=Endian.Little)
        for i in range(0,len(data)/2):
            returnData[i] = round(decoder.decode_32bit_float(),2)
        return returnData
コード例 #16
0
class modbusServer():
    def __init__(self):
        self.__logging()
        self.cfg = yamlImport.importYAML("./cfg/modbusSettings.yaml")
        self.builder = BinaryPayloadBuilder(endian=Endian.Little)
        self.__setupContext()
        self.__serverInfo()
        self.__configureServer()

    def __logging(self):
        import logging
        logging.basicConfig()
        log = logging.getLogger()
        log.setLevel(logging.INFO)

    def __setupContext(self):
        #Setup Coils
        co = ModbusSequentialDataBlock(1, [0] * 1)
        di = ModbusSequentialDataBlock(1, [0] * 6)

        #Setup Registers (Inc floats)
        for i in range(0, 3):
            self.builder.add_32bit_float(0.0)
        ir = ModbusSequentialDataBlock(1, self.builder.to_registers())

        for i in range(0, 3):
            self.builder.add_32bit_float(0.0)
        hr = ModbusSequentialDataBlock(1, self.builder.to_registers())

        #Setup datastore
        store = ModbusSlaveContext(co=co, di=di, hr=hr, ir=ir)
        self.context = ModbusServerContext(slaves=store, single=True)

    def __serverInfo(self):
        self.identity = ModbusDeviceIdentification()
        self.identity.VendorName = self.cfg["VendorName"]
        self.identity.VendorUrl = self.cfg["VendorUrl"]
        self.identity.ProductName = self.cfg["ProductName"]
        self.identity.ModelName = self.cfg["ModelName"]
        self.identity.MajorMinorRevision = self.cfg["Revision"]

    def __getIPAddress(self):
        if self.cfg["manualIP"] == "N":
            return socket.gethostbyname(socket.gethostname())
        return self.cfg["ip"]

    def __configureServer(self):
        if self.cfg["method"] == "tcp":
            self.servTCP = ModbusTcpServer(self.context,
                                           identity=self.identity,
                                           address=(self.__getIPAddress(),
                                                    self.cfg["tcpPort"]))
        elif self.cfg["method"] == "rtu":
            self.servRTU = ModbusSerialServer(self.context,
                                              framer=ModbusRtuFramer,
                                              identity=self.identity,
                                              port=self.cfg["rtuPort"],
                                              stopbits=self.cfg["stopbits"],
                                              bytesize=self.cfg["bytesize"],
                                              parity=self.cfg["parity"],
                                              baudrate=self.cfg["baudrate"],
                                              timeout=self.cfg["timeout"])
        else:
            raise ReferenceError("Invalid server type")

    def runServer(self):
        if self.cfg["method"] == "tcp":
            self.servTCP.serve_forever()
        elif self.cfg["method"] == "rtu":
            self.servRTU.serve_forever()
        else:
            raise ReferenceError("Invalid server type")

    def stopServer(self):
        if self.cfg["method"] == "tcp":
            self.servTCP.server_close()
            self.servTCP.shutdown()
        elif self.cfg["method"] == "rtu":
            self.servRTU.server_close()
        else:
            raise ReferenceError("Invalid server type")

    def encodeData(self, data):
        self.builder.reset()
        try:
            for i in range(0, len(data)):
                self.builder.add_32bit_float(data[i])
        except TypeError:
            self.builder.add_32bit_float(data)
        return self.builder.to_registers()

    def decodeData(self, data):
        returnData = [0] * (len(data) / 2)
        decoder = BinaryPayloadDecoder.fromRegisters(data,
                                                     endian=Endian.Little)
        for i in range(0, len(data) / 2):
            returnData[i] = round(decoder.decode_32bit_float(), 2)
        return returnData