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


Python ModbusSerialClient.connect方法代码示例

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


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

示例1: ModbusClient

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
def pa
#---------------------------------------------------------------------------#


#---------------------------------------------------------------------------#
# configure the client logging
#---------------------------------------------------------------------------#
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)

for port in ['/dev/ttyxuart3']:
    client = ModbusClient(method='rtu', port=port, baudrate=9600, timeout=1, retries=1)
    client.connect()
    try:
        for addr in [3,10]:
        # for addr in xrange(10,15):
            print ('Meter Modbus Address: %d' % addr)
            # regs = client.read_holding_registers(768,120,unit=addr); print regs.registers if regs else None
            # regs = client.read_holding_registers(128,4,unit=addr); print regs.registers if regs else None
            regs = client.read_holding_registers(142,8,unit=addr); print regs.registers if regs else None

        for addr in xrange(5,9):
            print ('Inverter Modbus Address: %d' % addr)
            regs = client.read_holding_registers(33,10,unit=addr); print regs.registers if regs else None

    except AttributeError, e:
    	print 'Device not responding'
    finally:
开发者ID:eastmanjoe,项目名称:python_bucket,代码行数:32,代码来源:daq_queries_via_bootstrapfile.py

示例2: SerialRtuChannel

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
class SerialRtuChannel(BaseChannel):
    def __init__(self, network, channel_name, channel_protocol, channel_params, channel_manager, channel_type):
        self.port = channel_params.get("port", "")
        self.stopbits = channel_params.get("stopbits", serial.STOPBITS_ONE)
        self.parity = channel_params.get("parity", serial.PARITY_NONE)
        self.bytesize = channel_params.get("bytesize", serial.EIGHTBITS)
        self.baudrate = channel_params.get("baudrate", 9600)
        self.timeout = channel_params.get("timeout", 2)
        self.modbus_client = None
        BaseChannel.__init__(self, network, channel_name, channel_protocol, channel_params, channel_manager,
                             channel_type)

    def run(self):
        self.modbus_client = ModbusSerialClient(method='rtu',
                                                port=self.port,
                                                baudrate=self.baudrate,
                                                stopbits=self.stopbits,
                                                parity=self.parity,
                                                bytesize=self.bytesize,
                                                timeout=self.timeout)
        try:
            self.modbus_client.connect()
            logger.debug("连接串口成功.")
        except Exception, e:
            logger.error("连接串口失败,错误信息:%r." % e)
            self.modbus_client = None
开发者ID:lianwutech,项目名称:plugin_linkworld-discard-,代码行数:28,代码来源:serial_rtu.py

示例3: main

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
def main():
  if len(sys.argv) != 4:
    print(
"""Usage: ./orno_modbus.py serial_port device_address target_device_address
Example: ./orno_modbus.py /dev/ttyUSB0 1 11

If you have only one device you can set the device_address to 0 to change its address.
""")
    sys.exit(0)

  port = sys.argv[1]
  address = int(sys.argv[2])
  target_address = int(sys.argv[3])

  client = ModbusClient(method="rtu", port=port, baudrate=9600)
  client.connect()

  request = SendOrnoPassword('00000000', unit=address)
  client.execute(request)

  response = client.write_registers(15, [target_address], unit=address)
  if response:
    if address:
      print "Success. Changed address from %d to %d." % (address, target_address)
    else:
      print "Success. Changed address to %d." % (target_address)
  else:
    print "Address change failed"

  client.close()
开发者ID:PeWu,项目名称:orno_modbus,代码行数:32,代码来源:orno_modbus.py

