当前位置: 首页>>代码示例>>Python>>正文


Python ModbusTcpClient.connect方法代码示例

本文整理汇总了Python中pymodbus.client.sync.ModbusTcpClient.connect方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusTcpClient.connect方法的具体用法?Python ModbusTcpClient.connect怎么用?Python ModbusTcpClient.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pymodbus.client.sync.ModbusTcpClient的用法示例。


在下文中一共展示了ModbusTcpClient.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ModbusModule

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
class ModbusModule():
    def __init__(self, io_module_name, ip):
        logger.debug('Creating new controller with name {} and address {}.'.format(io_module_name, ip))
        self.io_module_name = io_module_name
        self.ip_address = ip
        self.controller_type = CONTROLLER_TYPE.Modbus
        # build connection object
        self.client = ModbusClient(ip, port=config.DEFAULT_MODBUS_PORT)
        self.client.connect()

    def __del__(self):
        self.client.close()

    def __str__(self):
        return 'Controller "{}" at address {}'.format(self.io_module_name, self.ip_address)

    def get_bit(self, address):
        try:
            result = self.client.read_coils(address)
            bit_value = result.bits[0]
        except ConnectionException:
            logger.error('Could not connect to Modbus module "{}"!'
                         .format(self.io_module_name))
            bit_value = False
        return bit_value

    def set_bit(self, address, value):
        try:
            self.client.write_coil(address, value)
        except ConnectionException:
            logger.error('Could not connect to Modbus module "{}"!'
                         .format(self.io_module_name))
开发者ID:wichmann,项目名称:spots,代码行数:34,代码来源:controller.py

示例2: wren_gw_modbus_read

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
def wren_gw_modbus_read(config):
    ''' read a value from the peer.

    @param config the configuration in the key/value type.
    '''

    try:
        m = ModbusTcpClient(host=config['node'], port=config['port'])
        m.connect()
        unit = 0xff
        if config.has_key('unit_id'):
            unit = config['unit_id']
        # sed data
        value = None
        if config['table'] == 'InputRegister':
            result = m.read_input_registers(config['address'], 1, unit=unit)
            if result:
                value = result.registers[config['address']]
        if config['table'] == 'HoldingRegister':
            result = m.read_holding_registers(config['address'], 1, unit=unit)
            if result:
                value = result.registers[config['address']]
        # close it.
        m.close()
        return {"status":True, "value":str(value)};
    except Exception as e:
        return {"status":False, "value":str(e)};
开发者ID:tanupoo,项目名称:wren,代码行数:29,代码来源:wren_modbus.py

示例3: TestMbTcpClass1

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
class TestMbTcpClass1(unittest.TestCase):
	read_values = range(0xAA50, 0xAA60)
	write_values = range(0xBB50, 0xBB60)
	
	def setUp(self):
		self.client = ModbusTcpClient(SERVER_HOST)
		self.client.connect()
		
	def tearDown(self):
		self.client.close()
		
	def test_write_single_holding_register(self):
		rq = self.client.write_register(8, 0xCC)
		self.assertEqual(rq.function_code, 0x06)
		rr = self.client.read_holding_registers(8, 1)
		self.assertEqual(rr.registers[0], 0xCC)
		rq = self.client.write_register(16, 0x00)
		self.assertEqual(rq.function_code, 0x86)
		rq = self.client.write_register(8, 0xAA58)
		
	def test_write_coil(self):
		rq = self.client.write_coil(0, True)
		self.assertEqual(rq.function_code, 0x05)
		
		rq = self.client.write_coil(0, False)
		self.assertEqual(rq.function_code, 0x05)
		
		rq = self.client.write_coil(256, False)
		self.assertEqual(rq.function_code, 0x85)
		
	def test_read_coil(self):
		coil_read_values = [True, False, True, False, False, True, False, False]
开发者ID:davidmalovrh,项目名称:w7500_modbustcp,代码行数:34,代码来源:mbtcp_class1.py

