本文整理汇总了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:
示例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
示例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()
示例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)
示例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__()
示例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())
示例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__()
示例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)
示例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()
示例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))
示例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
示例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()
示例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()
示例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()
示例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()