示例4: run

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
 def run(self): 
     global tCtrl
     _sample=select(tCtrl.samples,'id',self.id)
     _protocol=select(tCtrl.protocols,'id',_sample.properties['protocol_id'])
     _transport=select(tCtrl.transports,'id',_sample.properties['transport_id'])
     _rule=select(tCtrl.rules,'id',_sample.properties['rule_id'])        
     _method=_protocol.properties['method']
     _port=_transport.properties['port']
     _para=_transport.properties['para'] 
     _timeout=int(_transport.properties['timeout'])/1000.0
     client = ModbusClient(method=_method, port=_port,baudrate= \
     Baudrate(_para),bytesize=Bytesize(_para),parity=Parity(_para),\
     stopbits=Stopbits(_para),timeout=_timeout) 
     _index=int(_rule.properties['index'])
     _count=int(_rule.properties['count'])
     _unit_begin=Begin(_rule.properties['range'])
     _unit_end=End(_rule.properties['range'])
     client.connect()  
     self.interval = int(_protocol.properties['period']) 
     while not self.thread_stop: 
         for i in range(_unit_begin,_unit_end):
             start_ = datetime.utcnow()
             response=client.read_holding_registers(address=_index, \
             count=_count,unit=i)                
             tCtrl.samples[self.index].data[i]=response.registers
             print response.registers #getRegister(1)/10.0
             end_ = datetime.utcnow()
             print '[cost time] %s' %(end_-start_)
         time.sleep(self.interval)  
开发者ID:ououcool,项目名称:ep,代码行数:31,代码来源:daq.py

示例5: connect

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
def connect():
	try:
	    client = None
	    client = ModbusClient(retries = 0, method='rtu', port='/dev/ttyUSB1', baudrate=38400, stopbits=1, parity='N', bytesize=8, timeout=1)
	    client.connect()
	    return client
	
	except Exception as e:
	    print "Error while connecting client: \n"+e.__str__()
开发者ID:xtompok,项目名称:RS485-logger,代码行数:11,代码来源:modbus.py

示例6: testSerialClientConnect

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

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

示例7: CONNECT_TO_METER

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
def CONNECT_TO_METER():

    try:
        client = None
        METER_PORT = find_tty_usb(ID_VENDOR, ID_PRODUCT)        #reading to which port rs485(client) is connected
        client = ModbusClient(retries = RETRIES, method=COM_METHOD, port=METER_PORT, baudrate=BAUD_RATE, stopbits=STOP_BITS, parity=PARITY, bytesize=BYTE_SIZE, timeout=TIME_OUT)
        client.connect()
        return client

    except Exception as e:
        lgr.error('Error while connecting client: ', exc_info = True)
        print "Error while connecting client: \n"+e.__str__()
开发者ID:26061990,项目名称:SmartMeter,代码行数:14,代码来源:dataCollector.py

示例8: SerialRtuChannel

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
class SerialRtuChannel(BaseChannel):
    def __init__(self, channel_params, devices_file_name, protocol, mqtt_client, network_name):
        BaseChannel.__init__(self, channel_params, devices_file_name, protocol, mqtt_client, network_name)
        # 配置项
        self.port = channel_params.get("port", "")
        self.baund = channel_params.get("baund", 9600)
        self.stopbits = channel_params.get("stopbits", serial.STOPBITS_ONE)
        self.parity = channel_params.get("parity", serial.PARITY_NONE)
        self.bytesize = channel_params.get("bytesize", serial.EIGHTBITS)
        self.timeout = channel_params.get("timeout", 2)
        self.protocol.set_device_info(self.port, self.baund)
        # modbus通信对象
        self.modbus_client = ModbusSerialClient(method='rtu',
                                                port=self.port,
                                                baudrate=self.baund,
                                                stopbits=self.stopbits,
                                                parity=self.parity,
                                                bytesize=self.bytesize,
                                                timeout=self.timeout)

    @staticmethod
    def check_config(channel_params):
        if "port" not in channel_params or "baund" not in channel_params:
            return False
        return BaseChannel.check_config(channel_params)

    def run(self):

        # 首先上报设备数据
        for device_id in self.devices_info_dict:
            device_info = self.devices_info_dict[device_id]
            device_msg = {
                "device_id": device_info["device_id"],
                "device_type": device_info["device_type"],
                "device_addr": device_info["device_addr"],
                "device_port": device_info["device_port"],
                "protocol": self.protocol.protocol_type,
                "data": ""
            }
            self.mqtt_client.publish_data(device_msg)

        try:
            self.modbus_client.connect()
            logger.debug("连接串口成功.")
        except Exception, e:
            logger.error("连接串口失败,错误信息:%r." % e)
            self.modbus_client = None
            return

        while True:
            # 该线程保持空转
            time.sleep(5)
