本文整理汇总了Python中pymodbus.client.sync.ModbusTcpClient类的典型用法代码示例。如果您正苦于以下问题:Python ModbusTcpClient类的具体用法?Python ModbusTcpClient怎么用?Python ModbusTcpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ModbusTcpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testTcpClientRegister
def testTcpClientRegister(self):
class CustomeRequest:
function_code = 79
client = ModbusTcpClient()
client.framer = Mock()
client.register(CustomeRequest)
assert client.framer.decoder.register.called_once_with(CustomeRequest)
示例2: TestMbTcpClass0
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)
示例3: runModBus
def runModBus(IOVariables):
#---------------------------------------------------------------------------#
# choose the client you want
#---------------------------------------------------------------------------#
# make sure to start an implementation to hit against. For this
# you can use an existing device, the reference implementation in the tools
# directory, or start a pymodbus server.
#---------------------------------------------------------------------------#
client = ModbusTcpClient('192.168.1.9')
#rq = client.write_registers(2048, [0])
#rr = client.read_input_registers(000, 1)
#print (rr.registers)
#---------------------------------------------------------------------------#
# configure io card
#---------------------------------------------------------------------------#
#Digital_In_1 = ModbusDigitalInputIOCard(0, client)
#print('IOVariables in modbus.py: {IOVariables} '.format(IOVariables=IOVariables))
Digital_Out_1 = ModbusDigitalOutputIOCard(2048, client, IOVariables)
#---------------------------------------------------------------------------#
# Run io card
#---------------------------------------------------------------------------#
#Digital_In_1.ReadStatus()
#---------------------------------------------------------------------------#
# Run io card
#---------------------------------------------------------------------------#
Digital_Out_1.WriteStatus()
#---------------------------------------------------------------------------#
# close the client
#---------------------------------------------------------------------------#
client.close()
示例4: testTcpClientSend
def testTcpClientSend(self):
''' Test the tcp client send method'''
client = ModbusTcpClient()
self.assertRaises(ConnectionException, lambda: client._send(None))
client.socket = mockSocket()
self.assertEqual(0, client._send(None))
self.assertEqual(4, client._send('1234'))
示例5: testTcpClientRecv
def testTcpClientRecv(self):
''' Test the tcp client receive method'''
client = ModbusTcpClient()
self.assertRaises(ConnectionException, lambda: client._recv(1024))
client.socket = mockSocket()
self.assertEqual('', client._recv(0))
self.assertEqual('\x00'*4, client._recv(4))
示例6: __init__
def __init__(self, *args, **kwargs):
''' Constructor
default modbus port is 502'''
#ip address
self.addr = args[0]
ModbusTcpClient.__init__(self, self.addr)
self.connect()
示例7: testTcpClientConnect
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())
示例8: run
def run(self):
comm=server_addr[random.randint(0,len(serverlist)-1)]
client = ModbusTcpClient(comm, self.port, source_address=(self.ipaddr,0), retries=1, retry_on_empty=True)
while(not self.clientstop.is_set()):
client.write_coil(1, True)
print "coil write from:" + self.ipaddr + " --->" + comm
time.sleep(random.randint(0,3))
print "stopping"
client.socket.shutdown(1)
client.close()
return
示例9: create_sunspec_sync_client
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
示例10: TcpRtuChannel
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)
示例11: __init__
def __init__(self, indicator_list, coil_on_list, coil_off_list, command_list, coil_list, port,
method="rtu", timeout=0.1, unit=0x01):
self.unit = unit
self.indicator_list = indicator_list
self.coil_on_list = coil_on_list
self.coil_off_list = coil_off_list
self.coil_list = coil_list
self.command_list = command_list
self.lock = threading.Lock()
if method == "rtu":
self.client = ModbusSerialClient(method=method, port=port, baudrate=19200, stopbits=1, bytesize=8,
timeout=timeout)
elif method == "tcp":
self.client = ModbusTcpClient(host=port)
示例12: __init__
class communication:
def __init__(self):
self.client = None
self.lock = threading.Lock()
def connectToDevice(self, address):
"""Connection to the client - the method takes the IP address (as a string, e.g. '192.168.1.11') as an argument."""
self.client = ModbusTcpClient(address)
def disconnectFromDevice(self):
"""Close connection"""
self.client.close()
def sendCommand(self, data):
"""Send a command to the Gripper - the method takes a list of uint8 as an argument. The meaning of each variable depends on the Gripper model (see support.robotiq.com for more details)"""
# make sure data has an even number of elements
if len(data) % 2 == 1:
data.append(0)
# Initiate message as an empty list
message = []
# Fill message by combining two bytes in one register
for i in range(0, len(data) / 2):
message.append((data[2 * i] << 8) + data[2 * i + 1])
# To do!: Implement try/except
with self.lock:
self.client.write_registers(0, message)
def getStatus(self, numBytes):
"""Sends a request to read, wait for the response and returns the Gripper status. The method gets the number of bytes to read as an argument"""
numRegs = int(ceil(numBytes / 2.0))
# To do!: Implement try/except
# Get status from the device
with self.lock:
response = self.client.read_input_registers(0, numRegs)
# Instantiate output as an empty list
output = []
# Fill the output with the bytes in the appropriate order
for i in range(0, numRegs):
output.append((response.getRegister(i) & 0xFF00) >> 8)
output.append(response.getRegister(i) & 0x00FF)
# Output the result
return output
示例13: on_switchMain_activate
def on_switchMain_activate(self, switch,gparam):
if switch.get_active():
self.client_1 = ModbusClient(manifold_host_1, port=manifold_port_1)
self.client_p = ModbusClient(pump_host, port=pump_port)
self.client_1.connect()
self.client_p.connect()
self.readDataSetupConfig()
time.sleep(2)
print "start connection"
time_delay = 1 # 1 seconds delay
self.loop = LoopingCall(f=self.logging_data, a=(self.client_1, builder.get_object("txtAIN1"),builder.get_object("txtAIN2"),builder.get_object("txtAIN1ENG"),builder.get_object("txtAIN2ENG"),builder.get_object("txtAIN12"),builder.get_object("txtAIN22"),builder.get_object("txtAIN1ENG2"),self.client_p,builder.get_object("txtPout"),builder.get_object("txtQout")))
self.loop.start(time_delay, now=False) # initially delay by time
builder.get_object("btnOpenFile").set_sensitive(False)
builder.get_object("btnOff").set_sensitive(False)
self.btnAnalyze.set_sensitive(False)
# self.ani = animation.FuncAnimation(self.figure, self.update_plot, interval = 1000)
else:
self.loop.stop()
time.sleep(1)
self.client_1.close()
self.client_p.close()
print "stop connection"
time.sleep(2)
builder.get_object("txtFilePath").set_text(export_csv_path)
builder.get_object("btnOpenFile").set_sensitive(True)
builder.get_object("btnOff").set_sensitive(True)
if self.oneLogged:
self.btnAnalyze.set_sensitive(True)
示例14: _run_single_client
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))
示例15: connect_modbus
def connect_modbus(modbus_ip, modbus_port):
try:
client = ModbusClient(modbus_ip, port=modbus_port)
except:
return None
if client.connect():
return client
return None