示例4: setDeviceStatus

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
    def setDeviceStatus(self, postmsg):
        setDeviceStatusResult = True

        try:
            client = ModbusTcpClient(self.get_variable('address'),port=502)
            client.connect()
            if (self.get_variable('model')=='VC1000'):
                if 'heat_setpoint' in postmsg.keys():
                    client.write_register(6,int(self.far2cel(float(postmsg.get('heat_setpoint')))*100.0),unit=self.get_variable('slave_id'))
                if 'cool_setpoint' in postmsg.keys():
                    client.write_register(6,int(self.far2cel(float(postmsg.get('cool_setpoint')))*100.0),unit=self.get_variable('slave_id'))
                if 'flap_override' in postmsg.keys():
                    if postmsg.get('flap_override') == 'ON' or postmsg.get('flap_override') == True:
                        client.write_register(159,1,unit=self.get_variable('slave_id'))
                    elif postmsg.get('flap_override') == 'OFF' or postmsg.get('flap_override') == False:
                        client.write_register(159,0,unit=self.get_variable('slave_id'))
                if 'flap_position' in postmsg.keys():
                    client.write_register(160,int(postmsg.get('flap_position')),unit=self.get_variable('slave_id'))
            elif (self.get_variable('model')=='M1000'):
                if 'heat_setpoint' in postmsg.keys():
                    client.write_register(187,int(self.far2cel(float(postmsg.get('heat_setpoint')))*100.0),unit=self.get_variable('slave_id'))
                if 'cool_setpoint' in postmsg.keys():
                    client.write_register(188,int(self.far2cel(float(postmsg.get('cool_setpoint')))*100.0),unit=self.get_variable('slave_id'))
                if 'outside_damper_position' in postmsg.keys():
                    client.write_register(274,int(postmsg.get('outside_damper_position')),unit=self.get_variable('slave_id'))
                if 'bypass_damper_position' in postmsg.keys():
                    client.write_register(275,int(postmsg.get('bypass_damper_position')),unit=self.get_variable('slave_id'))
                if 'fan_status' in postmsg.keys():
                    if postmsg.get('fan_status') == 'ON' or postmsg.get('fan_status') == True:
                        client.write_register(130,2,unit=self.get_variable('slave_id'))
                    elif postmsg.get('fan_status') == 'OFF' or postmsg.get('fan_status') == False:
                        client.write_register(130,1,unit=self.get_variable('slave_id'))
                if 'cooling_status' in postmsg.keys():
                    if postmsg.get('cooling_status') == 'ON':
                        client.write_registers(124,[1,2,2,2],unit=self.get_variable('slave_id'))
                    elif postmsg.get('cooling_status') == 'OFF':
                        client.write_registers(124,[0,1,1,1],unit=self.get_variable('slave_id'))
                if 'cooling_mode' in postmsg.keys():
                    if postmsg.get('cooling_mode') == 'None':
                        client.write_register(10,0,unit=self.get_variable('slave_id'))
                    elif postmsg.get('cooling_mode') == 'STG1':
                        client.write_register(10,1,unit=self.get_variable('slave_id'))
                    elif postmsg.get('cooling_mode') == 'STG2':
                        client.write_register(10,2,unit=self.get_variable('slave_id'))
                    elif postmsg.get('cooling_mode') == 'STG3':
                        client.write_register(10,3,unit=self.get_variable('slave_id'))
                    elif postmsg.get('cooling_mode') == 'STG4':
                        client.write_register(10,4,unit=self.get_variable('slave_id'))
                if 'heating' in postmsg.keys():
                    client.write_register(129,int(postmsg.get('heating')),unit=self.get_variable('slave_id'))
            client.close()

        except:
            try:
                client.close()
            except:
                print('Modbus TCP client was not built successfully at the beginning')
            setDeviceStatusResult=False

        return setDeviceStatusResult
开发者ID:kwarodom,项目名称:bemoss_os-2,代码行数:62,代码来源:classAPI_vav_rtu.py