开发者ID:lianwutech,项目名称:plugin_serialrtu_modbus,代码行数:54,代码来源:serialrtu.py

示例9: CONNECT_TO_METER

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
def CONNECT_TO_METER():

    try:
        client = None
        METER_PORT = find_tty_usb(ID_VENDOR, ID_PRODUCT)        #reading to which port rs485(client) is connected
        client = ModbusClient(retries = RETRIES, method=COM_METHOD, port=METER_PORT, baudrate=BAUD_RATE, stopbits=STOP_BITS, parity=PARITY, bytesize=BYTE_SIZE, timeout=TIME_OUT)
        client.connect()
        return client

    except Exception as e:
        print "Could not connect to client: \n" + e.__str__()
        log_file=open(DATA_BASE_PATH+"RealtimeLOG.txt","a")
        log_file.write(str(time.time())+" Could not connect to client: \n"+e.__str__()+"\n")
        log_file.close()
开发者ID:26061990,项目名称:SmartMeter,代码行数:16,代码来源:dataCollectorRealtimePlot.py

示例10: testBasicSyncSerialClient

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
    def testBasicSyncSerialClient(self, mock_serial):
        ''' Test the basic methods for the serial sync client'''

        # receive/send
        mock_serial.in_waiting = 0
        mock_serial.write = lambda x: len(x)

        mock_serial.read = lambda size: b'\x00' * size
        client = ModbusSerialClient()
        client.socket = mock_serial
        client.state = 0
        self.assertEqual(0, client._send(None))
        client.state = 0
        self.assertEqual(1, client._send(b'\x00'))
        self.assertEqual(b'\x00', client._recv(1))

        # connect/disconnect
        self.assertTrue(client.connect())
        client.close()

        # already closed socket
        client.socket = False
        client.close()

        self.assertEqual('ModbusSerialClient(ascii baud[19200])', str(client))
开发者ID:ccatterina,项目名称:pymodbus,代码行数:27,代码来源:test_client_sync.py

示例11: __init__

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
class EPsolarTracerClient:
    ''' EPsolar Tracer client
    '''

    def __init__(self, unit = 1, serialclient = None, **kwargs):
        ''' Initialize a serial client instance
        '''
        self.unit = unit
        if serialclient == None:
            port = kwargs.get('port', '/dev/ttyXRUSB0')
            baudrate = kwargs.get('baudrate', 115200)
            self.client = ModbusClient(method = 'rtu', port = port, baudrate = baudrate, kwargs = kwargs)
        else:
            self.client = serialclient

    def connect(self):
        ''' Connect to the serial
        :returns: True if connection succeeded, False otherwise
        '''
        return self.client.connect()

    def close(self):
        ''' Closes the underlying connection
        '''
        return self.client.close()

    def read_device_info(self):
        request = ReadDeviceInformationRequest (unit = self.unit)
        response = self.client.execute(request)
        return response

    def read_input(self, name):
        register = registerByName(name)
        if register.is_coil():
            response = self.client.read_coils(register.address, register.size, unit = self.unit)
        elif register.is_discrete_input():
            response = self.client.read_discrete_inputs(register.address, register.size, unit = self.unit)
        elif register.is_input_register():
            response = self.client.read_input_registers(register.address, register.size, unit = self.unit)
        else:
            response = self.client.read_holding_registers(register.address, register.size, unit = self.unit)
        return register.decode(response)

    def write_output(self, name, value):
        register = registerByName(name)
        values = register.encode(value)
        response = False
        if register.is_coil():
            self.client.write_coil(register.address, values, unit = self.unit)
            response = True
        elif register.is_discrete_input():
            _logger.error("Cannot write discrete input " + repr(name))
            pass
        elif register.is_input_register():
            _logger.error("Cannot write input register " + repr(name))
            pass
        else:
            self.client.write_registers(register.address, values, unit = self.unit)
            response = True
        return response
开发者ID:davcx,项目名称:epsolar-tracer,代码行数:62,代码来源:client.py

