本文整理汇总了Python中pymodbus.client.sync.ModbusTcpClient.close方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusTcpClient.close方法的具体用法?Python ModbusTcpClient.close怎么用?Python ModbusTcpClient.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymodbus.client.sync.ModbusTcpClient
的用法示例。
在下文中一共展示了ModbusTcpClient.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ModbusModule
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [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))
示例2: TestMbTcpClass0
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [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)
示例3: runModBus
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [as 别名]
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: main
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [as 别名]
def main():
### setup the client ###
ipaddr = '192.168.201.21'
port = 502
print 'Connecting to', (ipaddr, port)
client = ModbusTcpClient(ipaddr, port=port)
### fetch data ###
try:
reg = client.read_input_registers(0, 8) # data request
vlt = raw2volt(reg.registers) # convert bit to voltage (-10 -- 10[V])
except:
print 'Data fetch error. Finishing...'
client.close()
return
### convert voltage to engineering values ###
meas = vlt # TODO: CHANGE THIS
### show data ###
print 'Raw measurement:', vlt
print 'Engineering value:', meas
### finalizing ###
client.close()
示例5: wren_gw_modbus_read
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [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)};
示例6: wren_gw_modbus_write
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [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)};
示例7: TestMbTcpClass1
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [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]
示例8: setDeviceStatus
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [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
示例9: ModbusConnection
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [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)
示例10: get_point_sync
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [as 别名]
def get_point_sync(self, point_name):
register = self.point_map[point_name]
client = SyncModbusClient(self.ip_address, port=self.port)
try:
result = register.get_state_sync(client)
except (ConnectionException, ModbusIOException, ModbusInterfaceException):
result = None
finally:
client.close()
return result
示例11: scan
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [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)
示例12: set_point
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [as 别名]
def set_point(self, point_name, value):
register = self.get_register_by_name(point_name)
client = SyncModbusClient(self.ip_address, port=self.port)
result = None
try:
result = register.set_state(client, value)
except (ConnectionException, ModbusIOException, ModbusInterfaceException):
result = None
finally:
client.close()
return result
示例13: run
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [as 别名]
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
示例14: main
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [as 别名]
def main(argv):
syntax = os.path.basename(__file__) + " -p <first port> -n <number of servers> -i <ip:first port of pump server>"
tcp_port = 502
inj_tcp = "localhost:502"
no_server = 1
try:
opts = getopt.getopt(argv, "hp:n:i:", ["port=", "noserver=","injport="])[0]
except getopt.GetoptError:
print syntax
sys.exit(1)
if len(opts) < 1:
print syntax
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print syntax
sys.exit()
elif opt in ("-i", "--injport"):
inj_tcp = arg
elif opt in ("-p", "--port"):
tcp_port = int(arg)
elif opt in ("-n", "--noserver"):
no_server = int(arg)
port = tcp_port
context_list = []
identity_list = []
address_list = []
splitted = inj_tcp.split(":")
ip_pump = splitted[0]
port_pump = int(splitted[1])
p_prev_client = None
for srv in range(no_server):
p_client = ModbusClient(ip_pump, port=port_pump)
ret = p_client.connect()
if ret:
log.info("connection ok on {0}:{1}".format(ip_pump,port_pump))
p_client.close()
else:
p_client = p_prev_client
log.info("Keep the previous pump on {0}:{1}".format(ip_pump,port_pump-1))
port_pump += 1
address_list.append(("127.0.0.1", port))
port += 1
context = context_factory()
context_list.append(context)
identity_list.append(identity_factory())
time = 1 # 1 seconds delay
loop = LoopingCall(f=updating_writer, a=(context,srv,p_client))
p_prev_client = p_client
loop.start(time, now=False) # initially delay by time
StartMultipleTcpServers(context_list, identity_list, address_list)
示例15: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import close [as 别名]
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