示例5: _run_single_client

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
def _run_single_client(client_id, host, port, units, results, N, delay, warmup, table):
    _log.info('Client %d connecting to %s (%s)', client_id, host, port)
    client = ModbusClient(host, port=port)
    client.connect()

    _log.info('Client %d connected to %s (%s)', client_id, host, port)

    measurements = []
    errors = []
    for i in xrange(N):
        if N >= 1000 and i % (N/10) == 0 and i > 0:
            _log.info('Client %d %.0f%% complete', client_id, 100.0*i/N)
        try:
            m = _make_random_request(client, units, table)
            if i >= warmup or N <= warmup:
                if i == warmup:
                    _log.info('Client %d warmup complete.', client_id)
                measurements.append(m)
        except jem_exceptions.JemException, e:
            errors.append(e)
            _log.warn('Client %d received error response: %s', client_id, e)
        except Exception, e:
            from pymodbus import exceptions as es
            _log.error("Caught other exception: %s" % str(e))
            _log.error("Is instance: %s", isinstance(e, es.ModbusException))
开发者ID:sprily,项目名称:jem-data,代码行数:27,代码来源:performance.py

示例6: TestMbTcpClass0

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
class TestMbTcpClass0(unittest.TestCase):
	read_values = range(0xAA50, 0xAA60)
	write_values = range(0xBB50, 0xBB60)
	
	def setUp(self):
		self.client = ModbusTcpClient(SERVER_HOST)
		self.client.connect()
		
	def tearDown(self):
		self.client.close()
		
	def test_read_holding_registers(self):
		rv = self.client.read_holding_registers(0, 16)
		self.assertEqual(rv.function_code, 0x03)
		self.assertEqual(rv.registers, self.read_values)
		
	def test_read_holding_registers_exception(self):
		rv = self.client.read_holding_registers(16, 1)
		self.assertEqual(rv.function_code, 0x83)
		self.assertEqual(rv.exception_code, 0x02)
	
	def test_write_holding_registers(self):
		rq = self.client.write_registers(0, self.write_values)
		self.assertEqual(rq.function_code, 0x10)
		rr = self.client.read_holding_registers(0, 16)
		self.assertEqual(rr.registers, self.write_values)
		rq = self.client.write_registers(0, self.read_values)
		self.assertEqual(rq.function_code, 0x10)
		
	def test_write_holding_registers_exception(self):
		rq = self.client.write_registers(16, [0x00])
		self.assertEqual(rq.function_code, 0x90)
		self.assertEqual(rq.exception_code, 0x02)
开发者ID:davidmalovrh,项目名称:w7500_modbustcp,代码行数:35,代码来源:mbtcp_class0.py

示例7: wren_gw_modbus_write

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
def wren_gw_modbus_write(config, value):
    ''' write a value to the peer.

    @param value a number in the string type.
    '''

    try:
        m = ModbusTcpClient(host=config['node'], port=config['port'])
        # XXX
        # ModbusTcpClient.connect() does not look to do connect(2) actually.
        m.connect()
        unit = 0xff
        if config.has_key('unit_id'):
            unit = config['unit_id']
        # send data
        result = False
        if config['table'] == 'HoldingRegister':
            result = m.write_register(config['address'], int(value), unit=unit)
            if result.value == int(value):
                result = True
        # close it.
        m.close()
        return {"status":True, "value":str(value)};
    except Exception as e:
        return {"status":False, "value":str(e)};
开发者ID:tanupoo,项目名称:wren,代码行数:27,代码来源:wren_modbus.py