示例12: main

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
def main(host, port, mqtt_username, mqtt_password, instance, name, serial_port):
    modbus = ModbusClient(method='rtu', port=serial_port, baudrate=9600, timeout=1)

    if not modbus.connect():
        logger.error("Cannot connect to modbus")
        return

    client = mqtt.Client()
    client.loop_start()

    client.connect(host, port, 60)
    if mqtt_username is not None:
        client.username_pw_set(mqtt_username, mqtt_password)

    try:
        while True:
            now = int(time())
            r = modbus.read_holding_registers(0, 16, unit=1)

            bat_volt = r.registers[8] * 96.667 * 2**(-15)
            bat_curr = r.registers[11] * 316.67 * 2**(-15)
            bat_temp = r.registers[15]

            client.publish('{}/{}/power'.format(instance, name), "{} {:0.2f}".format(now, bat_volt * bat_curr), 0)
            client.publish('{}/{}/voltage'.format(instance, name), "{} {:0.2f}".format(now, bat_volt), 0)
            client.publish('{}/{}/current'.format(instance, name), "{} {:0.2f}".format(now, bat_curr), 0)
            client.publish('{}/{}/temperature'.format(instance, name), "{} {}".format(now, bat_temp), 0)

            sleep(5)
    except KeyboardInterrupt:
        pass
    client.disconnect()
    client.loop_stop()
    modbus.close()
开发者ID:izak,项目名称:ib.bluelantern.morningstar,代码行数:36,代码来源:mppt.py

示例13: main

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
def main(args):
    global PUMP_TIME
    global SENSOR_TIME
    try:
        PUMP_TIME = int(args[1])
        SENSOR_TIME = int(args[2])
        print('using custom args. pump time: %d sensor time: %d' % (PUMP_TIME, SENSOR_TIME))
    except:
        PUMP_TIME = 3
        SENSOR_TIME = 5
        print('using default args. pump time: %d sensor time: %d' % (PUMP_TIME, SENSOR_TIME))

    startMeasurement()

    # Connect to sensor and record data
    try:
        client = ModbusClient(method = "rtu", port="/dev/ttyS0",stopbits = 1, bytesize = 8, parity = 'N', baudrate= 9600)
        # Connect to the serial modbus server
        connection = client.connect()
        if connection:
            recordData(client)
        # Closes the underlying socket connection
        client.close()

    except Exception as error:
        print('CO2 measurement failed: ' + repr(error))
    finally:
        endMeasurement()
开发者ID:shawn-hateley,项目名称:Scripts,代码行数:30,代码来源:co2reading.py

示例14: SynchronousRtuClient

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
class SynchronousRtuClient(Runner, unittest.TestCase):
    """
    These are the integration tests for the synchronous
    serial rtu client.
    """

    def setUp(self):
        """ Initializes the test environment """
        super(Runner, self).setUp()
        self.initialize(["../tools/reference/diagslave", "-m", "rtu", "/dev/pts/14"])
        self.client = ModbusClient(method='rtu', timeout=0.2, port='/dev/pts/13')
        self.client.connect()

    def tearDown(self):
        """ Cleans up the test environment """
        self.client.close()
        super(Runner, self).tearDown()
开发者ID:bashwork,项目名称:pymodbus,代码行数:19,代码来源:synchronous_rtu_client.py

示例15: SynchronousAsciiClient

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import connect [as 别名]
class SynchronousAsciiClient(Runner, unittest.TestCase):
    '''
    These are the integration tests for the synchronous
    serial ascii client.
    '''

    def setUp(self):
        ''' Initializes the test environment '''
        super(Runner, self).setUp()
        #    "../tools/nullmodem/linux/run",
        self.initialize(["../tools/reference/diagslave", "-m", "ascii", "/dev/pts/14"])
        self.client = ModbusClient(method='ascii', timeout=0.2, port='/dev/pts/13')
        self.client.connect()

    def tearDown(self):
        ''' Cleans up the test environment '''
        self.client.close()
        super(Runner, self).tearDown()
开发者ID:mahongquan,项目名称:pymodbus,代码行数:20,代码来源:synchronous-ascii-client.py


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