本文整理汇总了Python中pymodbus.client.sync.ModbusSerialClient.close方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusSerialClient.close方法的具体用法?Python ModbusSerialClient.close怎么用?Python ModbusSerialClient.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymodbus.client.sync.ModbusSerialClient
的用法示例。
在下文中一共展示了ModbusSerialClient.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [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()
示例2: main
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [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()
示例3: main
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [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()
示例4: testBasicSyncSerialClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [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))
示例5: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [as 别名]
class communication:
def __init__(self):
self.client = None
def connectToDevice(self, device):
"""Connection to the client - the method takes the IP address (as a string, e.g. '192.168.1.11') as an argument."""
self.client = ModbusSerialClient(method='rtu',port=device,stopbits=1, bytesize=8, baudrate=115200, timeout=0.2)
if not self.client.connect():
print "Unable to connect to %s" % device
return False
return True
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
self.client.write_registers(0x03E8, message, unit=0x0009)
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
response = self.client.read_holding_registers(0x07D0, numRegs, unit=0x0009)
#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
示例6: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [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
示例7: SynchronousRtuClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [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()
示例8: SynchronousAsciiClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [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()
示例9: testBasicSyncSerialClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [as 别名]
def testBasicSyncSerialClient(self):
''' Test the basic methods for the serial sync client'''
# receive/send
client = ModbusSerialClient()
client.socket = mockSocket()
self.assertEqual(0, client._send(None))
self.assertEqual(1, client._send('\x00'))
self.assertEqual('\x00', client._recv(1))
# connect/disconnect
self.assertTrue(client.connect())
client.close()
# already closed socket
client.socket = False
client.close()
self.assertEqual('ascii baud[19200]', str(client))
示例10: run_motor_gui_standalone
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [as 别名]
def run_motor_gui_standalone():
client = ModbusClient(method="rtu", port="/dev/ttyUSB0", stopbits=1, \
bytesize=8, parity='E', baudrate=9600, timeout=0.1)
# connect to the serial modbus server
connection = client.connect()
print("Connection = " + str(connection))
# Create and set up the GUI object
root = Tk()
root.title("WIFIS Motor Controller")
root.geometry("275x375")
#root.protocol("WM_DELETE_WINDOW", on_closing)
app = MainApplication(root,client)
root.mainloop()
# closes the underlying socket connection
client.close()
示例11: get_data
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [as 别名]
def get_data():
# choose the serial client
client = ModbusClient(method='rtu', port=args.tty, baudrate=9600, timeout=args.timeout)
client.connect()
log.debug(client)
# read the registers
# for information about modbus registers see doc TSMPPT.APP.Modbus.EN.10.2.pdf
rr = client.read_holding_registers(0,count=60,unit=1)
if rr == None:
client.close()
log.error("couldn't connect")
exit(1)
# scaling
v_scale = rr.registers[0] + rr.registers[1]/(2**16)
i_scale = rr.registers[2] + rr.registers[3]/(2**16)
# the stuff we want (the numbers are decimal but the registers are listed in hex)
data={}
data["batt-voltage" ] = ( rr.registers[24] * float(v_scale )) / (2**15) # 0x18
data["array-voltage" ] = ( rr.registers[27] * float(v_scale )) / (2**15) # 0x1b
data["batt-current" ] = ( rr.registers[28] * float(i_scale )) / (2**15) # 0x1c
data["array-current" ] = ( rr.registers[29] * float(i_scale )) / (2**15) # 0x1d
data["batt-temp" ] = rr.registers[37] # 0x25
data["power-out" ] = ( rr.registers[58] * float(v_scale)*float(i_scale)) / (2**17) # 0x3a
data["power-in" ] = ( rr.registers[59] * float(v_scale)*float(i_scale)) / (2**17) # 0x3b
# close the client
client.close()
# debug
log.info("got data from mppt via modbus")
log.debug(datetime.datetime.now())
for key in keys:
log.debug("%-15s : %.2f" % (key, data[key]))
return data
示例12: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [as 别名]
class modbusClient:
"""Class to carry out MODBUS read/write requests
Usage: Ensure all params are setup in the 'modbusSettings' file
Call 'openConnection' to connect to the assigned server
Use 'dataHandler' to read or write data to the server
Call 'closeConnection' to safely close the connection
"""
def __init__(self):
"""Load settings and connect to the designated slave"""
self.modbusCfg = yamlImport.importYAML("./cfg/modbusSettings.yaml")
if self.modbusCfg['logging'] == "enable":
self.log = self.__logging()
if self.__setupClient() == 0:
return 0
if self.openConnection() == 0:
return 0
def __logging(self):
"""Setup and enable logging on the client
:return: enabled log instance
"""
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)
return log
def __setupClient(self):
"""Setup MODBUS client object"""
if self.modbusCfg['method'] == "tcp":
try:
self.client = ModbusTcpClient(self.modbusCfg['ip'],\
self.modbusCfg['tcpPort'])
except:
raise
return 0
elif self.modbusCfg['method'] == "rtu":
try:
self.client = ModbusSerialClient(self.modbusCfg['method'],\
self.modbusCfg['rtuPort'],\
self.modbusCfg['stopbits'],\
self.modbusCfg['bytesize'],\
self.modbusCfg['parity'],\
self.modbusCfg['baudrate'],\
self.modbusCfg['timeout'])
except:
raise
return 0
else:
raise NameError("Unsupported method")
return 0
def openConnection(self):
"""Attempt connection with the MODBUS server"""
for i in range(3):
if self.client.connect() == True:
return 1
else:
print "Attempt " + str(i) + " failed"
if i == 2:
raise IOError("Failed to connect to specified server")
return 0
time.sleep(0.5)
def closeConnection(self):
"""Close connection with the MODBUS server"""
try:
self.client.close()
except:
print("Error - See log for details")
return 0
return 1
def dataHandler(self, op, reg, addr, length=None, data=None, encoding=1):
"""Handle the MODBUS read/write requests and pass to the appropriate function
Arguments:
:param op: Operation to perform (R/W)
:param reg: Modbus register to access (1-4)
:param addr: Address to start operation at
:type op: string
:type reg: int
:type addr: int
Keyword Arguments:
:param length: Length of registers to read (default None)
:param data: Data to write to the slave
:type length: int
:type data: list
:return: List containing the requested data or confimation of send.
#.........这里部分代码省略.........
示例13: SenseAirDevice
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [as 别名]
class SenseAirDevice(object):
def __init__(self):
#---------------------------------------------------------------------------#
# This will simply send everything logged to console
#---------------------------------------------------------------------------#
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
self.client = None
def connect(self, deviceName):
self.client = ModbusSerialClient(method='rtu',port=deviceName,stopbits=1, bytesize=8, baudrate=9600, timeout=0.2)
if not self.client.connect():
rospy.logerr("Unable to connect to %s", device)
return False
return True
def close(self):
self.client.close()
# Not working right now
def getDeviceIdentification(self, objectId):
rq = ReadDeviceInformationRequest(read_code=4, object_id=objectId, unit=0xFE)
#rospy.loginfo("encoded: %h", encoded[0])
rr = self.client.execute(rq)
print rr
return ""
if rr is None:
rospy.logerr("No response from device")
return None
if rr.function_code < 0x80: # test that we are not an error
return rr.information[0]
#vendor_name = rr.information[0]
#product_code = rr.information[1]
#code_revision = rr.information[2]
#rospy.loginfo("vendor: %s", vendor_name)
#rospy.loginfo("product code: %s", product_code)
#rospy.loginfo("revision: %s", code_revision)
else:
rospy.logwarn("error reading device identification: %h", rr.function_code)
def getVendor(self):
vendor = self.getDeviceIdentification(0)
print vendor
def readCO2(self):
response = self.client.read_input_registers(address=3, count=1, unit=0xFE )
return response.getRegister(0)
def readTemperature(self):
response = self.client.read_input_registers(address=4, count=1, unit=0xFE )
return response.getRegister(0)*100.0
def sendCommand(self, data):
#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
self.client.write_registers(0x03E8, message, unit=0x0009)
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
response = self.client.read_holding_registers(0x07D0, numRegs, unit=0x0009)
#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
示例14: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [as 别名]
class comClient:
def __init__(self):
self.__parseConfig()
# Configure logging on the client
logging.basicConfig()
self.log = logging.getLogger()
# Change to DEBUG for full information during runtime
self.log.setLevel(logging.INFO)
# Setup and Open the connection
self.client = ModbusClient(**self.comSettings)
def __parseConfig(self):
try:
with open("../../cfg/connection.yaml", "r") as f: # safely opens the file and gets the text
config = yaml.load(f) # parses the data into python
self.comSettings = config # saves config to member variable
except IOError:
print ("Failed to set config from file. Falling back to default values:")
self.comSettings = {
"method": "rtu",
"port": "COM3", # FALL BACK VALUES ONLY
"stopbits": 1,
"bytesize": 8,
"parity": "N",
"baudrate": 9600,
"timeout": 1,
}
def dataHandler(self, operation, *data):
if operation == "r":
for i in range(3):
r = self.__readData() # Attempt to read MODBUS data
if r != IOError: # If success, carry on
break
elif i == 2: # Retry 3 times on failure
raise SystemExit("Modbus Error: Failed 3 Attemps")
time.sleep(5)
return r
elif operation == "w":
try:
self.__writeData(data[0]) # Attempt to write MODBUS data
except IndexError:
raise SystemExit("No data passed to write!")
return
else:
raise ValueError("Invalid Operation")
def __readData(self):
# Function to write data to controller
try:
self.client.connect()
# REMEMBER: Controller is unit 0x01
r = self.client.read_holding_registers(0, 4, unit=0x01)
self.client.close()
return r
except:
print "Modbus Error: Read Connection Failed"
return IOError
def __writeData(self, op):
# Set to write data to the controller output (MODBUS HR 3)
self.client.connect()
w = self.client.write_register(3, op, unit=0x01)
self.client.close()
return w
示例15: ModbusClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import close [as 别名]
"""
import time # For sleep functionality
import logging # For detailed error output
from pymodbus.client.sync import ModbusSerialClient \
as ModbusClient # Import MODBUS support class
comSettings = {
"method" : 'rtu',
"port" : 'COM3',
"stopbits" : 1,
"bytesize" : 8,
"parity" : 'N',
"baudrate" : 9600,
"timeout" : 1
}
logging.basicConfig() # Setup error logging
log = logging.getLogger() # Start logging
client = ModbusClient(**comSettings) # Setup connection object
client.connect() # Open the MODBUS connection
while(True):
client.write_register(3,1000,unit=0x01) # Write valve to 100%
time.sleep(4) # Sleep 4 seconds
client.write_register(3,0,unit=0x01) # Write valve to 0%
time.sleep(4) # Sleep 4 seconds
client.close() # Close the connection