示例8: ModbusConnection

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
class ModbusConnection(object):
    _max_retries_read = 10
    _max_retries_write = 3

    @property
    def max_retries_read(self):
        return self._max_retries_read

    @property
    def max_retries_write(self):
        return self._max_retries_write

    @property
    def client_address(self):
        return self.client.host

    @property
    def client_port(self):
        return str(self.client.port)

    def __init__(self, client_address, client_port):
        self.client = ModbusClient(host = client_address, port = int(client_port))
        self.connect_to_client()

    def __del__(self):
        self.disconnect_from_client()

    def connect_to_client(self):
        self.client.connect()

    def disconnect_from_client(self):
        self.client.close()

    def read_input_registers(self, address, count, unit):
        k = 0
        while k < self.max_retries_read:
            try:
                return self.client.read_input_registers(address = address, count = count, unit = unit).registers
            except:
                k += 1
                sleep(1.5)

    def read_holding_registers(self, address, count, unit):
        k = 0
        while k < self.max_retries_read:
            try:
                return self.client.read_holding_registers(address = address, count = count, unit = unit).registers
            except:
                k += 1
                sleep(1.5)

    def write_register(self, address, unit, value):
        k = 0
        while k < self.max_retries_write:
            try:
                return self.client.write_register(address = address, unit = unit, value = value)
            except:
                k += 1
                sleep(1.5)
开发者ID:mada1019,项目名称:t,代码行数:61,代码来源:modbus_connection.py

示例9: scan

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
def scan():
    
    parser = argparse.ArgumentParser(description = "Read all holding registries from a TCP MODBUS Slave")
    parser.add_argument("ip", help="IP address of the slave")
    parser.add_argument("-p", "--port", dest="port", help="Modbus Port. Defaults to 502", type=int, metavar="PORT", default=502)
    parser.add_argument("-u", "--uid", dest="uid", help="Modbus Unit ID. Defaults to 1", type=int, metavar="UID", default=1)
    parser.add_argument("-sa", "--start-address", dest="start_address", help="Starting Address for the scanner. Defaults to 1", type=int, metavar="START", default=1)
    parser.add_argument("-ea", "--end-address", dest="end_address", help="Ending Address for the scanner. Defaults to 65535", type=int, metavar="END", default=65535)
    
    args = parser.parse_args()
    
    try:
        ip = args.ip
    except IndexError:
        print "ERROR: No target to scan\n\n"
        parser.print_help()
        exit()

    # ip address format verification
    if not validate_ipv4(ip):
        print "ERROR: IP address is invalid\n\n"
        parser.print_help()
        exit()

    print 'Connecting to %s...' % ip,
    # connect to modbus slave
    client = ModbusTcpClient(ip, args.port)
    client.connect()
    if client.socket == None:
        print "ERROR: Could not connect to %s." %ip
        exit()
    print ' Connected.'

    # TODO add ETA mechanism
    results = {}
    addr = 1
    registers_tested = args.end_address - args.start_address + 1
    if registers_tested == 1:
        hr = client.read_holding_registers(args.start_address, 1, unit=args.uid) # unit value is device id of the slave (UID)
        if hr.function_code == 3: # if we succeed reading stuff
            results[addr] = hr.registers[0]
        # if it fails, hr.function = 131 (0x83), cf modbus doc
    else:
    	for addr in range(args.start_address, args.end_address):
            hr = client.read_holding_registers(addr, 1, unit=args.uid) # unit value is device id of the slave (UID)
            if hr.function_code == 3: # if we succeed reading stuff
                results[addr] = hr.registers[0]
            # if it fails, hr.function = 131 (0x83), cf modbus doc

    client.close()
    print 'Register scanning is finished (%d registers were tried)' % (registers_tested)
    # sorting dict for printing
    ordered_results = collections.OrderedDict(sorted(results.items()))
    for addr, value in ordered_results.iteritems():
        print 'Addr {0} \t{1}'.format(addr,value)
开发者ID:romainallain,项目名称:mas,代码行数:57,代码来源:read_all_holding_registers.py

示例10: testTcpClientConnect

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
    def testTcpClientConnect(self):
        ''' Test the tcp client connection method'''
        with patch.object(socket, 'create_connection') as mock_method:
            mock_method.return_value = object()
            client = ModbusTcpClient()
            self.assertTrue(client.connect())

        with patch.object(socket, 'create_connection') as mock_method:
            mock_method.side_effect = socket.error()
            client = ModbusTcpClient()
            self.assertFalse(client.connect())
开发者ID:zhanglongqi,项目名称:pymodbus,代码行数:13,代码来源:test_client_sync.py

示例11: create_sunspec_sync_client

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
def create_sunspec_sync_client(host):
    """ A quick helper method to create a sunspec
    client.

    :param host: The host to connect to
    :returns: an initialized SunspecClient
    """
    modbus = ModbusTcpClient(host)
    modbus.connect()
    client = SunspecClient(modbus)
    client.initialize()
    return client
开发者ID:ccatterina,项目名称:pymodbus,代码行数:14,代码来源:sunspec_client.py

示例12: get_temp

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
 def get_temp(self, addr):
     # connect to modbus slave
     try:
         client = ModbusClient(addr, port=502)
         client.connect()
         rr = client.read_holding_registers(0x00,1,unit=1)
         temp = rr.registers[0]
         return temp
     except:
         # if unable to connect, return None
         log_stuff("Unable to connect to " + self.addr)
         return None
开发者ID:RITSPARSA,项目名称:ISTS14-Stuff,代码行数:14,代码来源:poll_sensor.py

示例13: main

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
def main(host, port, delay, unit, table_num):
    client = ModbusClient(host, port=port)
    client.connect()
    
    min_response_time = 100
    max_response_time = 0
    sum_response_time = 0
    N = 0

    register_widths = diris_registers.TABLES[table_num-1].copy()
    register_labels = DEMO_REGISTERS.copy()
    registers = dict((addr, register_widths[addr]) \
                        for addr in DEMO_REGISTERS.keys() \
                        if addr in register_widths)

    label_width = max([len(label) for label in DEMO_REGISTERS.values()]) + 1

    while True:
    
        start = time.time()
        try:
            response = modbus.read_registers(client,
                                             registers=registers,
                                             unit=unit)
        except exceptions.ModbusExceptionResponse, e:
            response=None
    
        response_time = time.time() - start

        os.system('clear')

        print "Request Times:"

        min_response_time = min(min_response_time, response_time)
        max_response_time = max(max_response_time, response_time)
        sum_response_time += response_time
        N += 1
    
        print "Min".rjust(label_width) + ": " + str(min_response_time)
        print "Max".rjust(label_width) + ": " + str(max_response_time)
        print "Avg".rjust(label_width) + ": " + str(sum_response_time/N)

        print "Response Values:"
        for addr in sorted(registers.keys()):
            if response is None:
                break
            print (u"{label:>" + str(label_width) + u"s}: {value:f}").format(
                    label=register_labels[addr],
                    value=response.read_register(addr))

        print
        time.sleep(delay)
开发者ID:sprily,项目名称:jem-data,代码行数:54,代码来源:client.py

示例14: TcpRtuChannel

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
class TcpRtuChannel(BaseChannel):
    def __init__(self, network, channel_name, channel_protocol, channel_params, manager, channel_type):
        self.server = channel_params.get("server", "")
        self.port = channel_params.get("port", "")
        self.modbus_client = None
        BaseChannel.__init__(self, network, channel_name, channel_protocol, channel_params, manager, channel_type)

    def run(self):
        self.modbus_client = ModbusTcpClient(host=self.server, port=self.port)
        try:
            self.modbus_client.connect()
            logger.debug("连接服务器成功.")
        except Exception, e:
            logger.error("连接服务器失败,错误信息:%r." % e)
开发者ID:lianwutech,项目名称:plugin_linkworld-discard-,代码行数:16,代码来源:tcp_rtu.py

示例15: main

# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import connect [as 别名]
def main():
    # connect to modbus slave
    client = ModbusClient(args.slave_addr, port=502)
    client.connect()

    try:
        while True:
            # get value of holding registers (first has the temperature value)
            rr = client.read_holding_registers(0x00,1,unit=1)
            temp = rr.registers[0]
            enable_light(temp)
            time.sleep(3)
    except KeyboardInterrupt:
        subprocess.call(['gpio', 'write', '0', '0'])
        subprocess.call(['gpio', 'write', '1', '0'])
        print "Exiting..."
开发者ID:tylernfornes,项目名称:Raspberry-SCADA,代码行数:18,代码来源:pymodbus_master.py


注:本文中的pymodbus.client.sync.ModbusTcpClient.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。